├── .gitmodules ├── LICENSE ├── Makefile ├── README.md ├── eval ├── README.md └── eval.py └── src ├── cwt.cc ├── cwt.h ├── cxxopts.hpp ├── event.h ├── fast_dtw.cc ├── fast_dtw.h ├── hdf5_tools.hpp ├── khash.h ├── kseq.h ├── nanoflann.hpp ├── output_tools.h ├── pore_model.cc ├── pore_model.h ├── sequence_batch.cc ├── sequence_batch.h ├── sigmap.cc ├── sigmap.h ├── sigmap_adaptor.h ├── signal_batch.cc ├── signal_batch.h ├── spatial_index.cc ├── spatial_index.h └── utils.h /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "extern/hdf5"] 2 | path = extern/hdf5 3 | url = https://github.com/HDFGroup/hdf5.git 4 | branch = 1.10/master 5 | ignore = dirty 6 | [submodule "extern/kmer_models"] 7 | path = extern/kmer_models 8 | url = https://github.com/nanoporetech/kmer_models.git 9 | [submodule "extern/slow5lib"] 10 | path = extern/slow5lib 11 | url = https://github.com/hasindu2008/slow5lib 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | Sigmap: a streaming method for mapping nanopore raw signals 635 | Copyright (C) 2020 Haowen Zhang 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Sigmap Copyright (C) 2020 Haowen Zhang 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | cpp_source=sequence_batch.cc signal_batch.cc pore_model.cc cwt.cc spatial_index.cc sigmap.cc 2 | src_dir=src 3 | objs_dir=objs 4 | objs+=$(patsubst %.cc,$(objs_dir)/%.o,$(cpp_source)) 5 | 6 | project_dir = $(shell pwd) 7 | HDF5_DIR ?= ${project_dir}/extern/hdf5/build 8 | HDF5_INCLUDE_DIR ?= ${HDF5_DIR}/include 9 | HDF5_LIB_DIR ?= ${HDF5_DIR}/lib 10 | HDF5_LIB ?= hdf5 11 | SLOW5_DIR ?= ${project_dir}/extern/slow5lib/ 12 | SLOW5_INCLUDE_DIR ?= ${SLOW5_DIR}/include 13 | SLOW5_LIB_DIR ?= ${SLOW5_DIR}/lib 14 | 15 | cxx=${CXX} 16 | cxxflags=-std=c++11 -Wall -O3 -fopenmp -march=native -I${HDF5_INCLUDE_DIR} -I${SLOW5_INCLUDE_DIR} 17 | ldflags=${HDF5_LIB_DIR}/lib${HDF5_LIB}.a ${SLOW5_LIB_DIR}/libslow5.a -lm -lz -ldl 18 | 19 | exec=sigmap 20 | 21 | all: hdf5 slow5 check_hdf5 check_slow5 dir $(exec) 22 | Sigmap: check_slow5 check_hdf5 dir $(exec) 23 | 24 | check_hdf5: 25 | @[ -f "${HDF5_INCLUDE_DIR}/H5pubconf.h" ] || { echo "HDF5 headers not found" >&2; exit 1; } 26 | @[ -f "${HDF5_LIB_DIR}/lib${HDF5_LIB}.so" ] || [ -f "${HDF5_LIB_DIR}/lib${HDF5_LIB}.a" ] || { echo "HDF5 library not found" >&2; exit 1; } 27 | 28 | check_slow5: 29 | @[ -f "${SLOW5_INCLUDE_DIR}/slow5/slow5.h" ] || { echo "SLOW5 headers not found" >&2; exit 1; } 30 | @[ -f "${SLOW5_LIB_DIR}/libslow5.so" ] || [ -f "${SLOW5_LIB_DIR}/libslow5.a" ] || { echo "SLOW5 library not found" >&2; exit 1; } 31 | 32 | dir: 33 | mkdir -p $(objs_dir) 34 | 35 | hdf5: 36 | cd extern/hdf5;\ 37 | mkdir build;\ 38 | ./configure --enable-threadsafe --disable-hl --prefix="${HDF5_DIR}";\ 39 | make -j;\ 40 | make install 41 | 42 | slow5: 43 | make -C ${SLOW5_DIR} 44 | 45 | $(exec): $(objs) 46 | $(cxx) $(cxxflags) $(objs) -o $(exec) $(ldflags) 47 | 48 | $(objs_dir)/%.o: $(src_dir)/%.cc 49 | $(cxx) $(cxxflags) -c $< -o $@ 50 | 51 | .PHONY: clean 52 | clean: 53 | -rm -r $(exec) $(objs_dir) 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sigmap 2 | Sigmap is a streaming method for mapping raw nanopore signal to reference genomes. 3 | 4 | ## Installation 5 | First get the repo with submodules (make sure you use `--recursive`): 6 | ``` 7 | git clone --recursive git@github.com:haowenz/sigmap.git 8 | ``` 9 | Make sure you have GCC version > 8. Then just run: 10 | ``` 11 | cd sigmap && make 12 | ``` 13 | 14 | ## Usage 15 | First, an index needs to be built for the reference using ONT pore models (as a submodule in the extern folder). We use yeast genome as an example: 16 | ``` 17 | ./sigmap -i -r yeast.fasta -p extern/kmer_models/r9.4_180mv_450bps_6mer/template_median68pA.model -o yeast_index 18 | ``` 19 | It will generate the index file *yeast_index.si*. Note that a genome point cloud file *yeast_index.pt* will also be saved. But it can also be generated very quickly on the fly every time before mapping. After index construction, yeast raw signals in fast5 format or blow5 format can be mapped using 20 | ``` 21 | ./sigmap -m -r yeast.fasta -p extern/kmer_models/r9.4_180mv_450bps_6mer/template_median68pA.model -x yeast_index -s /path/to/yeast/fast5_or_blow5/dir -o yeast_mapping.paf -t 4 22 | ``` 23 | This command map all the fast5 and blow5 reads in `/path/to/yeast/fast5_or_blow5/dir` and its subdirectories to the yeast genome using 4 threads. The output will be saved to `yeast_mapping.paf` in a modified PAF format used by [Uncalled](https://github.com/skovaka/UNCALLED). 24 | 25 | Many other parameters can be found in the help information: 26 | ``` 27 | ./sigmap -h 28 | ``` 29 | 30 | It is possible that your reads in fast5 files are compressed with the [VBZ compression](https://github.com/nanoporetech/vbz_compression) from Nanopore. Then you have to download the proper HDF5 plugin from [here](https://github.com/nanoporetech/vbz_compression/releases) and make sure it can be found by your HDF5 library: 31 | ``` 32 | export HDF5_PLUGIN_PATH=/path/to/hdf5/plugins/lib 33 | ``` 34 | 35 | ## Getting help 36 | If you encounter bugs or have further questions or requests, you can raise an issue at the [issue page](https://github.com/haowenz/sigmap/issues) or contact me by email hwzhang@gatech.edu. 37 | 38 | ## Citing Sigmap 39 | If you use Sigmap, please cite: 40 | 41 | Zhang, H., Li, H., Jain, C., Cheng, H., Au, K. F., Li, H., & Aluru, S. (2021). Real-time mapping of nanopore raw signals. Bioinformatics, 37(Supplement_1), i477-i483. https://doi.org/10.1093/bioinformatics/btab264 42 | -------------------------------------------------------------------------------- /eval/README.md: -------------------------------------------------------------------------------- 1 | # Evaluation 2 | We provide the evaluation script to reproduce the results in the paper. 3 | 4 | ## Usage 5 | First, run minimap2 to get a groud truth for real sequencing data. Then run Uncalled and Sigmap with parameters specified in the paper and get the PAF outputs. Run [pafstats](https://github.com/skovaka/UNCALLED/blob/master/uncalled/pafstats.py) on the alignment outputs and get the read classification results in PAF. Finally, run our evaluation script and get the accuracy statistics. 6 | 7 | Note that pafstats only counts the mapping time of mapped reads and by default extend the mapping intervals by 1.5x. While in our evalution, we count the mapping time of all the reads in the groud truth and change pafstats to not extend the mapping intervals. 8 | -------------------------------------------------------------------------------- /eval/eval.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import argparse 4 | import subprocess 5 | import fileinput 6 | 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | from matplotlib import colors 10 | from matplotlib.ticker import PercentFormatter 11 | 12 | from statistics import median 13 | from statistics import mean 14 | 15 | if (len(sys.argv) < 4): 16 | print("usage: eval.py uncalled_ann.paf sigmap_ann.paf output_prefix") 17 | sys.exit(1) 18 | 19 | fps = [] 20 | for tool in [1, 2]: 21 | fps.append(open(sys.argv[tool])) 22 | 23 | uncalled_tp = 0 24 | uncalled_fp = 0 25 | uncalled_fn = 0 26 | uncalled_tn = 0 27 | 28 | uncalled_chunk = [] 29 | uncalled_time_per_read = [] 30 | for line in fps[0]: 31 | cols = line.rstrip().split() 32 | mt = float(cols[14].split(":")[2]) 33 | if (cols[15].split(":")[2] != 'na'): 34 | uncalled_time_per_read.append(mt) 35 | if (cols[15].split(":")[2] == 'tp'): 36 | uncalled_tp += 1 37 | if (cols[15].split(":")[2] == 'fp'): 38 | uncalled_fp += 1 39 | if (cols[15].split(":")[2] == 'fn'): 40 | uncalled_fn += 1 41 | if (cols[15].split(":")[2] == 'tn'): 42 | uncalled_tn += 1 43 | print("Uncalled TP: " + str(uncalled_tp)) 44 | print("Uncalled FP: " + str(uncalled_fp)) 45 | print("Uncalled FN: " + str(uncalled_fn)) 46 | print("Uncalled TN: " + str(uncalled_tn)) 47 | uncalled_preciosion = uncalled_tp / (uncalled_tp + uncalled_fp) 48 | print("Uncalled precision: " + str(uncalled_preciosion)) 49 | uncalled_recall = uncalled_tp / (uncalled_tp + uncalled_fn) 50 | print("Uncalled recall: " + str(uncalled_recall)) 51 | print("Uncalled F-1 score: " + str(2 * uncalled_preciosion * uncalled_recall / (uncalled_preciosion + uncalled_recall))) 52 | print("Mean time per read : " + str(mean(uncalled_time_per_read))) 53 | print("Median time per read : " + str(median(uncalled_time_per_read))) 54 | print("#Done with uncalled\n") 55 | 56 | sigmap_tp = 0 57 | sigmap_fp = 0 58 | sigmap_fn = 0 59 | sigmap_tn = 0 60 | 61 | sigmap_time_per_chunk = [] 62 | sigmap_time_per_read = [] 63 | for line in fps[1]: 64 | cols = line.rstrip().split() 65 | if (len(cols) == 24): 66 | mt = float(cols[12].split(":")[2]) 67 | if (cols[23].split(":")[2] != 'na'): 68 | sigmap_time_per_read.append(mt) 69 | chunk = int(cols[13].split(":")[2]) 70 | cm = int(cols[15].split(":")[2]) 71 | nc = int(cols[16].split(":")[2]) 72 | s1 = float(cols[17].split(":")[2]) 73 | s2 = float(cols[18].split(":")[2]) 74 | sm = float(cols[19].split(":")[2]) 75 | ad = float(cols[20].split(":")[2]) 76 | at = float(cols[21].split(":")[2]) 77 | aq = float(cols[22].split(":")[2]) 78 | if (cols[23].split(":")[2] == 'tp'): 79 | sigmap_tp += 1 80 | sigmap_time_per_chunk.append(mt / chunk) 81 | if (cols[23].split(":")[2] == 'fp'): 82 | sigmap_fp += 1 83 | sigmap_time_per_chunk.append(mt / chunk) 84 | if (cols[23].split(":")[2] == 'fn'): 85 | sigmap_fn += 1 86 | sigmap_time_per_chunk.append(mt / chunk) 87 | if (cols[23].split(":")[2] == 'tn'): 88 | sigmap_tn += 1 89 | sigmap_time_per_chunk.append(mt / chunk) 90 | if (len(cols) == 15): 91 | mt = float(cols[12].split(":")[2]) 92 | if (cols[14].split(":")[2] != 'na'): 93 | sigmap_time_per_read.append(mt) 94 | if (cols[14].split(":")[2] == 'fn'): 95 | sigmap_fn += 1 96 | if (cols[14].split(":")[2] == 'tn'): 97 | sigmap_tn += 1 98 | print("Sigmap TP: " + str(sigmap_tp)) 99 | print("Sigmap FP: " + str(sigmap_fp)) 100 | print("Sigmap FN: " + str(sigmap_fn)) 101 | print("Sigmap TN: " + str(sigmap_tn)) 102 | sigmap_preciosion = sigmap_tp / (sigmap_tp + sigmap_fp) 103 | print("Sigmap precision: " + str(sigmap_preciosion)) 104 | sigmap_recall = sigmap_tp / (sigmap_tp + sigmap_fn) 105 | print("Sigmap recall: " + str(sigmap_recall)) 106 | print("Sigmap F-1 score: " + str(2 * sigmap_preciosion * sigmap_recall / (sigmap_preciosion + sigmap_recall))) 107 | print("Mean time per chunk : " + str(mean(sigmap_time_per_chunk))) 108 | print("Median time per chunk : " + str(median(sigmap_time_per_chunk))) 109 | print("Mean time per read : " + str(mean(sigmap_time_per_read))) 110 | print("Median time per read : " + str(median(sigmap_time_per_read))) 111 | print("#Done with sigmap") 112 | 113 | for fp in fps: 114 | fp.close() 115 | -------------------------------------------------------------------------------- /src/cwt.h: -------------------------------------------------------------------------------- 1 | #ifndef CWT_H_ 2 | #define CWT_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | namespace sigmap { 10 | // FFT 11 | #ifndef fft_type 12 | #define fft_type float 13 | #endif 14 | 15 | #define PI2 6.28318530717958647692528676655900577 16 | 17 | typedef struct fft_set *fft_object; 18 | 19 | typedef struct fft_t { 20 | fft_type re; 21 | fft_type im; 22 | } fft_data; 23 | 24 | struct fft_set { 25 | int N; 26 | int sgn; 27 | int factors[64]; 28 | int lf; 29 | int lt; 30 | fft_data twiddle[1]; 31 | }; 32 | 33 | fft_object fft_init(int N, int sgn); 34 | void fft_exec(fft_object obj, fft_data *inp, fft_data *oup); 35 | void free_fft(fft_object object); 36 | 37 | // CWT 38 | #ifndef cplx_type 39 | #define cplx_type float 40 | #endif 41 | 42 | #ifndef cwt_type 43 | #define cwt_type float 44 | #endif 45 | 46 | typedef struct cplx_t { 47 | cplx_type re; 48 | cplx_type im; 49 | } cplx_data; 50 | 51 | typedef struct cwt_set *cwt_object; 52 | 53 | struct cwt_set { 54 | char wave[10]; // Wavelet - morl/morlet,paul,dog/dgauss 55 | int siglength; // Length of Input Data 56 | int J; // Total Number of Scales 57 | cwt_type s0; // Smallest scale. It depends on the sampling rate. s0 <= 2 * dt 58 | // for most wavelets 59 | cwt_type dt; // Sampling Rate 60 | cwt_type dj; // Separation between scales. eg., scale = s0 * 2 ^ ( [0:N-1] 61 | // *dj ) or scale = s0 *[0:N-1] * dj 62 | char type[10]; // Scale Type - Power or Linear 63 | int pow; // Base of Power in case type = pow. Typical value is pow = 2 64 | int sflag; 65 | int pflag; 66 | int npad; 67 | int mother; 68 | cwt_type m; // Wavelet parameter param 69 | cwt_type smean; // Input Signal mean 70 | cplx_data *output; 71 | cwt_type *scale; 72 | cwt_type *period; 73 | cwt_type *coi; 74 | cwt_type params[0]; 75 | }; 76 | 77 | cwt_object cwt_init(const char *wave, cwt_type param, int siglength, 78 | cwt_type dt, int J); 79 | void setCWTScales(cwt_object wt, cwt_type s0, cwt_type dj, const char *type, 80 | int power); 81 | // void setCWTScaleVector(cwt_object wt, const double *scale, int J, double s0, 82 | // double dj); void setCWTPadding(cwt_object wt, int pad); 83 | void cwavelet(const cwt_type *y, int N, cwt_type dt, int mother, cwt_type param, 84 | cwt_type s0, cwt_type dj, int jtot, int npad, cwt_type *wave, 85 | cwt_type *scale, cwt_type *period, cwt_type *coi); 86 | void cwt(cwt_object wt, const cwt_type *inp); 87 | void cwt_free(cwt_object object); 88 | void cwt_summary(cwt_object wt); 89 | // void icwt(cwt_object wt, double *cwtop); 90 | 91 | // int getCWTScaleLength(int N); 92 | } // namespace sigmap 93 | 94 | #endif // CWT_H_ 95 | -------------------------------------------------------------------------------- /src/event.h: -------------------------------------------------------------------------------- 1 | #ifndef EVENT_H_ 2 | #define EVENT_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include "utils.h" 14 | 15 | namespace sigmap { 16 | struct Event { 17 | uint64_t start; 18 | size_t length; 19 | float mean; 20 | float stdv; 21 | }; 22 | 23 | struct DetectorArgs { 24 | size_t window_length1; 25 | size_t window_length2; 26 | float threshold1; 27 | float threshold2; 28 | float peak_height; 29 | }; 30 | 31 | static DetectorArgs const event_detection_defaults = { 32 | .window_length1 = 3, 33 | .window_length2 = 6, 34 | .threshold1 = 4.30265f, // 4.60409f,//1.4f, 35 | .threshold2 = 2.57058f, // 3.16927f,//9.0f, 36 | .peak_height = 1.0f // 0.2f 37 | }; 38 | 39 | static DetectorArgs const event_detection_rna = {.window_length1 = 7, 40 | .window_length2 = 14, 41 | .threshold1 = 2.5f, 42 | .threshold2 = 9.0f, 43 | .peak_height = 1.0f}; 44 | 45 | struct Detector { 46 | int DEF_PEAK_POS; 47 | float DEF_PEAK_VAL; 48 | float *signal_values; 49 | size_t signal_length; 50 | float threshold; 51 | size_t window_length; 52 | size_t masked_to; 53 | int peak_pos; 54 | float peak_value; 55 | bool valid_peak; 56 | }; 57 | 58 | static inline void ComputePrefixSumAndPrefixSumSquares( 59 | const float *data, size_t data_length, std::vector &prefix_sum, 60 | std::vector &prefix_sum_square) { 61 | assert(data_length > 0); 62 | prefix_sum.emplace_back(0.0f); 63 | prefix_sum_square.emplace_back(0.0f); 64 | for (size_t i = 0; i < data_length; ++i) { 65 | prefix_sum.emplace_back(prefix_sum[i] + data[i]); 66 | prefix_sum_square.emplace_back(prefix_sum_square[i] + data[i] * data[i]); 67 | } 68 | } 69 | 70 | static inline void ComputeTStat(const float *prefix_sum, 71 | const float *prefix_sum_square, 72 | size_t signal_length, size_t window_length, 73 | std::vector &tstat) { 74 | const float eta = FLT_MIN; 75 | // Quick return: 76 | // t-test not defined for number of points less than 2 77 | // need at least as many points as twice the window length 78 | if (signal_length < 2 * window_length || window_length < 2) { 79 | for (size_t i = 0; i < signal_length; ++i) { 80 | tstat.emplace_back(0.0f); 81 | } 82 | return; 83 | } 84 | // fudge boundaries 85 | for (size_t i = 0; i < window_length; ++i) { 86 | tstat.emplace_back(0.0f); 87 | } 88 | // get to work on the rest 89 | for (size_t i = window_length; i <= signal_length - window_length; ++i) { 90 | float sum1 = prefix_sum[i]; 91 | float sumsq1 = prefix_sum_square[i]; 92 | if (i > window_length) { 93 | sum1 -= prefix_sum[i - window_length]; 94 | sumsq1 -= prefix_sum_square[i - window_length]; 95 | } 96 | float sum2 = prefix_sum[i + window_length] - prefix_sum[i]; 97 | float sumsq2 = prefix_sum_square[i + window_length] - prefix_sum_square[i]; 98 | float mean1 = sum1 / window_length; 99 | float mean2 = sum2 / window_length; 100 | float combined_var = sumsq1 / window_length - mean1 * mean1 + 101 | sumsq2 / window_length - mean2 * mean2; 102 | // Prevent problem due to very small variances 103 | combined_var = fmaxf(combined_var, eta); 104 | // t-stat 105 | // Formula is a simplified version of Student's t-statistic for the 106 | // special case where there are two samples of equal size with 107 | // differing variance 108 | const float delta_mean = mean2 - mean1; 109 | tstat.emplace_back(fabs(delta_mean) / sqrt(combined_var / window_length)); 110 | } 111 | // fudge boundaries 112 | for (size_t i = 0; i < window_length; ++i) { 113 | tstat.emplace_back(0.0f); 114 | } 115 | } 116 | 117 | static inline void GeneratePeaksUsingMultiWindows(Detector *short_detector, 118 | Detector *long_detector, 119 | const float peak_height, 120 | std::vector &peaks) { 121 | assert(short_detector->signal_length == long_detector->signal_length); 122 | size_t ndetector = 2; 123 | Detector *detectors[ndetector]; // = {short_detector, long_detector}; 124 | detectors[0] = short_detector; 125 | detectors[1] = long_detector; 126 | peaks.reserve(short_detector->signal_length); 127 | for (size_t i = 0; i < short_detector->signal_length; i++) { 128 | for (size_t k = 0; k < ndetector; k++) { 129 | Detector *detector = detectors[k]; 130 | // Carry on if we've been masked out 131 | if (detector->masked_to >= i) { 132 | continue; 133 | } 134 | float current_value = detector->signal_values[i]; 135 | if (detector->peak_pos == detector->DEF_PEAK_POS) { 136 | // CASE 1: We've not yet recorded a maximum 137 | if (current_value < detector->peak_value) { 138 | // Either record a deeper minimum... 139 | detector->peak_value = current_value; 140 | } else if (current_value - detector->peak_value > 141 | peak_height) { // TODO(Haowen): this might cause overflow, 142 | // need to fix this 143 | // ...or we've seen a qualifying maximum 144 | detector->peak_value = current_value; 145 | detector->peak_pos = i; 146 | // otherwise, wait to rise high enough to be considered a peak 147 | } 148 | } else { 149 | // CASE 2: In an existing peak, waiting to see if it is good 150 | if (current_value > detector->peak_value) { 151 | // Update the peak 152 | detector->peak_value = current_value; 153 | detector->peak_pos = i; 154 | } 155 | // Dominate other tstat signals if we're going to fire at some point 156 | if (detector == short_detector) { 157 | if (detector->peak_value > detector->threshold) { 158 | long_detector->masked_to = 159 | detector->peak_pos + detector->window_length; 160 | long_detector->peak_pos = long_detector->DEF_PEAK_POS; 161 | long_detector->peak_value = long_detector->DEF_PEAK_VAL; 162 | long_detector->valid_peak = false; 163 | } 164 | } 165 | // Have we convinced ourselves we've seen a peak 166 | if (detector->peak_value - current_value > peak_height && 167 | detector->peak_value > detector->threshold) { 168 | detector->valid_peak = true; 169 | } 170 | // Finally, check the distance if this is a good peak 171 | if (detector->valid_peak && 172 | (i - detector->peak_pos) > detector->window_length / 2) { 173 | // Emit the boundary and reset 174 | peaks.emplace_back(detector->peak_pos); 175 | detector->peak_pos = detector->DEF_PEAK_POS; 176 | detector->peak_value = current_value; 177 | detector->valid_peak = false; 178 | } 179 | } 180 | } 181 | } 182 | } 183 | 184 | static inline Event CreateEvent(size_t start, size_t end, 185 | const float *prefix_sum, 186 | const float *prefix_sum_square, 187 | size_t signal_length) { 188 | assert(start < signal_length); 189 | assert(end <= signal_length); 190 | Event event; 191 | event.start = start; 192 | event.length = end - start; 193 | event.mean = (prefix_sum[end] - prefix_sum[start]) / event.length; 194 | float deltasqr = prefix_sum_square[end] - prefix_sum_square[start]; 195 | float var = deltasqr / event.length - event.mean * event.mean; 196 | event.stdv = sqrtf(fmaxf(var, 0.0f)); 197 | return event; 198 | } 199 | 200 | static inline void CreateEvents(const size_t *peaks, uint32_t peak_size, 201 | const float *prefix_sum, 202 | const float *prefix_sum_square, 203 | size_t signal_length, 204 | std::vector &events) { 205 | // Count number of events found 206 | size_t num_events = 1; 207 | for (size_t i = 1; i < peak_size; ++i) { 208 | if (peaks[i] > 0 && peaks[i] < signal_length) { 209 | num_events++; 210 | } 211 | } 212 | // First event -- starts at zero 213 | events.emplace_back( 214 | CreateEvent(0, peaks[0], prefix_sum, prefix_sum_square, signal_length)); 215 | // Other events -- peak[i-1] -> peak[i] 216 | for (size_t pi = 1; pi < num_events - 1; pi++) { 217 | events.emplace_back(CreateEvent(peaks[pi - 1], peaks[pi], prefix_sum, 218 | prefix_sum_square, signal_length)); 219 | } 220 | // Last event -- ends at signal_length 221 | events.emplace_back(CreateEvent(peaks[num_events - 2], signal_length, 222 | prefix_sum, prefix_sum_square, 223 | signal_length)); 224 | } 225 | 226 | static inline void DetectEvents( 227 | const float *signal_values, size_t signal_length, 228 | const DetectorArgs &edparam, std::vector &prefix_sum, 229 | std::vector &prefix_sum_square, std::vector &tstat1, 230 | std::vector &tstat2, std::vector &peaks, 231 | std::vector &events) { 232 | prefix_sum.reserve(signal_length + 1); 233 | prefix_sum_square.reserve(signal_length + 1); 234 | ComputePrefixSumAndPrefixSumSquares(signal_values, signal_length, prefix_sum, 235 | prefix_sum_square); 236 | ComputeTStat(prefix_sum.data(), prefix_sum_square.data(), signal_length, 237 | edparam.window_length1, tstat1); 238 | ComputeTStat(prefix_sum.data(), prefix_sum_square.data(), signal_length, 239 | edparam.window_length2, tstat2); 240 | Detector short_detector = {.DEF_PEAK_POS = -1, 241 | .DEF_PEAK_VAL = FLT_MAX, 242 | .signal_values = tstat1.data(), 243 | .signal_length = signal_length, 244 | .threshold = edparam.threshold1, 245 | .window_length = edparam.window_length1, 246 | .masked_to = 0, 247 | .peak_pos = -1, 248 | .peak_value = FLT_MAX, 249 | .valid_peak = false}; 250 | Detector long_detector = {.DEF_PEAK_POS = -1, 251 | .DEF_PEAK_VAL = FLT_MAX, 252 | .signal_values = tstat2.data(), 253 | .signal_length = signal_length, 254 | .threshold = edparam.threshold2, 255 | .window_length = edparam.window_length2, 256 | .masked_to = 0, 257 | .peak_pos = -1, 258 | .peak_value = FLT_MAX, 259 | .valid_peak = false}; 260 | GeneratePeaksUsingMultiWindows(&short_detector, &long_detector, 261 | edparam.peak_height, peaks); 262 | CreateEvents(peaks.data(), peaks.size(), prefix_sum.data(), 263 | prefix_sum_square.data(), signal_length, events); 264 | #ifdef DEBUG 265 | std::cerr << "Detected " << events.size() << " events.\n"; 266 | #endif 267 | } 268 | } // namespace sigmap 269 | 270 | #endif // EVENT_H_ 271 | -------------------------------------------------------------------------------- /src/fast_dtw.cc: -------------------------------------------------------------------------------- 1 | #include "fast_dtw.h" 2 | namespace sigmap { 3 | void reduce_by_half(const float *signal, size_t length, float *signal_reduced, size_t &reduced_length){ 4 | reduced_length = 0; 5 | for (size_t i = 0; i < length - length % 2; i += 2){ 6 | signal_reduced[reduced_length] = (signal[i] + signal[i + 1]) / 2; 7 | reduced_length++; 8 | } 9 | } 10 | 11 | void expand_window(std::vector> &path,size_t target_length,size_t query_length,int radius,std::vector> &window) { 12 | std::set path_set; 13 | for (size_t i = 0;i=0)&(new_query_coord>=0)&(new_target_coord window_set; 25 | for (std::set::iterator it=path_set.begin() ;it!=path_set.end();it++){ 26 | for (int x=0;x<2;x++){ 27 | for (int y=0;y<2;y++){ 28 | ssize_t new_target_coord = it->target_coord*2+x; 29 | ssize_t new_query_coord = it->query_coord*2+y; 30 | if ((new_target_coord>=0)&(new_query_coord>=0)&(new_target_coord>().swap(window); 40 | size_t last_target_coord = window_set.begin()->target_coord; 41 | window.push_back(std::vector()); 42 | for (std::set::iterator it=window_set.begin() ;it!=window_set.end();it++){ 43 | if (last_target_coord!=it->target_coord){ 44 | window.push_back(std::vector()); 45 | last_target_coord = it->target_coord; 46 | } 47 | window.back().push_back(Coordinate(it->target_coord,it->query_coord)); 48 | } 49 | } 50 | 51 | void generate_path(std::vector> &path_matrix,std::vector> &window,std::map> &coord_to_window_index_map,std::vector> &path,ssize_t end_target_position){ 52 | //trace back 53 | size_t row = end_target_position; 54 | size_t col = window[end_target_position].size()-1; 55 | //clear the path 56 | std::vector>().swap(path); 57 | Coordinate coord = window[row][col]; 58 | while (coord.query_coord != 0) { 59 | coord = window[row][col]; 60 | path.push_back(std::make_pair(Coordinate(coord.target_coord,coord.query_coord),path_matrix[row][col])); 61 | //coordinate shift when trace back 62 | int query_shift[] = {-1,-1,-1,0}; 63 | int target_shift[] = {-1,0,0,-1}; 64 | coord.query_coord += query_shift[path_matrix[row][col]]; 65 | coord.target_coord += target_shift[path_matrix[row][col]]; 66 | std::pair index = coord_to_window_index_map[coord]; 67 | row = index.first; 68 | col = index.second; 69 | } 70 | path.push_back(std::make_pair(window[row][col],path_matrix[row][col])); 71 | std::reverse(path.begin(),path.end()); 72 | } 73 | 74 | float DTW(const float *target_signal, size_t target_length, const float *query_signal, size_t query_length, std::vector> &window,std::vector> &path,ssize_t &end_target_position){ 75 | float min_dtw_distance = std::numeric_limits::max(); 76 | float skip_target_cost = 2; 77 | float skip_query_cost = 2; 78 | std::map> coord_to_window_index_map; 79 | if ((window.empty())){ 80 | for (size_t i = 0; i < target_length; i++){ 81 | window.push_back(std::vector()); 82 | for (size_t j = 0; j < query_length; j++){ 83 | window.back().push_back(Coordinate(i,j)); 84 | } 85 | } 86 | } 87 | 88 | //path_matrix: 0 -> one-to-one map; 1 -> one base to multi signal; 2 -> skip one signal; 3 -> skip one base; 89 | //initialize path_matrix and coord_to_window_index_map 90 | std::vector> path_matrix(window.size(),std::vector()); 91 | for (size_t i = 0; i < window.size(); i++){ 92 | path_matrix[i]= std::vector(window[i].size(),0); 93 | for (size_t j = 0; j < window[i].size(); j++){ 94 | coord_to_window_index_map[window[i][j]] = std::make_pair(i,j); 95 | } 96 | } 97 | std::vector previous_row(query_length + 1, std::numeric_limits::max()); 98 | std::vector current_row(query_length + 1, std::numeric_limits::max()); 99 | previous_row[0] = 0; 100 | end_target_position = -1; 101 | size_t target_position; 102 | size_t query_position; 103 | for (size_t i = 0; i < window.size(); ++i){ 104 | // iterate to a new row (new signal on reference) 105 | current_row[0] = 0; 106 | for (size_t j = 0; j < window[i].size(); ++j){ 107 | target_position = window[i][j].target_coord + 1; 108 | query_position = window[i][j].query_coord + 1; 109 | float cost = std::abs(target_signal[target_position - 1] - query_signal[query_position - 1]); 110 | std::vector candidates; 111 | std::vector candidates_path_direction; 112 | //for the start position 113 | candidates = {previous_row[query_position-1]+cost,current_row[query_position-1]+cost,current_row[query_position-1]+skip_query_cost,previous_row[query_position]+skip_target_cost}; 114 | candidates_path_direction = {0,1,2,3}; 115 | // if ((target_position==1)&&(query_position==1)){ 116 | // candidates = {cost,skip_query_cost,skip_target_cost}; 117 | // candidates_path_direction = {0,2,3}; 118 | // } else if ((j>0) && (path_matrix[i][j-1]==3)){ 119 | // // if skip this base in the last step, one base to multi signal is not allowed 120 | // candidates = {previous_row[query_position-1]+cost,current_row[query_position-1]+skip_query_cost,previous_row[query_position]+skip_target_cost}; 121 | // candidates_path_direction = {0,2,3}; 122 | // } else { 123 | // candidates = {previous_row[query_position-1]+cost,current_row[query_position-1]+cost,current_row[query_position-1]+skip_query_cost,previous_row[query_position]+skip_target_cost}; 124 | // candidates_path_direction = {0,1,2,3}; 125 | // } 126 | int argmin_candidates = std::min_element( candidates.begin(),candidates.end()) - candidates.begin(); 127 | current_row[query_position] = candidates[argmin_candidates]; 128 | path_matrix[i][j] = candidates_path_direction[argmin_candidates]; 129 | } 130 | if ((query_position == query_length) && (current_row[query_position] < min_dtw_distance)) { 131 | min_dtw_distance = current_row[query_position]; 132 | end_target_position = i; 133 | } 134 | current_row.swap(previous_row); 135 | std::vector(query_length + 1, std::numeric_limits::max()).swap(current_row); 136 | } 137 | generate_path(path_matrix,window,coord_to_window_index_map,path,end_target_position); 138 | end_target_position = window[end_target_position][0].target_coord; 139 | return min_dtw_distance; 140 | } 141 | 142 | float _fastDTW(const float *target_signal, size_t target_length, const float *query_signal, size_t query_length, int radius,std::vector> &path,std::vector> &window, ssize_t &end_target_position){ 143 | int min_time_size = radius + 2; 144 | 145 | std::vector>().swap(window); 146 | if ((target_length < min_time_size) || (query_length < min_time_size)){ 147 | return DTW(target_signal, target_length, query_signal, query_length,window,path,end_target_position); 148 | } 149 | size_t target_reduced_length = 0; 150 | size_t query_reduced_length = 0; 151 | float target_reduced[target_length / 2 + 1]; 152 | float query_reduced[query_length / 2 + 1]; 153 | reduce_by_half(target_signal, target_length, target_reduced, target_reduced_length); 154 | reduce_by_half(query_signal, query_length, query_reduced, query_reduced_length); 155 | float dist = _fastDTW(target_reduced,target_reduced_length, query_reduced,query_reduced_length,radius,path,window,end_target_position); 156 | expand_window(path, target_length,query_length, radius,window); 157 | return DTW(target_signal, target_length, query_signal, query_length,window,path,end_target_position); 158 | } 159 | 160 | std::string print_alignment(std::vector> &path){ 161 | //path[i].second: 0 -> one-to-one map; 1 -> one base to multi signal; 2 -> skip one signal; 3 -> skip one base; 162 | std::string print_flags = "MMID"; 163 | if (path.empty()){ 164 | return ""; 165 | } 166 | std::vector per_base_cigar; 167 | size_t num_same_continuous_flag = 1; 168 | int last_flag; 169 | // for the first base to signal alignment 170 | if (path[0].second == 3){ 171 | per_base_cigar.push_back("1D"); 172 | last_flag = 3; 173 | } else { 174 | last_flag = path[0].second == 0 ? 1 : 2; 175 | } 176 | per_base_cigar.push_back(""); 177 | 178 | for (size_t i = 1; i < path.size(); ++i){ 179 | int flag = path[i].second; 180 | // if within one base,counting the continous same flag 181 | if ((flag == 1) || (flag == 2)){ 182 | if (last_flag == flag){ 183 | num_same_continuous_flag ++; 184 | } else { 185 | per_base_cigar.back() += std::to_string(num_same_continuous_flag) + print_flags[last_flag]; 186 | num_same_continuous_flag = 1; 187 | last_flag = flag; 188 | } 189 | } else { 190 | // if not within one base, finish the last base and adding new base 191 | per_base_cigar.back() += std::to_string(num_same_continuous_flag) + print_flags[last_flag]; 192 | if (flag == 0){ 193 | last_flag = 1; 194 | } else if (flag == 3){ 195 | // if skip one base 196 | last_flag = 3; 197 | } 198 | if (i != path.size() - 1){ 199 | per_base_cigar.push_back(""); 200 | num_same_continuous_flag = 1; 201 | } 202 | } 203 | } 204 | std::string cigar = ""; 205 | for (size_t i = 0; i < per_base_cigar.size(); ++i){ 206 | cigar += "(" + per_base_cigar[i] + ")"; 207 | } 208 | return cigar; 209 | } 210 | 211 | float fastDTW(const float *target_signal, size_t target_length, const float *query_signal, size_t query_length,int radius,ssize_t& end_target_position,std::string &cigar){ 212 | double real_start_time = GetRealTime(); 213 | std::vector> path; 214 | std::vector> window; 215 | float distance = _fastDTW(target_signal,target_length,query_signal,query_length,radius,path,window,end_target_position); 216 | std::cerr << "Finished sDTW in "<< GetRealTime() - real_start_time << ", target length: " << target_length << ", query length: " << query_length << "\n"; 217 | std::cerr<< path[0].first.target_coord<<","< 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "signal_batch.h" 13 | #include "utils.h" 14 | 15 | namespace sigmap { 16 | 17 | struct Coordinate{ 18 | size_t target_coord; 19 | size_t query_coord; 20 | Coordinate(size_t new_target_coord,size_t new_query_coord): 21 | target_coord(new_target_coord),query_coord(new_query_coord){} 22 | bool operator < (const Coordinate &other) const { return ((target_coord < other.target_coord)||((target_coord == other.target_coord)&(query_coord < other.query_coord))); } 23 | }; 24 | // std::ostream& operator<<(std::ostream& os, const Coordinate& c){ 25 | // os << c.target_coord << "," << c.query_coord; 26 | // return os; 27 | // } 28 | void reduce_by_half(const float *signal, size_t length, float *signal_reduced, size_t &reduced_length); 29 | void expand_window(std::vector &path,size_t target_length,size_t query_length,int radius,std::vector> &window); 30 | void generate_path(std::vector> &path_matrix,std::vector> &window,std::map> &coord_to_window_index_map,std::vector> &path,ssize_t end_target_position); 31 | float DTW(const float *target_signal, size_t target_length, const float *query_signal, size_t query_length, std::vector> &window,std::vector> &path,ssize_t &end_target_position); 32 | float _fastDTW(const float *target_signal, size_t target_length, const float *query_signal, size_t query_length, int radius,std::vector> &path,std::vector> &window, ssize_t &end_target_position); 33 | std::string print_alignment(std::vector> &path); 34 | float fastDTW(const float *target_signal, size_t target_length, const float *query_signal, size_t query_length,int radius,ssize_t &end_target_position,std::string &cigar); 35 | } // namespace sigmap 36 | 37 | #endif // FAST_DTW_H_ 38 | -------------------------------------------------------------------------------- /src/khash.h: -------------------------------------------------------------------------------- 1 | /* The MIT License 2 | 3 | Copyright (c) 2008, 2009, 2011 by Attractive Chaos 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 20 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 21 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 22 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | SOFTWARE. 24 | */ 25 | 26 | /* 27 | An example: 28 | 29 | #include "khash.h" 30 | KHASH_MAP_INIT_INT(32, char) 31 | int main() { 32 | int ret, is_missing; 33 | khiter_t k; 34 | khash_t(32) *h = kh_init(32); 35 | k = kh_put(32, h, 5, &ret); 36 | kh_value(h, k) = 10; 37 | k = kh_get(32, h, 10); 38 | is_missing = (k == kh_end(h)); 39 | k = kh_get(32, h, 5); 40 | kh_del(32, h, k); 41 | for (k = kh_begin(h); k != kh_end(h); ++k) 42 | if (kh_exist(h, k)) kh_value(h, k) = 1; 43 | kh_destroy(32, h); 44 | return 0; 45 | } 46 | */ 47 | 48 | /* 49 | 2013-05-02 (0.2.8): 50 | 51 | * Use quadratic probing. When the capacity is power of 2, stepping function 52 | i*(i+1)/2 guarantees to traverse each bucket. It is better than double 53 | hashing on cache performance and is more robust than linear probing. 54 | 55 | In theory, double hashing should be more robust than quadratic probing. 56 | However, my implementation is probably not for large hash tables, because 57 | the second hash function is closely tied to the first hash function, 58 | which reduce the effectiveness of double hashing. 59 | 60 | Reference: http://research.cs.vt.edu/AVresearch/hashing/quadratic.php 61 | 62 | 2011-12-29 (0.2.7): 63 | 64 | * Minor code clean up; no actual effect. 65 | 66 | 2011-09-16 (0.2.6): 67 | 68 | * The capacity is a power of 2. This seems to dramatically improve the 69 | speed for simple keys. Thank Zilong Tan for the suggestion. Reference: 70 | 71 | - http://code.google.com/p/ulib/ 72 | - http://nothings.org/computer/judy/ 73 | 74 | * Allow to optionally use linear probing which usually has better 75 | performance for random input. Double hashing is still the default as it 76 | is more robust to certain non-random input. 77 | 78 | * Added Wang's integer hash function (not used by default). This hash 79 | function is more robust to certain non-random input. 80 | 81 | 2011-02-14 (0.2.5): 82 | 83 | * Allow to declare global functions. 84 | 85 | 2009-09-26 (0.2.4): 86 | 87 | * Improve portability 88 | 89 | 2008-09-19 (0.2.3): 90 | 91 | * Corrected the example 92 | * Improved interfaces 93 | 94 | 2008-09-11 (0.2.2): 95 | 96 | * Improved speed a little in kh_put() 97 | 98 | 2008-09-10 (0.2.1): 99 | 100 | * Added kh_clear() 101 | * Fixed a compiling error 102 | 103 | 2008-09-02 (0.2.0): 104 | 105 | * Changed to token concatenation which increases flexibility. 106 | 107 | 2008-08-31 (0.1.2): 108 | 109 | * Fixed a bug in kh_get(), which has not been tested previously. 110 | 111 | 2008-08-31 (0.1.1): 112 | 113 | * Added destructor 114 | */ 115 | 116 | 117 | #ifndef __AC_KHASH_H 118 | #define __AC_KHASH_H 119 | 120 | /*! 121 | @header 122 | 123 | Generic hash table library. 124 | */ 125 | 126 | #define AC_VERSION_KHASH_H "0.2.8" 127 | 128 | #include 129 | #include 130 | #include 131 | 132 | /* compiler specific configuration */ 133 | 134 | #if UINT_MAX == 0xffffffffu 135 | typedef unsigned int khint32_t; 136 | #elif ULONG_MAX == 0xffffffffu 137 | typedef unsigned long khint32_t; 138 | #endif 139 | 140 | #if ULONG_MAX == ULLONG_MAX 141 | typedef unsigned long khint64_t; 142 | #else 143 | typedef unsigned long long khint64_t; 144 | #endif 145 | 146 | #ifndef kh_inline 147 | #ifdef _MSC_VER 148 | #define kh_inline __inline 149 | #else 150 | #define kh_inline inline 151 | #endif 152 | #endif /* kh_inline */ 153 | 154 | #ifndef klib_unused 155 | #if (defined __clang__ && __clang_major__ >= 3) || (defined __GNUC__ && __GNUC__ >= 3) 156 | #define klib_unused __attribute__ ((__unused__)) 157 | #else 158 | #define klib_unused 159 | #endif 160 | #endif /* klib_unused */ 161 | 162 | typedef khint32_t khint_t; 163 | typedef khint_t khiter_t; 164 | 165 | #define __ac_isempty(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&2) 166 | #define __ac_isdel(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&1) 167 | #define __ac_iseither(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&3) 168 | #define __ac_set_isdel_false(flag, i) (flag[i>>4]&=~(1ul<<((i&0xfU)<<1))) 169 | #define __ac_set_isempty_false(flag, i) (flag[i>>4]&=~(2ul<<((i&0xfU)<<1))) 170 | #define __ac_set_isboth_false(flag, i) (flag[i>>4]&=~(3ul<<((i&0xfU)<<1))) 171 | #define __ac_set_isdel_true(flag, i) (flag[i>>4]|=1ul<<((i&0xfU)<<1)) 172 | 173 | #define __ac_fsize(m) ((m) < 16? 1 : (m)>>4) 174 | 175 | #ifndef kroundup32 176 | #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x)) 177 | #endif 178 | 179 | #ifndef kcalloc 180 | #define kcalloc(N,Z) calloc(N,Z) 181 | #endif 182 | #ifndef kmalloc 183 | #define kmalloc(Z) malloc(Z) 184 | #endif 185 | #ifndef krealloc 186 | #define krealloc(P,Z) realloc(P,Z) 187 | #endif 188 | #ifndef kfree 189 | #define kfree(P) free(P) 190 | #endif 191 | 192 | static const double __ac_HASH_UPPER = 0.77; 193 | 194 | #define __KHASH_TYPE(name, khkey_t, khval_t) \ 195 | typedef struct kh_##name##_s { \ 196 | khint_t n_buckets, size, n_occupied, upper_bound; \ 197 | khint32_t *flags; \ 198 | khkey_t *keys; \ 199 | khval_t *vals; \ 200 | } kh_##name##_t; 201 | 202 | #define __KHASH_PROTOTYPES(name, khkey_t, khval_t) \ 203 | extern kh_##name##_t *kh_init_##name(void); \ 204 | extern void kh_destroy_##name(kh_##name##_t *h); \ 205 | extern void kh_clear_##name(kh_##name##_t *h); \ 206 | extern khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key); \ 207 | extern int kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets); \ 208 | extern khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret); \ 209 | extern void kh_del_##name(kh_##name##_t *h, khint_t x); \ 210 | extern void kh_load_##name(kh_##name##_t *h, FILE* fp); \ 211 | extern void kh_save_##name(kh_##name##_t *h, FILE* fp); 212 | 213 | #define __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ 214 | SCOPE kh_##name##_t *kh_init_##name(void) { \ 215 | return (kh_##name##_t*)kcalloc(1, sizeof(kh_##name##_t)); \ 216 | } \ 217 | SCOPE void kh_destroy_##name(kh_##name##_t *h) \ 218 | { \ 219 | if (h) { \ 220 | kfree((void *)h->keys); kfree(h->flags); \ 221 | kfree((void *)h->vals); \ 222 | kfree(h); \ 223 | } \ 224 | } \ 225 | SCOPE void kh_clear_##name(kh_##name##_t *h) \ 226 | { \ 227 | if (h && h->flags) { \ 228 | memset(h->flags, 0xaa, __ac_fsize(h->n_buckets) * sizeof(khint32_t)); \ 229 | h->size = h->n_occupied = 0; \ 230 | } \ 231 | } \ 232 | SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \ 233 | { \ 234 | if (h->n_buckets) { \ 235 | khint_t k, i, last, mask, step = 0; \ 236 | mask = h->n_buckets - 1; \ 237 | k = __hash_func(key); i = k & mask; \ 238 | last = i; \ 239 | while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \ 240 | i = (i + (++step)) & mask; \ 241 | if (i == last) return h->n_buckets; \ 242 | } \ 243 | return __ac_iseither(h->flags, i)? h->n_buckets : i; \ 244 | } else return 0; \ 245 | } \ 246 | SCOPE int kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \ 247 | { /* This function uses 0.25*n_buckets bytes of working space instead of [sizeof(key_t+val_t)+.25]*n_buckets. */ \ 248 | khint32_t *new_flags = 0; \ 249 | khint_t j = 1; \ 250 | { \ 251 | kroundup32(new_n_buckets); \ 252 | if (new_n_buckets < 4) new_n_buckets = 4; \ 253 | if (h->size >= (khint_t)(new_n_buckets * __ac_HASH_UPPER + 0.5)) j = 0; /* requested size is too small */ \ 254 | else { /* hash table size to be changed (shrink or expand); rehash */ \ 255 | new_flags = (khint32_t*)kmalloc(__ac_fsize(new_n_buckets) * sizeof(khint32_t)); \ 256 | if (!new_flags) return -1; \ 257 | memset(new_flags, 0xaa, __ac_fsize(new_n_buckets) * sizeof(khint32_t)); \ 258 | if (h->n_buckets < new_n_buckets) { /* expand */ \ 259 | khkey_t *new_keys = (khkey_t*)krealloc((void *)h->keys, new_n_buckets * sizeof(khkey_t)); \ 260 | if (!new_keys) { kfree(new_flags); return -1; } \ 261 | h->keys = new_keys; \ 262 | if (kh_is_map) { \ 263 | khval_t *new_vals = (khval_t*)krealloc((void *)h->vals, new_n_buckets * sizeof(khval_t)); \ 264 | if (!new_vals) { kfree(new_flags); return -1; } \ 265 | h->vals = new_vals; \ 266 | } \ 267 | } /* otherwise shrink */ \ 268 | } \ 269 | } \ 270 | if (j) { /* rehashing is needed */ \ 271 | for (j = 0; j != h->n_buckets; ++j) { \ 272 | if (__ac_iseither(h->flags, j) == 0) { \ 273 | khkey_t key = h->keys[j]; \ 274 | khval_t val; \ 275 | khint_t new_mask; \ 276 | new_mask = new_n_buckets - 1; \ 277 | if (kh_is_map) val = h->vals[j]; \ 278 | __ac_set_isdel_true(h->flags, j); \ 279 | while (1) { /* kick-out process; sort of like in Cuckoo hashing */ \ 280 | khint_t k, i, step = 0; \ 281 | k = __hash_func(key); \ 282 | i = k & new_mask; \ 283 | while (!__ac_isempty(new_flags, i)) i = (i + (++step)) & new_mask; \ 284 | __ac_set_isempty_false(new_flags, i); \ 285 | if (i < h->n_buckets && __ac_iseither(h->flags, i) == 0) { /* kick out the existing element */ \ 286 | { khkey_t tmp = h->keys[i]; h->keys[i] = key; key = tmp; } \ 287 | if (kh_is_map) { khval_t tmp = h->vals[i]; h->vals[i] = val; val = tmp; } \ 288 | __ac_set_isdel_true(h->flags, i); /* mark it as deleted in the old hash table */ \ 289 | } else { /* write the element and jump out of the loop */ \ 290 | h->keys[i] = key; \ 291 | if (kh_is_map) h->vals[i] = val; \ 292 | break; \ 293 | } \ 294 | } \ 295 | } \ 296 | } \ 297 | if (h->n_buckets > new_n_buckets) { /* shrink the hash table */ \ 298 | h->keys = (khkey_t*)krealloc((void *)h->keys, new_n_buckets * sizeof(khkey_t)); \ 299 | if (kh_is_map) h->vals = (khval_t*)krealloc((void *)h->vals, new_n_buckets * sizeof(khval_t)); \ 300 | } \ 301 | kfree(h->flags); /* free the working space */ \ 302 | h->flags = new_flags; \ 303 | h->n_buckets = new_n_buckets; \ 304 | h->n_occupied = h->size; \ 305 | h->upper_bound = (khint_t)(h->n_buckets * __ac_HASH_UPPER + 0.5); \ 306 | } \ 307 | return 0; \ 308 | } \ 309 | SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \ 310 | { \ 311 | khint_t x; \ 312 | if (h->n_occupied >= h->upper_bound) { /* update the hash table */ \ 313 | if (h->n_buckets > (h->size<<1)) { \ 314 | if (kh_resize_##name(h, h->n_buckets - 1) < 0) { /* clear "deleted" elements */ \ 315 | *ret = -1; return h->n_buckets; \ 316 | } \ 317 | } else if (kh_resize_##name(h, h->n_buckets + 1) < 0) { /* expand the hash table */ \ 318 | *ret = -1; return h->n_buckets; \ 319 | } \ 320 | } /* TODO: to implement automatically shrinking; resize() already support shrinking */ \ 321 | { \ 322 | khint_t k, i, site, last, mask = h->n_buckets - 1, step = 0; \ 323 | x = site = h->n_buckets; k = __hash_func(key); i = k & mask; \ 324 | if (__ac_isempty(h->flags, i)) x = i; /* for speed up */ \ 325 | else { \ 326 | last = i; \ 327 | while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \ 328 | if (__ac_isdel(h->flags, i)) site = i; \ 329 | i = (i + (++step)) & mask; \ 330 | if (i == last) { x = site; break; } \ 331 | } \ 332 | if (x == h->n_buckets) { \ 333 | if (__ac_isempty(h->flags, i) && site != h->n_buckets) x = site; \ 334 | else x = i; \ 335 | } \ 336 | } \ 337 | } \ 338 | if (__ac_isempty(h->flags, x)) { /* not present at all */ \ 339 | h->keys[x] = key; \ 340 | __ac_set_isboth_false(h->flags, x); \ 341 | ++h->size; ++h->n_occupied; \ 342 | *ret = 1; \ 343 | } else if (__ac_isdel(h->flags, x)) { /* deleted */ \ 344 | h->keys[x] = key; \ 345 | __ac_set_isboth_false(h->flags, x); \ 346 | ++h->size; \ 347 | *ret = 2; \ 348 | } else *ret = 0; /* Don't touch h->keys[x] if present and not deleted */ \ 349 | return x; \ 350 | } \ 351 | SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \ 352 | { \ 353 | if (x != h->n_buckets && !__ac_iseither(h->flags, x)) { \ 354 | __ac_set_isdel_true(h->flags, x); \ 355 | --h->size; \ 356 | } \ 357 | } \ 358 | SCOPE void kh_load_##name(kh_##name##_t *h, FILE* fp)\ 359 | {\ 360 | fread(&(h->n_buckets), sizeof(khint_t), 1, fp);\ 361 | fread(&(h->size), sizeof(khint_t), 1, fp);\ 362 | fread(&(h->n_occupied), sizeof(khint_t), 1, fp);\ 363 | fread(&(h->upper_bound), sizeof(khint_t), 1, fp);\ 364 | if (h->n_buckets)\ 365 | {\ 366 | h->flags = (khint32_t*)kmalloc(__ac_fsize(h->n_buckets) * sizeof(khint32_t));\ 367 | fread(h->flags, sizeof(khint32_t), __ac_fsize(h->n_buckets), fp);\ 368 | h->keys = (khkey_t*)kmalloc(sizeof(khkey_t)*h->n_buckets);\ 369 | fread(h->keys, sizeof(khkey_t), h->n_buckets, fp);\ 370 | h->vals = (khval_t*)kmalloc(sizeof(khval_t)*h->n_buckets);\ 371 | fread(h->vals, sizeof(khval_t), h->n_buckets, fp);\ 372 | }\ 373 | }\ 374 | SCOPE void kh_write_##name(kh_##name##_t *h, FILE* fp)\ 375 | {\ 376 | fwrite(&(h->n_buckets), sizeof(khint_t), 1, fp);\ 377 | fwrite(&(h->size), sizeof(khint_t), 1, fp);\ 378 | fwrite(&(h->n_occupied), sizeof(khint_t), 1, fp);\ 379 | fwrite(&(h->upper_bound), sizeof(khint_t), 1, fp);\ 380 | if (h->n_buckets)\ 381 | {\ 382 | fwrite(h->flags, sizeof(khint32_t), __ac_fsize(h->n_buckets), fp);\ 383 | fwrite(h->keys, sizeof(khkey_t), h->n_buckets, fp);\ 384 | fwrite(h->vals, sizeof(khval_t), h->n_buckets, fp);\ 385 | }\ 386 | } 387 | 388 | #define KHASH_DECLARE(name, khkey_t, khval_t) \ 389 | __KHASH_TYPE(name, khkey_t, khval_t) \ 390 | __KHASH_PROTOTYPES(name, khkey_t, khval_t) 391 | 392 | #define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ 393 | __KHASH_TYPE(name, khkey_t, khval_t) \ 394 | __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) 395 | 396 | #define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ 397 | KHASH_INIT2(name, static kh_inline klib_unused, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) 398 | 399 | /* --- BEGIN OF HASH FUNCTIONS --- */ 400 | 401 | /*! @function 402 | @abstract Integer hash function 403 | @param key The integer [khint32_t] 404 | @return The hash value [khint_t] 405 | */ 406 | #define kh_int_hash_func(key) (khint32_t)(key) 407 | /*! @function 408 | @abstract Integer comparison function 409 | */ 410 | #define kh_int_hash_equal(a, b) ((a) == (b)) 411 | /*! @function 412 | @abstract 64-bit integer hash function 413 | @param key The integer [khint64_t] 414 | @return The hash value [khint_t] 415 | */ 416 | #define kh_int64_hash_func(key) (khint32_t)((key)>>33^(key)^(key)<<11) 417 | /*! @function 418 | @abstract 64-bit integer comparison function 419 | */ 420 | #define kh_int64_hash_equal(a, b) ((a) == (b)) 421 | /*! @function 422 | @abstract const char* hash function 423 | @param s Pointer to a null terminated string 424 | @return The hash value 425 | */ 426 | static kh_inline khint_t __ac_X31_hash_string(const char *s) 427 | { 428 | khint_t h = (khint_t)*s; 429 | if (h) for (++s ; *s; ++s) h = (h << 5) - h + (khint_t)*s; 430 | return h; 431 | } 432 | /*! @function 433 | @abstract Another interface to const char* hash function 434 | @param key Pointer to a null terminated string [const char*] 435 | @return The hash value [khint_t] 436 | */ 437 | #define kh_str_hash_func(key) __ac_X31_hash_string(key) 438 | /*! @function 439 | @abstract Const char* comparison function 440 | */ 441 | #define kh_str_hash_equal(a, b) (strcmp(a, b) == 0) 442 | 443 | static kh_inline khint_t __ac_Wang_hash(khint_t key) 444 | { 445 | key += ~(key << 15); 446 | key ^= (key >> 10); 447 | key += (key << 3); 448 | key ^= (key >> 6); 449 | key += ~(key << 11); 450 | key ^= (key >> 16); 451 | return key; 452 | } 453 | #define kh_int_hash_func2(key) __ac_Wang_hash((khint_t)key) 454 | 455 | /* --- END OF HASH FUNCTIONS --- */ 456 | 457 | /* Other convenient macros... */ 458 | 459 | /*! 460 | @abstract Type of the hash table. 461 | @param name Name of the hash table [symbol] 462 | */ 463 | #define khash_t(name) kh_##name##_t 464 | 465 | /*! @function 466 | @abstract Initiate a hash table. 467 | @param name Name of the hash table [symbol] 468 | @return Pointer to the hash table [khash_t(name)*] 469 | */ 470 | #define kh_init(name) kh_init_##name() 471 | 472 | /*! @function 473 | @abstract Destroy a hash table. 474 | @param name Name of the hash table [symbol] 475 | @param h Pointer to the hash table [khash_t(name)*] 476 | */ 477 | #define kh_destroy(name, h) kh_destroy_##name(h) 478 | 479 | /*! @function 480 | @abstract Reset a hash table without deallocating memory. 481 | @param name Name of the hash table [symbol] 482 | @param h Pointer to the hash table [khash_t(name)*] 483 | */ 484 | #define kh_clear(name, h) kh_clear_##name(h) 485 | 486 | /*! @function 487 | @abstract Resize a hash table. 488 | @param name Name of the hash table [symbol] 489 | @param h Pointer to the hash table [khash_t(name)*] 490 | @param s New size [khint_t] 491 | */ 492 | #define kh_resize(name, h, s) kh_resize_##name(h, s) 493 | 494 | /*! @function 495 | @abstract Insert a key to the hash table. 496 | @param name Name of the hash table [symbol] 497 | @param h Pointer to the hash table [khash_t(name)*] 498 | @param k Key [type of keys] 499 | @param r Extra return code: -1 if the operation failed; 500 | 0 if the key is present in the hash table; 501 | 1 if the bucket is empty (never used); 2 if the element in 502 | the bucket has been deleted [int*] 503 | @return Iterator to the inserted element [khint_t] 504 | */ 505 | #define kh_put(name, h, k, r) kh_put_##name(h, k, r) 506 | 507 | /*! @function 508 | @abstract Retrieve a key from the hash table. 509 | @param name Name of the hash table [symbol] 510 | @param h Pointer to the hash table [khash_t(name)*] 511 | @param k Key [type of keys] 512 | @return Iterator to the found element, or kh_end(h) if the element is absent [khint_t] 513 | */ 514 | #define kh_get(name, h, k) kh_get_##name(h, k) 515 | 516 | /*! @function 517 | @abstract Remove a key from the hash table. 518 | @param name Name of the hash table [symbol] 519 | @param h Pointer to the hash table [khash_t(name)*] 520 | @param k Iterator to the element to be deleted [khint_t] 521 | */ 522 | #define kh_del(name, h, k) kh_del_##name(h, k) 523 | 524 | /*! @function 525 | @abstract Test whether a bucket contains data. 526 | @param h Pointer to the hash table [khash_t(name)*] 527 | @param x Iterator to the bucket [khint_t] 528 | @return 1 if containing data; 0 otherwise [int] 529 | */ 530 | #define kh_exist(h, x) (!__ac_iseither((h)->flags, (x))) 531 | 532 | /*! @function 533 | @abstract Get key given an iterator 534 | @param h Pointer to the hash table [khash_t(name)*] 535 | @param x Iterator to the bucket [khint_t] 536 | @return Key [type of keys] 537 | */ 538 | #define kh_key(h, x) ((h)->keys[x]) 539 | 540 | /*! @function 541 | @abstract Get value given an iterator 542 | @param h Pointer to the hash table [khash_t(name)*] 543 | @param x Iterator to the bucket [khint_t] 544 | @return Value [type of values] 545 | @discussion For hash sets, calling this results in segfault. 546 | */ 547 | #define kh_val(h, x) ((h)->vals[x]) 548 | 549 | /*! @function 550 | @abstract Alias of kh_val() 551 | */ 552 | #define kh_value(h, x) ((h)->vals[x]) 553 | 554 | /*! @function 555 | @abstract Get the start iterator 556 | @param h Pointer to the hash table [khash_t(name)*] 557 | @return The start iterator [khint_t] 558 | */ 559 | #define kh_begin(h) (khint_t)(0) 560 | 561 | /*! @function 562 | @abstract Get the end iterator 563 | @param h Pointer to the hash table [khash_t(name)*] 564 | @return The end iterator [khint_t] 565 | */ 566 | #define kh_end(h) ((h)->n_buckets) 567 | 568 | /*! @function 569 | @abstract Get the number of elements in the hash table 570 | @param h Pointer to the hash table [khash_t(name)*] 571 | @return Number of elements in the hash table [khint_t] 572 | */ 573 | #define kh_size(h) ((h)->size) 574 | 575 | /*! @function 576 | @abstract Get the number of buckets in the hash table 577 | @param h Pointer to the hash table [khash_t(name)*] 578 | @return Number of buckets in the hash table [khint_t] 579 | */ 580 | #define kh_n_buckets(h) ((h)->n_buckets) 581 | 582 | /*! @function 583 | @abstract Iterate over the entries in the hash table 584 | @param h Pointer to the hash table [khash_t(name)*] 585 | @param kvar Variable to which key will be assigned 586 | @param vvar Variable to which value will be assigned 587 | @param code Block of code to execute 588 | */ 589 | #define kh_foreach(h, kvar, vvar, code) { khint_t __i; \ 590 | for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ 591 | if (!kh_exist(h,__i)) continue; \ 592 | (kvar) = kh_key(h,__i); \ 593 | (vvar) = kh_val(h,__i); \ 594 | code; \ 595 | } } 596 | 597 | /*! @function 598 | @abstract Iterate over the values in the hash table 599 | @param h Pointer to the hash table [khash_t(name)*] 600 | @param vvar Variable to which value will be assigned 601 | @param code Block of code to execute 602 | */ 603 | #define kh_foreach_value(h, vvar, code) { khint_t __i; \ 604 | for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ 605 | if (!kh_exist(h,__i)) continue; \ 606 | (vvar) = kh_val(h,__i); \ 607 | code; \ 608 | } } 609 | 610 | #define kh_load(name, h, fp) kh_load_##name(h, fp) 611 | #define kh_save(name, h, fp) kh_write_##name(h, fp) 612 | 613 | /* More convenient interfaces */ 614 | 615 | /*! @function 616 | @abstract Instantiate a hash set containing integer keys 617 | @param name Name of the hash table [symbol] 618 | */ 619 | #define KHASH_SET_INIT_INT(name) \ 620 | KHASH_INIT(name, khint32_t, char, 0, kh_int_hash_func, kh_int_hash_equal) 621 | 622 | /*! @function 623 | @abstract Instantiate a hash map containing integer keys 624 | @param name Name of the hash table [symbol] 625 | @param khval_t Type of values [type] 626 | */ 627 | #define KHASH_MAP_INIT_INT(name, khval_t) \ 628 | KHASH_INIT(name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) 629 | 630 | /*! @function 631 | @abstract Instantiate a hash set containing 64-bit integer keys 632 | @param name Name of the hash table [symbol] 633 | */ 634 | #define KHASH_SET_INIT_INT64(name) \ 635 | KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal) 636 | 637 | /*! @function 638 | @abstract Instantiate a hash map containing 64-bit integer keys 639 | @param name Name of the hash table [symbol] 640 | @param khval_t Type of values [type] 641 | */ 642 | #define KHASH_MAP_INIT_INT64(name, khval_t) \ 643 | KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal) 644 | 645 | typedef const char *kh_cstr_t; 646 | /*! @function 647 | @abstract Instantiate a hash map containing const char* keys 648 | @param name Name of the hash table [symbol] 649 | */ 650 | #define KHASH_SET_INIT_STR(name) \ 651 | KHASH_INIT(name, kh_cstr_t, char, 0, kh_str_hash_func, kh_str_hash_equal) 652 | 653 | /*! @function 654 | @abstract Instantiate a hash map containing const char* keys 655 | @param name Name of the hash table [symbol] 656 | @param khval_t Type of values [type] 657 | */ 658 | #define KHASH_MAP_INIT_STR(name, khval_t) \ 659 | KHASH_INIT(name, kh_cstr_t, khval_t, 1, kh_str_hash_func, kh_str_hash_equal) 660 | 661 | #endif /* __AC_KHASH_H */ 662 | -------------------------------------------------------------------------------- /src/kseq.h: -------------------------------------------------------------------------------- 1 | /* The MIT License 2 | 3 | Copyright (c) 2008, 2009, 2011 Attractive Chaos 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 20 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 21 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 22 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | SOFTWARE. 24 | */ 25 | 26 | /* Last Modified: 05MAR2012 */ 27 | 28 | #ifndef AC_KSEQ_H 29 | #define AC_KSEQ_H 30 | 31 | #include 32 | #include 33 | #include 34 | 35 | #define KS_SEP_SPACE 0 // isspace(): \t, \n, \v, \f, \r 36 | #define KS_SEP_TAB 1 // isspace() && !' ' 37 | #define KS_SEP_LINE 2 // line separator: "\n" (Unix) or "\r\n" (Windows) 38 | #define KS_SEP_MAX 2 39 | 40 | #define __KS_TYPE(type_t) \ 41 | typedef struct __kstream_t { \ 42 | unsigned char *buf; \ 43 | int begin, end, is_eof; \ 44 | type_t f; \ 45 | } kstream_t; 46 | 47 | #define ks_err(ks) ((ks)->end == -1) 48 | #define ks_eof(ks) ((ks)->is_eof && (ks)->begin >= (ks)->end) 49 | #define ks_rewind(ks) ((ks)->is_eof = (ks)->begin = (ks)->end = 0) 50 | 51 | #define __KS_BASIC(type_t, __bufsize) \ 52 | static inline kstream_t *ks_init(type_t f) \ 53 | { \ 54 | kstream_t *ks = (kstream_t*)calloc(1, sizeof(kstream_t)); \ 55 | ks->f = f; \ 56 | ks->buf = (unsigned char*)malloc(__bufsize); \ 57 | return ks; \ 58 | } \ 59 | static inline void ks_destroy(kstream_t *ks) \ 60 | { \ 61 | if (ks) { \ 62 | free(ks->buf); \ 63 | free(ks); \ 64 | } \ 65 | } 66 | 67 | #define __KS_GETC(__read, __bufsize) \ 68 | static inline int ks_getc(kstream_t *ks) \ 69 | { \ 70 | if (ks_err(ks)) return -3; \ 71 | if (ks->is_eof && ks->begin >= ks->end) return -1; \ 72 | if (ks->begin >= ks->end) { \ 73 | ks->begin = 0; \ 74 | ks->end = __read(ks->f, ks->buf, __bufsize); \ 75 | if (ks->end == 0) { ks->is_eof = 1; return -1;} \ 76 | if (ks->end == -1) { ks->is_eof = 1; return -3;}\ 77 | } \ 78 | return (int)ks->buf[ks->begin++]; \ 79 | } 80 | 81 | #ifndef KSTRING_T 82 | #define KSTRING_T kstring_t 83 | typedef struct __kstring_t { 84 | size_t l, m; 85 | char *s; 86 | } kstring_t; 87 | #endif 88 | 89 | #ifndef kroundup32 90 | #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x)) 91 | #endif 92 | 93 | #define __KS_GETUNTIL(__read, __bufsize) \ 94 | static int ks_getuntil2(kstream_t *ks, int delimiter, kstring_t *str, int *dret, int append) \ 95 | { \ 96 | int gotany = 0; \ 97 | if (dret) *dret = 0; \ 98 | str->l = append? str->l : 0; \ 99 | for (;;) { \ 100 | int i; \ 101 | if (ks_err(ks)) return -3; \ 102 | if (ks->begin >= ks->end) { \ 103 | if (!ks->is_eof) { \ 104 | ks->begin = 0; \ 105 | ks->end = __read(ks->f, ks->buf, __bufsize); \ 106 | if (ks->end == 0) { ks->is_eof = 1; break; } \ 107 | if (ks->end == -1) { ks->is_eof = 1; return -3; } \ 108 | } else break; \ 109 | } \ 110 | if (delimiter == KS_SEP_LINE) { \ 111 | for (i = ks->begin; i < ks->end; ++i) \ 112 | if (ks->buf[i] == '\n') break; \ 113 | } else if (delimiter > KS_SEP_MAX) { \ 114 | for (i = ks->begin; i < ks->end; ++i) \ 115 | if (ks->buf[i] == delimiter) break; \ 116 | } else if (delimiter == KS_SEP_SPACE) { \ 117 | for (i = ks->begin; i < ks->end; ++i) \ 118 | if (isspace(ks->buf[i])) break; \ 119 | } else if (delimiter == KS_SEP_TAB) { \ 120 | for (i = ks->begin; i < ks->end; ++i) \ 121 | if (isspace(ks->buf[i]) && ks->buf[i] != ' ') break; \ 122 | } else i = 0; /* never come to here! */ \ 123 | if (str->m - str->l < (size_t)(i - ks->begin + 1)) { \ 124 | str->m = str->l + (i - ks->begin) + 1; \ 125 | kroundup32(str->m); \ 126 | str->s = (char*)realloc(str->s, str->m); \ 127 | } \ 128 | gotany = 1; \ 129 | memcpy(str->s + str->l, ks->buf + ks->begin, i - ks->begin); \ 130 | str->l = str->l + (i - ks->begin); \ 131 | ks->begin = i + 1; \ 132 | if (i < ks->end) { \ 133 | if (dret) *dret = ks->buf[i]; \ 134 | break; \ 135 | } \ 136 | } \ 137 | if (!gotany && ks_eof(ks)) return -1; \ 138 | if (str->s == 0) { \ 139 | str->m = 1; \ 140 | str->s = (char*)calloc(1, 1); \ 141 | } else if (delimiter == KS_SEP_LINE && str->l > 1 && str->s[str->l-1] == '\r') --str->l; \ 142 | str->s[str->l] = '\0'; \ 143 | return str->l; \ 144 | } \ 145 | static inline int ks_getuntil(kstream_t *ks, int delimiter, kstring_t *str, int *dret) \ 146 | { return ks_getuntil2(ks, delimiter, str, dret, 0); } 147 | 148 | #define KSTREAM_INIT(type_t, __read, __bufsize) \ 149 | __KS_TYPE(type_t) \ 150 | __KS_BASIC(type_t, __bufsize) \ 151 | __KS_GETC(__read, __bufsize) \ 152 | __KS_GETUNTIL(__read, __bufsize) 153 | 154 | #define kseq_rewind(ks) ((ks)->last_char = (ks)->f->is_eof = (ks)->f->begin = (ks)->f->end = 0) 155 | 156 | #define __KSEQ_BASIC(SCOPE, type_t) \ 157 | SCOPE kseq_t *kseq_init(type_t fd) \ 158 | { \ 159 | kseq_t *s = (kseq_t*)calloc(1, sizeof(kseq_t)); \ 160 | s->f = ks_init(fd); \ 161 | return s; \ 162 | } \ 163 | SCOPE void kseq_destroy(kseq_t *ks) \ 164 | { \ 165 | if (!ks) return; \ 166 | free(ks->name.s); free(ks->comment.s); free(ks->seq.s); free(ks->qual.s); \ 167 | ks_destroy(ks->f); \ 168 | free(ks); \ 169 | } 170 | 171 | /* Return value: 172 | >=0 length of the sequence (normal) 173 | -1 end-of-file 174 | -2 truncated quality string 175 | -3 error reading stream 176 | */ 177 | #define __KSEQ_READ(SCOPE) \ 178 | SCOPE int kseq_read(kseq_t *seq) \ 179 | { \ 180 | int c,r; \ 181 | kstream_t *ks = seq->f; \ 182 | if (seq->last_char == 0) { /* then jump to the next header line */ \ 183 | while ((c = ks_getc(ks)) >= 0 && c != '>' && c != '@'); \ 184 | if (c < 0) return c; /* end of file or error*/ \ 185 | seq->last_char = c; \ 186 | } /* else: the first header char has been read in the previous call */ \ 187 | seq->comment.l = seq->seq.l = seq->qual.l = 0; /* reset all members */ \ 188 | if ((r=ks_getuntil(ks, 0, &seq->name, &c)) < 0) return r; /* normal exit: EOF or error */ \ 189 | if (c != '\n') ks_getuntil(ks, KS_SEP_LINE, &seq->comment, 0); /* read FASTA/Q comment */ \ 190 | if (seq->seq.s == 0) { /* we can do this in the loop below, but that is slower */ \ 191 | seq->seq.m = 256; \ 192 | seq->seq.s = (char*)malloc(seq->seq.m); \ 193 | } \ 194 | while ((c = ks_getc(ks)) >= 0 && c != '>' && c != '+' && c != '@') { \ 195 | if (c == '\n') continue; /* skip empty lines */ \ 196 | seq->seq.s[seq->seq.l++] = c; /* this is safe: we always have enough space for 1 char */ \ 197 | ks_getuntil2(ks, KS_SEP_LINE, &seq->seq, 0, 1); /* read the rest of the line */ \ 198 | } \ 199 | if (c == '>' || c == '@') seq->last_char = c; /* the first header char has been read */ \ 200 | if (seq->seq.l + 1 >= seq->seq.m) { /* seq->seq.s[seq->seq.l] below may be out of boundary */ \ 201 | seq->seq.m = seq->seq.l + 2; \ 202 | kroundup32(seq->seq.m); /* rounded to the next closest 2^k */ \ 203 | seq->seq.s = (char*)realloc(seq->seq.s, seq->seq.m); \ 204 | } \ 205 | seq->seq.s[seq->seq.l] = 0; /* null terminated string */ \ 206 | if (c != '+') return seq->seq.l; /* FASTA */ \ 207 | if (seq->qual.m < seq->seq.m) { /* allocate memory for qual in case insufficient */ \ 208 | seq->qual.m = seq->seq.m; \ 209 | seq->qual.s = (char*)realloc(seq->qual.s, seq->qual.m); \ 210 | } \ 211 | while ((c = ks_getc(ks)) >= 0 && c != '\n'); /* skip the rest of '+' line */ \ 212 | if (c == -1) return -2; /* error: no quality string */ \ 213 | while ((c = ks_getuntil2(ks, KS_SEP_LINE, &seq->qual, 0, 1) >= 0 && seq->qual.l < seq->seq.l)); \ 214 | if (c == -3) return -3; /* stream error */ \ 215 | seq->last_char = 0; /* we have not come to the next header line */ \ 216 | if (seq->seq.l != seq->qual.l) return -2; /* error: qual string is of a different length */ \ 217 | return seq->seq.l; \ 218 | } 219 | 220 | #define __KSEQ_TYPE(type_t) \ 221 | typedef struct { \ 222 | kstring_t name, comment, seq, qual; \ 223 | int last_char; \ 224 | kstream_t *f; \ 225 | uint32_t id; \ 226 | } kseq_t; 227 | 228 | #define KSEQ_INIT2(SCOPE, type_t, __read) \ 229 | KSTREAM_INIT(type_t, __read, 16384) \ 230 | __KSEQ_TYPE(type_t) \ 231 | __KSEQ_BASIC(SCOPE, type_t) \ 232 | __KSEQ_READ(SCOPE) 233 | 234 | #define KSEQ_INIT(type_t, __read) KSEQ_INIT2(static, type_t, __read) 235 | 236 | #define KSEQ_DECLARE(type_t) \ 237 | __KS_TYPE(type_t) \ 238 | __KSEQ_TYPE(type_t) \ 239 | extern kseq_t *kseq_init(type_t fd); \ 240 | void kseq_destroy(kseq_t *ks); \ 241 | int kseq_read(kseq_t *seq); 242 | 243 | #endif 244 | -------------------------------------------------------------------------------- /src/output_tools.h: -------------------------------------------------------------------------------- 1 | #ifndef OUTPUTTOOLS_H_ 2 | #define OUTPUTTOOLS_H_ 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "sequence_batch.h" 13 | 14 | namespace sigmap { 15 | 16 | struct PAFMapping { 17 | uint32_t read_id; 18 | std::string read_name; 19 | uint32_t read_length; 20 | uint32_t read_start_position; 21 | uint32_t read_end_position; 22 | uint32_t fragment_start_position; 23 | uint32_t fragment_length; 24 | uint8_t mapq : 6, direction : 1, is_unique : 1; 25 | std::string tags; 26 | bool operator<(const PAFMapping &m) const { 27 | return std::tie(fragment_start_position, fragment_length, mapq, direction, 28 | is_unique, read_id, read_start_position, 29 | read_end_position) < 30 | std::tie(m.fragment_start_position, m.fragment_length, m.mapq, 31 | m.direction, m.is_unique, m.read_id, m.read_start_position, 32 | m.read_end_position); 33 | } 34 | bool operator==(const PAFMapping &m) const { 35 | return std::tie(fragment_start_position) == 36 | std::tie(m.fragment_start_position); 37 | } 38 | }; 39 | 40 | struct MappingWithBarcode { 41 | uint32_t read_id; 42 | uint32_t cell_barcode; 43 | uint32_t fragment_start_position; 44 | uint16_t fragment_length; 45 | uint8_t mapq : 6, direction : 1, is_unique : 1; 46 | bool operator<(const MappingWithBarcode &m) const { 47 | return std::tie(fragment_start_position, fragment_length, cell_barcode, 48 | mapq, direction, is_unique, read_id) < 49 | std::tie(m.fragment_start_position, m.fragment_length, 50 | m.cell_barcode, m.mapq, m.direction, m.is_unique, 51 | m.read_id); 52 | } 53 | bool operator==(const MappingWithBarcode &m) const { 54 | return std::tie(cell_barcode, fragment_start_position) == 55 | std::tie(m.cell_barcode, m.fragment_start_position); 56 | } 57 | }; 58 | 59 | struct MappingWithoutBarcode { 60 | uint32_t read_id; 61 | uint32_t fragment_start_position; 62 | uint16_t fragment_length; 63 | uint8_t mapq : 6, direction : 1, is_unique : 1; 64 | bool operator<(const MappingWithoutBarcode &m) const { 65 | return std::tie(fragment_start_position, fragment_length, mapq, direction, 66 | is_unique, read_id) < 67 | std::tie(m.fragment_start_position, m.fragment_length, m.mapq, 68 | m.direction, m.is_unique, m.read_id); 69 | } 70 | bool operator==(const MappingWithoutBarcode &m) const { 71 | return std::tie(fragment_start_position) == 72 | std::tie(m.fragment_start_position); 73 | } 74 | }; 75 | 76 | template 77 | struct TempMappingFileHandle { 78 | std::string file_path; 79 | FILE *file; 80 | bool all_loaded; 81 | uint32_t num_mappings; 82 | uint32_t block_size; 83 | uint32_t current_rid; 84 | uint32_t current_mapping_index; 85 | uint32_t num_mappings_on_current_rid; 86 | uint32_t num_loaded_mappings_on_current_rid; 87 | std::vector 88 | mappings; // this vector only keep mappings on the same ref seq 89 | inline void InitializeTempMappingLoading(uint32_t num_reference_sequences) { 90 | file = fopen(file_path.c_str(), "rb"); 91 | assert(file != NULL); 92 | all_loaded = false; 93 | current_rid = 0; 94 | fread(&num_mappings_on_current_rid, sizeof(size_t), 1, file); 95 | mappings.resize(block_size); 96 | num_loaded_mappings_on_current_rid = 0; 97 | std::cerr << "Block size: " << block_size << ", initialize temp file " 98 | << file_path << "\n"; 99 | } 100 | inline void FinalizeTempMappingLoading() { fclose(file); } 101 | inline void LoadTempMappingBlock(uint32_t num_reference_sequences) { 102 | num_mappings = 0; 103 | while (num_mappings == 0) { 104 | // Only keep mappings on one ref seq, which means # mappings in buffer can 105 | // be less than block size Two cases: current ref seq has remainings or 106 | // not 107 | if (num_loaded_mappings_on_current_rid < num_mappings_on_current_rid) { 108 | // Check if # remains larger than block size 109 | uint32_t num_mappings_to_load_on_current_rid = 110 | num_mappings_on_current_rid - num_loaded_mappings_on_current_rid; 111 | if (num_mappings_to_load_on_current_rid > block_size) { 112 | num_mappings_to_load_on_current_rid = block_size; 113 | } 114 | // std::cerr << num_mappings_to_load_on_current_rid << " " << 115 | // num_loaded_mappings_on_current_rid << " " << 116 | // num_mappings_on_current_rid << "\n"; std::cerr << mappings.size() << 117 | // "\n"; 118 | fread(mappings.data(), sizeof(MappingRecord), 119 | num_mappings_to_load_on_current_rid, file); 120 | // std::cerr << "Load mappings\n"; 121 | num_loaded_mappings_on_current_rid += 122 | num_mappings_to_load_on_current_rid; 123 | num_mappings = num_mappings_to_load_on_current_rid; 124 | } else { 125 | // Move to next rid 126 | ++current_rid; 127 | if (current_rid < num_reference_sequences) { 128 | // std::cerr << "Load size\n"; 129 | fread(&num_mappings_on_current_rid, sizeof(size_t), 1, file); 130 | // std::cerr << "Load size " << num_mappings_on_current_rid << "\n"; 131 | num_loaded_mappings_on_current_rid = 0; 132 | } else { 133 | all_loaded = true; 134 | break; 135 | } 136 | } 137 | } 138 | current_mapping_index = 0; 139 | } 140 | inline void Next(uint32_t num_reference_sequences) { 141 | ++current_mapping_index; 142 | if (current_mapping_index >= num_mappings) { 143 | LoadTempMappingBlock(num_reference_sequences); 144 | } 145 | } 146 | }; 147 | 148 | template 149 | class OutputTools { 150 | public: 151 | OutputTools() {} 152 | virtual ~OutputTools() {} 153 | inline void OutputTempMapping( 154 | const std::string &temp_mapping_output_file_path, 155 | uint32_t num_reference_sequences, 156 | const std::vector > &mappings) { 157 | FILE *temp_mapping_output_file = 158 | fopen(temp_mapping_output_file_path.c_str(), "wb"); 159 | assert(temp_mapping_output_file != NULL); 160 | for (size_t ri = 0; ri < num_reference_sequences; ++ri) { 161 | // make sure mappings[ri] exists even if its size is 0 162 | size_t num_mappings = mappings[ri].size(); 163 | fwrite(&num_mappings, sizeof(size_t), 1, temp_mapping_output_file); 164 | if (mappings[ri].size() > 0) { 165 | fwrite(mappings[ri].data(), sizeof(MappingRecord), mappings[ri].size(), 166 | temp_mapping_output_file); 167 | } 168 | } 169 | fclose(temp_mapping_output_file); 170 | } 171 | inline void LoadBinaryTempMapping( 172 | const std::string &temp_mapping_file_path, 173 | uint32_t num_reference_sequences, 174 | std::vector > &mappings) { 175 | FILE *temp_mapping_file = fopen(temp_mapping_file_path.c_str(), "rb"); 176 | assert(temp_mapping_file != NULL); 177 | for (size_t ri = 0; ri < num_reference_sequences; ++ri) { 178 | size_t num_mappings = 0; 179 | fread(&num_mappings, sizeof(size_t), 1, temp_mapping_file); 180 | if (num_mappings > 0) { 181 | mappings.emplace_back(std::vector(num_mappings)); 182 | fread(&(mappings[ri].data()), sizeof(MappingRecord), num_mappings, 183 | temp_mapping_file); 184 | } else { 185 | mappings.emplace_back(std::vector()); 186 | } 187 | } 188 | fclose(temp_mapping_file); 189 | } 190 | inline void InitializeMappingOutput( 191 | const std::string &mapping_output_file_path) { 192 | mapping_output_file_path_ = mapping_output_file_path; 193 | mapping_output_file_ = fopen(mapping_output_file_path_.c_str(), "w"); 194 | assert(mapping_output_file_ != NULL); 195 | } 196 | inline void FinalizeMappingOutput() { fclose(mapping_output_file_); } 197 | inline void AppendMappingOutput(const std::string &line) { 198 | fprintf(mapping_output_file_, "%s", line.data()); 199 | } 200 | inline void AppendUnmappedRead(uint32_t rid, const SequenceBatch &reference, 201 | const PAFMapping &mapping) { 202 | // const char *reference_sequence_name = reference.GetSequenceNameAt(rid); 203 | // uint32_t reference_sequence_length = reference.GetSequenceLengthAt(rid); 204 | // uint32_t mapping_end_position = mapping.fragment_start_position + 205 | // mapping.fragment_length; 206 | this->AppendMappingOutput( 207 | mapping.read_name + "\t" + std::to_string(mapping.read_length) + 208 | "\t*\t*\t*\t*\t*\t*\t*\t*\t*\t" + std::to_string(mapping.mapq) + "\t" + 209 | mapping.tags + "\n"); 210 | } 211 | virtual void AppendMapping(uint32_t rid, const SequenceBatch &reference, 212 | const MappingRecord &mapping) = 0; 213 | inline std::string GeneratePAFLine( 214 | const SequenceBatch &query_batch, uint32_t query_index, 215 | const int query_start, const int query_end, const char relative_strand, 216 | const SequenceBatch &target_batch, uint32_t target_index, 217 | const int target_start, const int target_end, const int num_matches, 218 | const int alignment_length, const int mapping_quality) { 219 | return std::string(query_batch.GetSequenceNameAt(query_index)) + "\t" + 220 | std::to_string(query_batch.GetSequenceLengthAt(query_index)) + "\t" + 221 | std::to_string(query_start) + "\t" + std::to_string(query_end) + 222 | "\t" + relative_strand + "\t" + 223 | std::string(target_batch.GetSequenceNameAt(target_index)) + "\t" + 224 | std::to_string(target_batch.GetSequenceLengthAt(target_index)) + 225 | "\t" + std::to_string(target_start) + "\t" + 226 | std::to_string(target_end) + "\t" + std::to_string(num_matches) + 227 | "\t" + std::to_string(alignment_length) + "\t" + 228 | std::to_string(mapping_quality) + "\n"; 229 | } 230 | inline uint32_t GetNumMappings() const { return num_mappings_; } 231 | inline std::string Seed2Sequence(uint64_t seed, uint32_t seed_length) const { 232 | std::string sequence; 233 | sequence.reserve(seed_length); 234 | uint64_t mask = 3; 235 | for (uint32_t i = 0; i < seed_length; ++i) { 236 | sequence.push_back(SequenceBatch::Uint8ToChar( 237 | (seed >> ((seed_length - 1 - i) * 2)) & mask)); 238 | } 239 | return sequence; 240 | } 241 | 242 | // inline void InitializeMatrixOutput(const std::string &matrix_output_prefix) 243 | // { 244 | // matrix_output_prefix_ = matrix_output_prefix; 245 | // matrix_output_file_ = fopen((matrix_output_prefix_ + 246 | // "_matrix.mtx").c_str(), "w"); assert(matrix_output_file_ != NULL); 247 | // peak_output_file_ = fopen((matrix_output_prefix_ + "_peaks.bed").c_str(), 248 | // "w"); assert(peak_output_file_ != NULL); barcode_output_file_ = 249 | // fopen((matrix_output_prefix_ + "_barcode.tsv").c_str(), "w"); 250 | // assert(barcode_output_file_ != NULL); 251 | //} 252 | // void OutputPeaks(uint32_t bin_size, uint32_t num_sequences, const 253 | // SequenceBatch &reference) { 254 | // for (uint32_t rid = 0; rid < num_sequences; ++rid) { 255 | // uint32_t sequence_length = reference.GetSequenceLengthAt(rid); 256 | // const char *sequence_name = reference.GetSequenceNameAt(rid); 257 | // for (uint32_t position = 0; position < sequence_length; position += 258 | // bin_size) { 259 | // fprintf(peak_output_file_, "%s\t%u\t%u\n", sequence_name, position + 260 | // 1, position + bin_size); 261 | // } 262 | // } 263 | //} 264 | // void OutputPeaks(uint32_t peak_start_position, uint16_t peak_length, 265 | // uint32_t rid, const SequenceBatch &reference) { 266 | // const char *sequence_name = reference.GetSequenceNameAt(rid); 267 | // fprintf(peak_output_file_, "%s\t%u\t%u\n", sequence_name, 268 | // peak_start_position + 1, peak_start_position + peak_length); 269 | //} 270 | // void AppendBarcodeOutput(uint32_t barcode_key) { 271 | // fprintf(barcode_output_file_, "%s-1\n", Seed2Sequence(barcode_key, 272 | // cell_barcode_length_).data()); 273 | //} 274 | // void WriteMatrixOutputHead(uint64_t num_peaks, uint64_t num_barcodes, 275 | // uint64_t num_lines) { 276 | // fprintf(matrix_output_file_, "%lu\t%lu\t%lu\n", num_peaks, num_barcodes, 277 | // num_lines); 278 | //} 279 | // void AppendMatrixOutput(uint32_t peak_index, uint32_t barcode_index, 280 | // uint32_t num_mappings) { 281 | // fprintf(matrix_output_file_, "%u\t%u\t%u\n", peak_index, barcode_index, 282 | // num_mappings); 283 | //} 284 | inline void FinalizeMatrixOutput() { 285 | fclose(matrix_output_file_); 286 | fclose(peak_output_file_); 287 | fclose(barcode_output_file_); 288 | } 289 | 290 | protected: 291 | std::string mapping_output_file_path_; 292 | FILE *mapping_output_file_; 293 | uint32_t num_mappings_; 294 | uint32_t cell_barcode_length_ = 16; 295 | std::string matrix_output_prefix_; 296 | FILE *peak_output_file_; 297 | FILE *barcode_output_file_; 298 | FILE *matrix_output_file_; 299 | }; 300 | 301 | // template 302 | // class BEDOutputTools : public OutputTools { 303 | // inline void AppendMapping(uint32_t rid, const SequenceBatch &reference, 304 | // const MappingRecord &mapping) { 305 | // std::string strand = (mapping.direction & 1) == 1 ? "+" : "-"; 306 | // const char *reference_sequence_name = reference.GetSequenceNameAt(rid); 307 | // uint32_t mapping_end_position = mapping.fragment_start_position + 308 | // mapping.fragment_length; 309 | // this->AppendMappingOutput(std::string(reference_sequence_name) + "\t" + 310 | // std::to_string(mapping.fragment_start_position) + "\t" + 311 | // std::to_string(mapping_end_position) + "\tN\t1000\t" + strand + "\n"); 312 | // } 313 | //}; 314 | // 315 | // template <> 316 | // class BEDOutputTools : public 317 | // OutputTools { 318 | // inline void AppendMapping(uint32_t rid, const SequenceBatch &reference, 319 | // const MappingWithBarcode &mapping) { 320 | // std::string strand = (mapping.direction & 1) == 1 ? "+" : "-"; 321 | // const char *reference_sequence_name = reference.GetSequenceNameAt(rid); 322 | // uint32_t mapping_end_position = mapping.fragment_start_position + 323 | // mapping.fragment_length; 324 | // this->AppendMappingOutput(std::string(reference_sequence_name) + "\t" + 325 | // std::to_string(mapping.fragment_start_position) + "\t" + 326 | // std::to_string(mapping_end_position) + "\t" + 327 | // Seed2Sequence(mapping.cell_barcode, cell_barcode_length_) +"\n"); 328 | // } 329 | //}; 330 | 331 | template 332 | class PAFOutputTools : public OutputTools {}; 333 | 334 | template <> 335 | class PAFOutputTools : public OutputTools { 336 | inline void AppendMapping(uint32_t rid, const SequenceBatch &reference, 337 | const PAFMapping &mapping) { 338 | const char *reference_sequence_name = reference.GetSequenceNameAt(rid); 339 | uint32_t reference_sequence_length = reference.GetSequenceLengthAt(rid); 340 | std::string strand = (mapping.direction & 1) == 1 ? "+" : "-"; 341 | uint32_t mapping_end_position = 342 | mapping.fragment_start_position + mapping.fragment_length; 343 | this->AppendMappingOutput( 344 | mapping.read_name + "\t" + std::to_string(mapping.read_length) + "\t" + 345 | std::to_string(mapping.read_start_position) + "\t" + 346 | std::to_string(mapping.read_end_position) + "\t" + strand + "\t" + 347 | std::string(reference_sequence_name) + "\t" + 348 | std::to_string(reference_sequence_length) + "\t" + 349 | std::to_string(mapping.fragment_start_position) + "\t" + 350 | std::to_string(mapping_end_position) + "\t" + 351 | std::to_string(mapping.read_length) + "\t" + 352 | std::to_string(mapping.fragment_length) + "\t" + 353 | std::to_string(mapping.mapq) + "\t" + mapping.tags + "\n"); 354 | } 355 | }; 356 | 357 | template <> 358 | class PAFOutputTools 359 | : public OutputTools { 360 | inline void AppendMapping(uint32_t rid, const SequenceBatch &reference, 361 | const MappingWithBarcode &mapping) { 362 | const char *reference_sequence_name = reference.GetSequenceNameAt(rid); 363 | uint32_t reference_sequence_length = reference.GetSequenceLengthAt(rid); 364 | std::string strand = (mapping.direction & 1) == 1 ? "+" : "-"; 365 | uint32_t mapping_end_position = 366 | mapping.fragment_start_position + mapping.fragment_length; 367 | this->AppendMappingOutput( 368 | std::to_string(mapping.read_id) + "\t" + 369 | std::to_string(mapping.fragment_length) + "\t" + std::to_string(0) + 370 | "\t" + std::to_string(mapping.fragment_length) + "\t" + strand + "\t" + 371 | std::string(reference_sequence_name) + "\t" + 372 | std::to_string(reference_sequence_length) + "\t" + 373 | std::to_string(mapping.fragment_start_position) + "\t" + 374 | std::to_string(mapping_end_position) + "\t" + 375 | std::to_string(mapping.fragment_length) + "\t" + 376 | std::to_string(mapping.fragment_length) + "\t" + 377 | std::to_string(mapping.mapq) + "\n"); 378 | } 379 | }; 380 | 381 | template <> 382 | class PAFOutputTools 383 | : public OutputTools { 384 | inline void AppendMapping(uint32_t rid, const SequenceBatch &reference, 385 | const MappingWithoutBarcode &mapping) { 386 | const char *reference_sequence_name = reference.GetSequenceNameAt(rid); 387 | uint32_t reference_sequence_length = reference.GetSequenceLengthAt(rid); 388 | std::string strand = (mapping.direction & 1) == 1 ? "+" : "-"; 389 | uint32_t mapping_end_position = 390 | mapping.fragment_start_position + mapping.fragment_length; 391 | this->AppendMappingOutput( 392 | std::to_string(mapping.read_id) + "\t" + 393 | std::to_string(mapping.fragment_length) + "\t" + std::to_string(0) + 394 | "\t" + std::to_string(mapping.fragment_length) + "\t" + strand + "\t" + 395 | std::string(reference_sequence_name) + "\t" + 396 | std::to_string(reference_sequence_length) + "\t" + 397 | std::to_string(mapping.fragment_start_position) + "\t" + 398 | std::to_string(mapping_end_position) + "\t" + 399 | std::to_string(mapping.fragment_length) + "\t" + 400 | std::to_string(mapping.fragment_length) + "\t" + 401 | std::to_string(mapping.mapq) + "\n"); 402 | } 403 | }; 404 | } // namespace sigmap 405 | 406 | #endif // OUTPUTTOOLS_H_ 407 | -------------------------------------------------------------------------------- /src/pore_model.cc: -------------------------------------------------------------------------------- 1 | #include "pore_model.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "utils.h" 9 | 10 | namespace sigmap { 11 | void PoreModel::Load(const std::string &pore_model_file_path) { 12 | double real_start_time = GetRealTime(); 13 | int num_kmers = 0; 14 | std::ifstream pore_model_file_stream(pore_model_file_path); 15 | std::string pore_model_file_line; 16 | bool first_line = true; 17 | while (getline(pore_model_file_stream, pore_model_file_line)) { 18 | std::stringstream pore_model_file_line_string_stream(pore_model_file_line); 19 | // skip the header 20 | if (pore_model_file_line[0] == '#' || 21 | pore_model_file_line.find("kmer") == 0) { 22 | continue; 23 | } 24 | std::string kmer; 25 | pore_model_file_line_string_stream >> kmer; 26 | if (first_line) { 27 | kmer_size_ = kmer.length(); 28 | // Allocate memory to save pore model parameters 29 | size_t num_pore_models = 1 << (kmer_size_ * 2); 30 | pore_models_.assign(num_pore_models, PoreModelParameters()); 31 | first_line = false; 32 | } 33 | assert(kmer.length() == (size_t)kmer_size_); 34 | uint64_t kmer_hash_value = 35 | GenerateSeedFromSequence(kmer.data(), kmer_size_, 0, kmer_size_); 36 | PoreModelParameters &pore_model_parameters = pore_models_[kmer_hash_value]; 37 | pore_model_file_line_string_stream >> pore_model_parameters.level_mean >> 38 | pore_model_parameters.level_stdv >> pore_model_parameters.sd_mean >> 39 | pore_model_parameters.sd_stdv; 40 | ++num_kmers; 41 | } 42 | std::cerr << "Loaded " << num_kmers << " kmers in " 43 | << GetRealTime() - real_start_time << "s.\n"; 44 | } 45 | 46 | void PoreModel::Print() { 47 | size_t num_pore_models = 1 << (kmer_size_ * 2); 48 | for (size_t i = 0; i < num_pore_models; ++i) { 49 | std::cerr << i << " " << pore_models_[i].level_mean << " " 50 | << pore_models_[i].level_stdv << " " << pore_models_[i].sd_mean 51 | << " " << pore_models_[i].sd_stdv << "\n"; 52 | } 53 | } 54 | 55 | // This funtion return a array of level means given the [start, end) positions 56 | // (0-based). 57 | std::vector PoreModel::GetLevelMeansAt(const char *sequence, 58 | uint32_t start_position, 59 | uint32_t end_position) const { 60 | // Note that the start and end positions should be checked before calling this 61 | // function 62 | int32_t signal_length = end_position - start_position - kmer_size_ + 1; 63 | assert(signal_length > 0); 64 | std::vector signal_values; 65 | signal_values.reserve(signal_length); 66 | uint32_t mask = ((uint32_t)1 << (2 * kmer_size_)) - 1; 67 | uint32_t hash_value = GenerateSeedFromSequence( 68 | sequence, start_position + signal_length, start_position, kmer_size_); 69 | signal_values.emplace_back(pore_models_[hash_value].level_mean); 70 | for (uint32_t position = start_position + 1; 71 | position < end_position - kmer_size_ + 1; ++position) { 72 | uint8_t current_base = CharToUint8(sequence[position + kmer_size_]); 73 | if (current_base < 4) { 74 | hash_value = ((hash_value << 2) | current_base) & mask; 75 | } else { 76 | hash_value = (hash_value << 2) & mask; 77 | } 78 | signal_values.emplace_back(pore_models_[hash_value].level_mean); 79 | } 80 | return signal_values; 81 | } 82 | } // namespace sigmap 83 | -------------------------------------------------------------------------------- /src/pore_model.h: -------------------------------------------------------------------------------- 1 | #ifndef POREMODEL_H_ 2 | #define POREMODEL_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include "utils.h" 8 | 9 | namespace sigmap { 10 | struct PoreModelParameters { 11 | uint16_t kmer; 12 | float level_mean; 13 | float level_stdv; 14 | float sd_mean; 15 | float sd_stdv; 16 | // float weight; // No need to store weight 17 | }; 18 | 19 | class PoreModel { 20 | public: 21 | PoreModel() {} 22 | ~PoreModel() {} 23 | void Load(const std::string &pore_model_file_path); 24 | void Print(); 25 | std::vector GetLevelMeansAt(const char *sequence, 26 | uint32_t start_position, 27 | uint32_t end_position) const; 28 | int GetKmerSize() const { return kmer_size_; } 29 | 30 | protected: 31 | int kmer_size_; 32 | std::vector pore_models_; 33 | }; 34 | } // namespace sigmap 35 | 36 | #endif // POREMODEL_H_ 37 | -------------------------------------------------------------------------------- /src/sequence_batch.cc: -------------------------------------------------------------------------------- 1 | #include "sequence_batch.h" 2 | 3 | #include 4 | 5 | #include "utils.h" 6 | 7 | namespace sigmap { 8 | void SequenceBatch::InitializeLoading(const std::string &sequence_file_path) { 9 | sequence_file_path_ = sequence_file_path; 10 | sequence_file_ = gzopen(sequence_file_path_.c_str(), "r"); 11 | if (sequence_file_ == NULL) { 12 | ExitWithMessage("Cannot find sequence file!"); 13 | } 14 | sequence_kseq_ = kseq_init(sequence_file_); 15 | } 16 | 17 | uint32_t SequenceBatch::LoadBatch() { 18 | double real_start_time = GetRealTime(); 19 | uint32_t num_sequences = 0; 20 | num_bases_ = 0; 21 | for (uint32_t sequence_index = 0; sequence_index < max_num_sequences_; 22 | ++sequence_index) { 23 | int length = kseq_read(sequence_kseq_); 24 | while (length == 0) { // Skip the sequences of length 0 25 | length = kseq_read(sequence_kseq_); 26 | } 27 | if (length > 0) { 28 | kseq_t *sequence = sequence_batch_[sequence_index]; 29 | std::swap(sequence_kseq_->seq, sequence->seq); 30 | std::swap(sequence_kseq_->name, sequence->name); 31 | std::swap(sequence_kseq_->comment, sequence->comment); 32 | if (sequence_kseq_->qual.l != 0) { // fastq file 33 | std::swap(sequence_kseq_->qual, sequence->qual); 34 | } 35 | sequence->id = num_loaded_sequences_; 36 | ++num_loaded_sequences_; 37 | ++num_sequences; 38 | num_bases_ += length; 39 | } else { 40 | if (length != -1) { 41 | ExitWithMessage( 42 | "Didn't reach the end of sequence file, which might be corrupted!"); 43 | } 44 | // make sure to reach the end of file rather than meet an error 45 | break; 46 | } 47 | } 48 | if (num_sequences != 0) { 49 | std::cerr << "Number of sequences: " << num_sequences << ".\n"; 50 | std::cerr << "Number of bases: " << num_bases_ << ".\n"; 51 | std::cerr << "Loaded sequence batch successfully in " 52 | << GetRealTime() - real_start_time << "s.\n"; 53 | } else { 54 | std::cerr << "No more sequences.\n"; 55 | } 56 | return num_sequences; 57 | } 58 | 59 | bool SequenceBatch::LoadOneSequenceAndSaveAt(uint32_t sequence_index) { 60 | bool no_more_sequence = false; 61 | int length = kseq_read(sequence_kseq_); 62 | while (length == 0) { // Skip the sequences of length 0 63 | length = kseq_read(sequence_kseq_); 64 | } 65 | if (length > 0) { 66 | kseq_t *sequence = sequence_batch_[sequence_index]; 67 | std::swap(sequence_kseq_->seq, sequence->seq); 68 | std::swap(sequence_kseq_->name, sequence->name); 69 | std::swap(sequence_kseq_->comment, sequence->comment); 70 | sequence->id = num_loaded_sequences_; 71 | ++num_loaded_sequences_; 72 | if (sequence_kseq_->qual.l != 0) { // fastq file 73 | std::swap(sequence_kseq_->qual, sequence->qual); 74 | } 75 | } else { 76 | if (length != -1) { 77 | ExitWithMessage( 78 | "Didn't reach the end of sequence file, which might be corrupted!"); 79 | } 80 | // make sure to reach the end of file rather than meet an error 81 | no_more_sequence = true; 82 | } 83 | return no_more_sequence; 84 | } 85 | 86 | uint32_t SequenceBatch::LoadAllSequences() { 87 | double real_start_time = GetRealTime(); 88 | sequence_batch_.reserve(200); 89 | uint32_t num_sequences = 0; 90 | num_bases_ = 0; 91 | int length = kseq_read(sequence_kseq_); 92 | while (length >= 0) { 93 | if (length == 0) { // Skip the sequences of length 0 94 | continue; 95 | } else if (length > 0) { 96 | sequence_batch_.emplace_back((kseq_t *)calloc(1, sizeof(kseq_t))); 97 | kseq_t *sequence = sequence_batch_.back(); 98 | std::swap(sequence_kseq_->seq, sequence->seq); 99 | std::swap(sequence_kseq_->name, sequence->name); 100 | std::swap(sequence_kseq_->comment, sequence->comment); 101 | if (sequence_kseq_->qual.l != 0) { // fastq file 102 | std::swap(sequence_kseq_->qual, sequence->qual); 103 | } 104 | sequence->id = num_loaded_sequences_; 105 | ++num_loaded_sequences_; 106 | ++num_sequences; 107 | num_bases_ += length; 108 | } else { 109 | if (length != -1) { 110 | ExitWithMessage( 111 | "Didn't reach the end of sequence file, which might be corrupted!"); 112 | } 113 | // make sure to reach the end of file rather than meet an error 114 | break; 115 | } 116 | length = kseq_read(sequence_kseq_); 117 | } 118 | negative_sequence_batch_.assign(num_sequences, ""); 119 | std::cerr << "Number of sequences: " << num_sequences << ".\n"; 120 | std::cerr << "Number of bases: " << num_bases_ << ".\n"; 121 | std::cerr << "Loaded all sequences successfully in " 122 | << GetRealTime() - real_start_time << "s.\n"; 123 | return num_sequences; 124 | } 125 | 126 | void SequenceBatch::FinalizeLoading() { 127 | kseq_destroy(sequence_kseq_); 128 | gzclose(sequence_file_); 129 | } 130 | } // namespace sigmap 131 | -------------------------------------------------------------------------------- /src/sequence_batch.h: -------------------------------------------------------------------------------- 1 | #ifndef SEQUENCEBATCH_H_ 2 | #define SEQUENCEBATCH_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | #include "kseq.h" 12 | #include "utils.h" 13 | 14 | namespace sigmap { 15 | class SequenceBatch { 16 | public: 17 | KSEQ_INIT(gzFile, gzread); 18 | SequenceBatch() {} 19 | SequenceBatch(uint32_t max_num_sequences) 20 | : max_num_sequences_(max_num_sequences) { 21 | // Construct once and use update methods when loading each batch 22 | sequence_batch_.reserve(max_num_sequences_); 23 | for (uint32_t i = 0; i < max_num_sequences_; ++i) { 24 | sequence_batch_.emplace_back((kseq_t *)calloc(1, sizeof(kseq_t))); 25 | } 26 | negative_sequence_batch_.assign(max_num_sequences_, ""); 27 | } 28 | ~SequenceBatch() { 29 | if (sequence_batch_.size() > 0) { 30 | for (uint32_t i = 0; i < sequence_batch_.size(); ++i) { 31 | free(sequence_batch_[i]); 32 | } 33 | } 34 | } 35 | inline uint32_t GetMaxBatchSize() const { return max_num_sequences_; } 36 | inline uint64_t GetNumBases() const { return num_bases_; } 37 | inline std::vector &GetSequenceBatch() { return sequence_batch_; } 38 | inline std::vector &GetNegativeSequenceBatch() { 39 | return negative_sequence_batch_; 40 | } 41 | inline const char *GetSequenceAt(uint32_t sequence_index) const { 42 | return sequence_batch_[sequence_index]->seq.s; 43 | } 44 | inline uint32_t GetSequenceLengthAt(uint32_t sequence_index) const { 45 | return sequence_batch_[sequence_index]->seq.l; 46 | } 47 | inline const char *GetSequenceNameAt(uint32_t sequence_index) const { 48 | return sequence_batch_[sequence_index]->name.s; 49 | } 50 | inline uint32_t GetSequenceNameLengthAt(uint32_t sequence_index) const { 51 | return sequence_batch_[sequence_index]->name.l; 52 | } 53 | inline uint32_t GetSequenceIdAt(uint32_t sequence_index) const { 54 | return sequence_batch_[sequence_index]->id; 55 | } 56 | inline const std::string &GetNegativeSequenceAt( 57 | uint32_t sequence_index) const { 58 | return negative_sequence_batch_[sequence_index]; 59 | } 60 | // inline char GetReverseComplementBaseOfSequenceAt(uint32_t sequence_index, 61 | // uint32_t position) { 62 | // kseq_t *sequence = sequence_batch_[sequence_index]; 63 | // return Uint8ToChar(((uint8_t)3) ^ 64 | // (CharToUint8((sequence->seq.s)[sequence->seq.l - position - 1]))); 65 | // } 66 | inline void PrepareNegativeSequenceAt(uint32_t sequence_index) { 67 | kseq_t *sequence = sequence_batch_[sequence_index]; 68 | uint32_t sequence_length = sequence->seq.l; 69 | std::string &negative_sequence = negative_sequence_batch_[sequence_index]; 70 | negative_sequence.clear(); 71 | negative_sequence.reserve(sequence_length); 72 | for (uint32_t i = 0; i < sequence_length; ++i) { 73 | negative_sequence.push_back(Uint8ToChar( 74 | ((uint8_t)3) ^ 75 | (CharToUint8((sequence->seq.s)[sequence_length - i - 1])))); 76 | } 77 | } 78 | inline void TrimSequenceAt(uint32_t sequence_index, int length_after_trim) { 79 | kseq_t *sequence = sequence_batch_[sequence_index]; 80 | negative_sequence_batch_[sequence_index].erase( 81 | negative_sequence_batch_[sequence_index].begin(), 82 | negative_sequence_batch_[sequence_index].begin() + sequence->seq.l - 83 | length_after_trim); 84 | sequence->seq.l = length_after_trim; 85 | } 86 | inline void SwapSequenceBatch(SequenceBatch &batch) { 87 | sequence_batch_.swap(batch.GetSequenceBatch()); 88 | negative_sequence_batch_.swap(batch.GetNegativeSequenceBatch()); 89 | } 90 | void InitializeLoading(const std::string &sequence_file_path); 91 | void FinalizeLoading(); 92 | // Return the number of reads loaded into the batch 93 | // and return 0 if there is no more reads 94 | uint32_t LoadBatch(); 95 | bool LoadOneSequenceAndSaveAt(uint32_t sequence_index); 96 | uint32_t LoadAllSequences(); 97 | 98 | inline static uint8_t CharToUint8(const char c) { 99 | return char_to_uint8_table_[(uint8_t)c]; 100 | } 101 | inline static char Uint8ToChar(const uint8_t i) { 102 | return uint8_to_char_table_[i]; 103 | } 104 | 105 | inline uint64_t GenerateSeedFromSequenceAt(uint32_t sequence_index, 106 | uint32_t start_position, 107 | uint32_t seed_length) const { 108 | const char *sequence = GetSequenceAt(sequence_index); 109 | uint32_t sequence_length = GetSequenceLengthAt(sequence_index); 110 | uint64_t mask = (((uint64_t)1) << (2 * seed_length)) - 1; 111 | uint64_t seed = 0; 112 | for (uint32_t i = 0; i < seed_length; ++i) { 113 | if (start_position + i < sequence_length) { 114 | uint8_t current_base = 115 | SequenceBatch::CharToUint8(sequence[i + start_position]); 116 | if (current_base < 4) { // not an ambiguous base 117 | seed = ((seed << 2) | current_base) & mask; // forward k-mer 118 | } else { 119 | seed = (seed << 2) & mask; // N->A 120 | } 121 | } else { 122 | seed = (seed << 2) & mask; // Pad A 123 | } 124 | } 125 | return seed; 126 | } 127 | 128 | protected: 129 | uint32_t num_loaded_sequences_ = 0; 130 | uint32_t max_num_sequences_; 131 | uint64_t num_bases_; 132 | std::string sequence_file_path_; 133 | gzFile sequence_file_; 134 | kseq_t *sequence_kseq_; 135 | std::vector sequence_batch_; 136 | std::vector negative_sequence_batch_; 137 | }; 138 | } // namespace sigmap 139 | 140 | #endif // SEQUENCEBATCH_H_ 141 | -------------------------------------------------------------------------------- /src/sigmap.h: -------------------------------------------------------------------------------- 1 | #ifndef SIGMAP_H_ 2 | #define SIGMAP_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include "event.h" 8 | #include "output_tools.h" 9 | #include "signal_batch.h" 10 | #include "utils.h" 11 | 12 | namespace sigmap { 13 | class SigmapDriver { 14 | public: 15 | SigmapDriver() {} 16 | ~SigmapDriver() {} 17 | void ParseArgsAndRun(int argc, char *argv[]); 18 | }; 19 | 20 | class Sigmap { 21 | public: 22 | Sigmap() {} 23 | ~Sigmap() {} 24 | // for index construction 25 | Sigmap(int dimension, int max_leaf, const std::string &reference_file_path, 26 | const std::string &pore_model_file_path, 27 | const std::string &output_file_path) 28 | : dimension_(dimension), 29 | max_leaf_(max_leaf), 30 | reference_file_path_(reference_file_path), 31 | pore_model_file_path_(pore_model_file_path), 32 | output_file_path_(output_file_path) {} 33 | void ConstructIndex(); 34 | // for mapping 35 | Sigmap(int num_threads, const std::string &reference_file_path, 36 | const std::string &pore_model_file_path, 37 | const std::string &signal_directory, 38 | const std::string &reference_index_file_path, 39 | const std::string &output_file_path) 40 | : num_threads_(num_threads), 41 | reference_file_path_(reference_file_path), 42 | pore_model_file_path_(pore_model_file_path), 43 | signal_directory_(signal_directory), 44 | reference_index_file_path_(reference_index_file_path), 45 | output_file_path_(output_file_path) {} 46 | Sigmap(float search_radius, int read_seeding_step_size, int num_threads, 47 | int max_num_chunks, int stop_mapping_min_num_anchors, 48 | int output_mapping_min_num_anchors, float stop_mapping_ratio, 49 | float output_mapping_ratio, float stop_mapping_mean_ratio, 50 | float output_mapping_mean_ratio, 51 | const std::string &reference_file_path, 52 | const std::string &pore_model_file_path, 53 | const std::string &signal_directory, 54 | const std::string &reference_index_file_path, 55 | const std::string &output_file_path) 56 | : search_radius_(search_radius), 57 | read_seeding_step_size_(read_seeding_step_size), 58 | num_threads_(num_threads), 59 | max_num_chunks_(max_num_chunks), 60 | stop_mapping_min_num_anchors_(stop_mapping_min_num_anchors), 61 | output_mapping_min_num_anchors_(output_mapping_min_num_anchors), 62 | stop_mapping_ratio_(stop_mapping_ratio), 63 | output_mapping_ratio_(output_mapping_ratio), 64 | stop_mapping_mean_ratio_(stop_mapping_mean_ratio), 65 | output_mapping_mean_ratio_(output_mapping_mean_ratio), 66 | reference_file_path_(reference_file_path), 67 | pore_model_file_path_(pore_model_file_path), 68 | signal_directory_(signal_directory), 69 | reference_index_file_path_(reference_index_file_path), 70 | output_file_path_(output_file_path) {} 71 | void Map(); 72 | void StreamingMap(); 73 | void DTWAlign(); 74 | void CWTAlign(); 75 | // Support functions 76 | void GenerateEvents(size_t start, size_t end, const Signal &signal, 77 | std::vector &feature_signal, 78 | std::vector &feature_signal_stdvs); 79 | void GenerateFeatureSignalUsingCWT(const Signal &signal, float scale0, 80 | std::vector &feature_signal, 81 | std::vector &feature_positions); 82 | float GenerateMADNormalizedSignal(const float *signal_values, 83 | size_t signal_length, 84 | std::vector &normalized_signal); 85 | float GenerateZscoreNormalizedSignal(const float *signal_values, 86 | size_t signal_length, 87 | std::vector &normalized_signal); 88 | void GenerateCWTSignal(const float *signal_values, size_t signal_length, 89 | float scale0, std::vector &cwt_signal); 90 | void GeneratePeaks(const float *signal_values, size_t signal_length, 91 | float selective, std::vector &peaks, 92 | std::vector &peak_positions); 93 | float sDTW(const Signal &target_signal, const Signal &query_signal); 94 | float sDTW(const float *target_signal_values, size_t target_length, 95 | const float *query_signal_values, size_t query_length, 96 | ssize_t &mapping_end_position); 97 | // void EmplaceBackMappingRecord(uint32_t read_id, const char *read_name, 98 | // uint32_t read_length, uint32_t barcode, uint32_t fragment_start_position, 99 | // uint32_t fragment_length, uint8_t mapq, uint8_t direction, uint8_t 100 | // is_unique, std::vector *mappings_on_diff_ref_seqs); 101 | void OutputMappingsInVector( 102 | uint8_t mapq_threshold, uint32_t num_reference_sequences, 103 | const SequenceBatch &reference, 104 | const std::vector > &mappings); 105 | uint32_t MoveMappingsInBuffersToMappingContainer( 106 | uint32_t num_reference_sequences, 107 | std::vector > > 108 | *mappings_on_diff_ref_seqs_for_diff_threads_for_saving); 109 | void GenerateMaskedPositions( 110 | int kmer_size, float frequency, uint32_t num_reference_sequences, 111 | const SequenceBatch &sequence_batch, 112 | std::vector > &positive_is_masked, 113 | std::vector > &negative_is_masked); 114 | // Output debug files 115 | void FAST5ToText(); 116 | void EventsToText(); 117 | 118 | protected: 119 | int dimension_; 120 | int max_leaf_; 121 | float search_radius_; 122 | int read_seeding_step_size_; 123 | int num_threads_; 124 | int max_num_chunks_; 125 | int stop_mapping_min_num_anchors_; 126 | int output_mapping_min_num_anchors_; 127 | float stop_mapping_ratio_; 128 | float output_mapping_ratio_; 129 | float stop_mapping_mean_ratio_; 130 | float output_mapping_mean_ratio_; 131 | std::string reference_file_path_; 132 | std::string pore_model_file_path_; 133 | std::string signal_directory_; 134 | std::string reference_index_file_path_; 135 | std::string output_file_path_; 136 | std::unique_ptr > output_tools_; 137 | std::vector > mappings_on_diff_ref_seqs_; 138 | }; 139 | } // namespace sigmap 140 | 141 | #endif // SIGMAP_H_ 142 | -------------------------------------------------------------------------------- /src/sigmap_adaptor.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "nanoflann.hpp" 6 | 7 | struct Point { 8 | uint64_t position; 9 | float value; 10 | Point() {} 11 | Point(const float value) : value(value) {} 12 | Point(const uint64_t position, const float value) 13 | : position(position), value(value) {} 14 | bool operator<(const Point &p) const { 15 | return std::tie(value, position) < std::tie(p.value, p.position); 16 | } 17 | }; 18 | // ===== This example shows how to use nanoflann with these types of containers: 19 | // ======= 20 | // typedef std::vector > my_vector_of_vectors_t; 21 | // typedef std::vector my_vector_of_vectors_t; // This 22 | // requires #include 23 | // ===================================================================================== 24 | 25 | /** A simple vector-of-vectors adaptor for nanoflann, without duplicating the 26 | * storage. The i'th vector represents a point in the state space. 27 | * 28 | * \tparam DIM If set to >0, it specifies a compile-time fixed dimensionality 29 | * for the points in the data set, allowing more compiler optimizations. \tparam 30 | * num_t The type of the point coordinates (typically, double or float). \tparam 31 | * Distance The distance metric to use: nanoflann::metric_L1, 32 | * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. \tparam IndexType The 33 | * type for indices in the KD-tree index (typically, size_t of int) 34 | */ 35 | template 37 | struct SigmapAdaptor { 38 | typedef SigmapAdaptor self_t; 39 | typedef 40 | typename Distance::template traits::distance_t metric_t; 41 | typedef nanoflann::KDTreeSingleIndexAdaptor 42 | index_t; 43 | 44 | index_t *index; //! The kd-tree index for the user to call its methods as 45 | //! usual with any other FLANN index. 46 | 47 | size_t dims_; 48 | /// Constructor: takes a const ref to the vector of vectors object with the 49 | /// data points 50 | SigmapAdaptor(const size_t dims /* dimensionality */, 51 | const std::vector &mat, const int leaf_max_size = 10) 52 | : m_data(mat) { 53 | assert(mat.size() != 0); // && mat[0].size() != 0); 54 | // const size_t dims = mat[0].size(); 55 | if (DIM > 0 && static_cast(dims) != DIM) 56 | throw std::runtime_error( 57 | "Data set dimensionality does not match the 'DIM' template argument"); 58 | dims_ = dims; 59 | index = 60 | new index_t(static_cast(dims), *this /* adaptor */, 61 | nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size)); 62 | } 63 | 64 | ~SigmapAdaptor() { delete index; } 65 | 66 | const std::vector &m_data; 67 | 68 | /** Query for the \a num_closest closest points to a given point (entered as 69 | * query_point[0:dim-1]). Note that this is a short-cut method for 70 | * index->findNeighbors(). The user can also call index->... methods as 71 | * desired. \note nChecks_IGNORED is ignored but kept for compatibility with 72 | * the original FLANN interface. 73 | */ 74 | inline void query(const num_t *query_point, const size_t num_closest, 75 | IndexType *out_indices, num_t *out_distances_sq, 76 | const int nChecks_IGNORED = 10) const { 77 | nanoflann::KNNResultSet resultSet(num_closest); 78 | resultSet.init(out_indices, out_distances_sq); 79 | index->findNeighbors(resultSet, query_point, nanoflann::SearchParams()); 80 | } 81 | 82 | /** @name Interface expected by KDTreeSingleIndexAdaptor 83 | * @{ */ 84 | 85 | const self_t &derived() const { return *this; } 86 | self_t &derived() { return *this; } 87 | 88 | // Must return the number of data points 89 | inline size_t kdtree_get_point_count() const { 90 | return m_data.size() - dims_ + 1; 91 | } 92 | 93 | // Returns the dim'th component of the idx'th point in the class: 94 | inline num_t kdtree_get_pt(const size_t idx, const size_t dim) const { 95 | // return m_data[idx][dim]; 96 | return m_data[idx + dim].value; 97 | } 98 | 99 | // Optional bounding-box computation: return false to default to a standard 100 | // bbox computation loop. 101 | // Return true if the BBOX was already computed by the class and returned in 102 | // "bb" so it can be avoided to redo it again. Look at bb.size() to find out 103 | // the expected dimensionality (e.g. 2 or 3 for point clouds) 104 | template 105 | bool kdtree_get_bbox(BBOX & /*bb*/) const { 106 | return false; 107 | } 108 | 109 | /** @} */ 110 | 111 | }; // end of SigmapAdaptor 112 | -------------------------------------------------------------------------------- /src/signal_batch.cc: -------------------------------------------------------------------------------- 1 | #include "signal_batch.h" 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "utils.h" 11 | 12 | namespace sigmap { 13 | void SignalBatch::InitializeLoading(const std::string &signal_directory) { 14 | if (IsDirectory(signal_directory)) { 15 | signal_directory_ = signal_directory; 16 | } else { 17 | ExitWithMessage("Signal directory is in valid!"); 18 | } 19 | } 20 | 21 | void SignalBatch::FinalizeLoading() {} 22 | 23 | size_t SignalBatch::LoadAllReadSignals() { 24 | double real_start_time = GetRealTime(); 25 | auto dir_list = ListDirectory(signal_directory_); 26 | // two rounds, get all the fast5 absolute paths first and then load reads 27 | std::vector fast5_list; 28 | std::vector slow5_list; 29 | for (size_t pi = 0; pi < dir_list.size(); ++pi) { 30 | std::string &relative_path = dir_list[pi]; 31 | if (relative_path == "." or relative_path == "..") { 32 | continue; 33 | } 34 | std::string absolute_path = signal_directory_ + "/" + relative_path; 35 | if (IsDirectory(absolute_path)) { 36 | auto sub_directory_list = ListDirectory(absolute_path); 37 | std::vector sub_relative_paths; 38 | sub_relative_paths.reserve(sub_directory_list.size()); 39 | for (size_t si = 0; si < sub_directory_list.size(); ++si) { 40 | sub_relative_paths.push_back(relative_path + "/" + 41 | sub_directory_list[si]); 42 | } 43 | dir_list.insert(dir_list.end(), sub_relative_paths.begin(), 44 | sub_relative_paths.end()); 45 | } 46 | bool is_fast5 = absolute_path.find(".fast5") != std::string::npos; 47 | bool is_slow5 = absolute_path.find(".blow5") != std::string::npos; 48 | if (is_fast5) { 49 | fast5_list.emplace_back(absolute_path); 50 | }else if(is_slow5) { 51 | slow5_list.emplace_back(absolute_path); 52 | }else{ 53 | // don't put it into index 54 | } 55 | } 56 | signals_.reserve(fast5_list.size()); 57 | for (size_t pi = 0; pi < fast5_list.size(); ++pi) { 58 | AddSignalsFromFAST5(fast5_list[pi]); 59 | } 60 | for (size_t pi = 0; pi < slow5_list.size(); ++pi) { 61 | AddSignalsFromSLOW5(slow5_list[pi]); 62 | } 63 | std::cerr << "Loaded " << signals_.size() << " reads in " 64 | << GetRealTime() - real_start_time << "s.\n"; 65 | return signals_.size(); 66 | } 67 | 68 | void SignalBatch::AddSignalsFromFAST5(const std::string &fast5_file_path) { 69 | hdf5_tools::File fast5_file; 70 | fast5_file.open(fast5_file_path); 71 | // Check format 72 | bool is_single = false; 73 | std::vector fast5_file_groups = fast5_file.list_group("/"); 74 | for (std::string &group : fast5_file_groups) { 75 | if (group == "Raw") { 76 | is_single = true; 77 | break; 78 | } 79 | } 80 | if (is_single) { 81 | for (std::string &read : fast5_file.list_group("/Raw/Reads")) { 82 | std::string read_id = ""; 83 | for (auto a : fast5_file.get_attr_map("/Raw/Reads/" + read)) { 84 | if (a.first == "read_id") { 85 | read_id = a.second; 86 | break; 87 | } 88 | } 89 | if (read_id.empty()) { 90 | std::cerr << "Error: failed to find read_id\n"; 91 | exit(-1); 92 | } 93 | std::string raw_path = "/Raw/Reads/" + read; 94 | std::string ch_path = "/UniqueGlobalKey/channel_id"; 95 | AddSignal(fast5_file, raw_path, ch_path); 96 | } 97 | } else { 98 | signals_.reserve(signals_.size() + fast5_file_groups.size()); 99 | for (std::string &read : fast5_file_groups) { 100 | std::string raw_path = "/" + read + "/Raw"; 101 | std::string ch_path = "/" + read + "/channel_id"; 102 | AddSignal(fast5_file, raw_path, ch_path); 103 | } 104 | } 105 | fast5_file.close(); 106 | } 107 | 108 | void SignalBatch::AddSignal(const hdf5_tools::File &file, 109 | const std::string &raw_path, 110 | const std::string &ch_path) { 111 | std::string id; 112 | for (auto a : file.get_attr_map(raw_path)) { 113 | if (a.first == "read_id") { 114 | id = a.second; 115 | } else if (a.first == "read_number") { 116 | // number = atoi(a.second.c_str()); 117 | } else if (a.first == "start_time") { 118 | // start_sample = atoi(a.second.c_str()); 119 | } 120 | } 121 | 122 | float digitisation = 0, range = 0, offset = 0; 123 | for (auto a : file.get_attr_map(ch_path)) { 124 | if (a.first == "channel_number") { 125 | // channel_idx = atoi(a.second.c_str()) - 1; 126 | } else if (a.first == "digitisation") { 127 | digitisation = atof(a.second.c_str()); 128 | } else if (a.first == "range") { 129 | range = atof(a.second.c_str()); 130 | } else if (a.first == "offset") { 131 | offset = atof(a.second.c_str()); 132 | } 133 | } 134 | 135 | std::string sig_path = raw_path + "/Signal"; 136 | std::vector signal_values; 137 | file.read(sig_path, signal_values); 138 | // convert to pA 139 | uint32_t valid_signal_length = 0; 140 | float scale = range / digitisation; 141 | for (size_t i = 0; i < signal_values.size(); i++) { 142 | if ((signal_values[i] + offset) * scale > 30 && 143 | (signal_values[i] + offset) * scale < 200) { 144 | signal_values[valid_signal_length] = (signal_values[i] + offset) * scale; 145 | ++valid_signal_length; 146 | } 147 | } 148 | if (valid_signal_length < signal_values.size()) { 149 | signal_values.erase(signal_values.begin() + valid_signal_length, 150 | signal_values.end()); 151 | } 152 | signals_.emplace_back(Signal{id, digitisation, range, offset, signal_values, 153 | std::vector()}); 154 | } 155 | 156 | void SignalBatch::AddSignalsFromSLOW5(const std::string &slow5_file_path) { 157 | 158 | slow5_file_t *sp = slow5_open(slow5_file_path.c_str(),"r"); 159 | if(sp==NULL){ 160 | fprintf(stderr,"Error in opening file\n"); 161 | exit(EXIT_FAILURE); 162 | } 163 | slow5_rec_t *rec = NULL; 164 | int ret=0; 165 | 166 | while((ret = slow5_get_next(&rec,sp)) >= 0){ 167 | AddSignal(rec); 168 | } 169 | 170 | if(ret != SLOW5_ERR_EOF){ //check if proper end of file has been reached 171 | fprintf(stderr,"Error in slow5_get_next. Error code %d\n",ret); 172 | exit(EXIT_FAILURE); 173 | } 174 | 175 | slow5_rec_free(rec); 176 | 177 | slow5_close(sp); 178 | 179 | } 180 | 181 | 182 | void SignalBatch::AddSignal(slow5_rec_t *rec) { 183 | std::string id; 184 | 185 | id = rec->read_id; 186 | 187 | float digitisation = 0, range = 0, offset = 0; 188 | digitisation = rec->digitisation; 189 | range = rec->range; 190 | offset = rec->offset; 191 | 192 | std::vector signal_values(rec->len_raw_signal); 193 | 194 | // convert to pA 195 | uint32_t valid_signal_length = 0; 196 | float scale = range / digitisation; 197 | for (size_t i = 0; i < rec->len_raw_signal; i++) { 198 | if ((rec->raw_signal[i] + offset) * scale > 30 && 199 | (rec->raw_signal[i] + offset) * scale < 200) { 200 | signal_values[valid_signal_length] = (rec->raw_signal[i] + offset) * scale; 201 | ++valid_signal_length; 202 | } 203 | } 204 | if (valid_signal_length < signal_values.size()) { 205 | signal_values.erase(signal_values.begin() + valid_signal_length, 206 | signal_values.end()); 207 | } 208 | signals_.emplace_back(Signal{id, digitisation, range, offset, signal_values, 209 | std::vector()}); 210 | } 211 | 212 | void SignalBatch::NormalizeSignalAt(size_t signal_index) { 213 | //// Should use a linear algorithm like median of medians 214 | //// But for now let us use sort 215 | // std::vector tmp_signal((signals_[signal_index]).signal_values, 216 | // (signals_[signal_index]).signal_values + 217 | // (signals_[signal_index]).signal_length); 218 | // std::nth_element(tmp_signal.begin(), tmp_signal.begin() + tmp_signal.size() 219 | // / 2, tmp_signal.end()); float signal_median = tmp_signal[tmp_signal.size() 220 | // / 2]; // This is a fake median, but should be okay for a quick 221 | // implementation for (size_t i = 0; i < tmp_signal.size(); ++i) { 222 | // tmp_signal[i] = std::abs(tmp_signal[i] - signal_median); 223 | //} 224 | // std::nth_element(tmp_signal.begin(), tmp_signal.begin() + tmp_signal.size() 225 | // / 2, tmp_signal.end()); float MAD = tmp_signal[tmp_signal.size() / 2]; // 226 | // Again, fake MAD, ok for a quick implementation 227 | //// Now we can normalize signal 228 | // for (size_t i = 0; i < signals_[signal_index].signal_length; ++i) { 229 | // ((signals_[signal_index]).signal_values)[i] = 230 | // (((signals_[signal_index]).signal_values)[i] - signal_median) / MAD; 231 | //} 232 | // Calculate mean 233 | float mean = 0; 234 | for (size_t i = 0; i < signals_[signal_index].GetSignalLength(); ++i) { 235 | mean += signals_[signal_index].signal_values[i]; 236 | } 237 | mean /= signals_[signal_index].signal_values.size(); 238 | // Calculate standard deviation 239 | float stdv = 0; 240 | for (size_t i = 0; i < signals_[signal_index].GetSignalLength(); ++i) { 241 | stdv += (signals_[signal_index].signal_values[i] - mean) * 242 | (signals_[signal_index].signal_values[i] - mean); 243 | } 244 | stdv /= (signals_[signal_index].signal_values.size() - 1); 245 | stdv = sqrt(stdv); 246 | // Now we can normalize signal 247 | for (size_t i = 0; i < signals_[signal_index].signal_values.size(); ++i) { 248 | signals_[signal_index].signal_values[i] = 249 | (signals_[signal_index].signal_values[i] - mean) / stdv; 250 | } 251 | } 252 | 253 | void SignalBatch::ConvertSequencesToSignals(const SequenceBatch &sequence_batch, 254 | const PoreModel &pore_model, 255 | size_t num_sequences) { 256 | double real_start_time = GetRealTime(); 257 | for (size_t sequence_index = 0; sequence_index < num_sequences; 258 | ++sequence_index) { 259 | size_t sequence_length = sequence_batch.GetSequenceLengthAt(sequence_index); 260 | std::vector signal_values = pore_model.GetLevelMeansAt( 261 | sequence_batch.GetSequenceAt(sequence_index), 0, sequence_length); 262 | std::vector negative_signal_values = pore_model.GetLevelMeansAt( 263 | sequence_batch.GetNegativeSequenceAt(sequence_index).data(), 0, 264 | sequence_length); 265 | std::string signal_id(sequence_batch.GetSequenceNameAt(sequence_index)); 266 | signals_.emplace_back( 267 | Signal{signal_id, 0, 0, 0, signal_values, negative_signal_values}); 268 | } 269 | std::cerr << "Convert " << num_sequences << " sequences to signals in " 270 | << GetRealTime() - real_start_time << "s.\n"; 271 | } 272 | } // namespace sigmap 273 | -------------------------------------------------------------------------------- /src/signal_batch.h: -------------------------------------------------------------------------------- 1 | #ifndef SIGNALBATCH_H_ 2 | #define SIGNALBATCH_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "hdf5_tools.hpp" 9 | #include "pore_model.h" 10 | #include "sequence_batch.h" 11 | #include "utils.h" 12 | 13 | namespace sigmap { 14 | struct Signal { 15 | // read group name 16 | std::string id; 17 | // channel_id 18 | float digitisation; 19 | float range; 20 | float offset; 21 | // signal 22 | std::vector signal_values; 23 | std::vector negative_signal_values; 24 | size_t GetSignalLength() const { return signal_values.size(); } 25 | }; 26 | 27 | class SignalBatch { 28 | public: 29 | SignalBatch() {} 30 | ~SignalBatch() {} 31 | void InitializeLoading(const std::string &signal_directory); 32 | void FinalizeLoading(); 33 | size_t LoadAllReadSignals(); 34 | void AddSignal(const hdf5_tools::File &file, const std::string &raw_path, 35 | const std::string &ch_path); 36 | void AddSignal(slow5_rec_t *rec); 37 | void AddSignalsFromFAST5(const std::string &fast5_file_path); 38 | void AddSignalsFromSLOW5(const std::string &slow5_file_path); 39 | void NormalizeSignalAt(size_t signal_index); 40 | void ConvertSequencesToSignals(const SequenceBatch &sequence_batch, 41 | const PoreModel &pore_model, 42 | size_t num_sequences); 43 | const Signal &GetSignalAt(size_t signal_index) const { 44 | return signals_[signal_index]; 45 | } 46 | const char *GetSignalNameAt(size_t signal_index) const { 47 | return signals_[signal_index].id.data(); 48 | } 49 | size_t GetSignalLengthAt(size_t signal_index) const { 50 | return signals_[signal_index].signal_values.size(); 51 | } 52 | 53 | protected: 54 | std::string signal_directory_; 55 | std::vector signals_; 56 | }; 57 | } // namespace sigmap 58 | 59 | #endif // SIGNALBATCH_H_ 60 | -------------------------------------------------------------------------------- /src/spatial_index.cc: -------------------------------------------------------------------------------- 1 | #include "spatial_index.h" 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | 8 | #include "utils.h" 9 | 10 | namespace sigmap { 11 | bool compare(const std::pair &left, 12 | const std::pair &right) { 13 | if (left.first > right.first) { 14 | return true; 15 | } else if (left.first == right.first) { 16 | return (left.second > right.second); 17 | } else { 18 | return false; 19 | } 20 | } 21 | 22 | bool compare1(const std::pair &left, 23 | const std::pair &right) { 24 | if (left.first > right.first) { 25 | return true; 26 | } else if (left.first == right.first) { 27 | return (left.second < right.second); 28 | } else { 29 | return false; 30 | } 31 | } 32 | 33 | void SpatialIndex::GeneratePointCloudOnOneDirection( 34 | Direction direction, uint32_t signal_index, 35 | const std::vector > &is_masked, 36 | const float *signal_values, size_t signal_length, int step_size, 37 | std::vector &point_cloud) { 38 | if (signal_length >= (uint32_t)dimension_) { 39 | for (size_t signal_position = 0; 40 | signal_position < signal_length - dimension_ + 1; 41 | signal_position += step_size) { 42 | if (!is_masked[signal_index][signal_position]) { 43 | if (signal_position == 0 || point_cloud.empty() || 44 | (signal_position > 0 && 45 | std::fabs(signal_values[signal_position] - 46 | point_cloud.back().value) > 0.01)) { 47 | uint64_t strand = direction == Positive ? 0 : 1; 48 | uint64_t position = 49 | ((((uint64_t)signal_index) << 32 | (uint32_t)signal_position) 50 | << 1) | 51 | strand; 52 | point_cloud.emplace_back(position, signal_values[signal_position]); 53 | } 54 | } 55 | } 56 | } 57 | } 58 | 59 | // void SpatialIndex::GetSignalIndexAndPosition(size_t point_index, size_t 60 | // num_signals, const std::vector > &signals, size_t 61 | // &signal_index, size_t &signal_position) { 62 | // for (signal_index = 0; signal_index < num_signals; ++signal_index) { 63 | // signal_position = signals[signal_index].size() - dimension_ + 1; 64 | // if (point_index > signal_position) { 65 | // point_index -= signal_position; 66 | // } else { 67 | // signal_position = point_index; 68 | // break; 69 | // } 70 | // } 71 | //} 72 | 73 | void SpatialIndex::Construct( 74 | size_t num_signals, 75 | const std::vector > &positive_is_masked, 76 | const std::vector > &negative_is_masked, 77 | const std::vector > &positive_signals, 78 | const std::vector > &negative_signals) { 79 | double real_start_time = GetRealTime(); 80 | int signal_point_step_size = 1; 81 | point_cloud_.reserve(2 * GetSignalsTotalLength(positive_signals)); 82 | for (size_t signal_index = 0; signal_index < num_signals; ++signal_index) { 83 | GeneratePointCloudOnOneDirection(Positive, signal_index, positive_is_masked, 84 | positive_signals[signal_index].data(), 85 | positive_signals[signal_index].size(), 86 | signal_point_step_size, point_cloud_); 87 | } 88 | for (size_t signal_index = 0; signal_index < num_signals; ++signal_index) { 89 | GeneratePointCloudOnOneDirection(Negative, signal_index, negative_is_masked, 90 | negative_signals[signal_index].data(), 91 | negative_signals[signal_index].size(), 92 | signal_point_step_size, point_cloud_); 93 | } 94 | std::cerr << "Collected " << point_cloud_.size() << " points.\n"; 95 | // sort(point_cloud_.begin(), point_cloud_.end()); 96 | // std::cerr << "Sorted " << point_cloud_.size() << " points.\n"; 97 | spatial_index_ = new SigmapAdaptor(dimension_ /*dim*/, point_cloud_, 98 | max_leaf_ /* max leaf */); 99 | spatial_index_->index->buildIndex(); 100 | std::cerr << "Built spatial index.\n"; 101 | std::cerr << "Built index successfully in " << GetRealTime() - real_start_time 102 | << "s.\n"; 103 | } 104 | 105 | void SpatialIndex::Save() { 106 | double real_start_time = GetRealTime(); 107 | FILE *point_cloud_file = 108 | fopen((index_file_path_prefix_ + ".pt").c_str(), "wb"); 109 | assert(point_cloud_file != NULL); 110 | fwrite(&dimension_, sizeof(int), 1, point_cloud_file); 111 | fwrite(&max_leaf_, sizeof(int), 1, point_cloud_file); 112 | size_t point_cloud_size = point_cloud_.size(); 113 | fwrite(&point_cloud_size, sizeof(size_t), 1, point_cloud_file); 114 | // TODO(Haowen): we don't have to save the whole point cloud. Instead, we can 115 | // just save the feature signal and build the point cloud on the fly. I will 116 | // leave this as an easy later code refactor work. 117 | // for (size_t pi = 0; pi < point_cloud_size; ++pi) { 118 | // fwrite(point_cloud_[pi].data(), sizeof(float), dimension_, 119 | // point_cloud_file); 120 | //} 121 | fwrite(point_cloud_.data(), sizeof(Point), point_cloud_size, 122 | point_cloud_file); 123 | fclose(point_cloud_file); 124 | FILE *spatial_index_file = 125 | fopen((index_file_path_prefix_ + ".si").c_str(), "wb"); 126 | assert(spatial_index_file != NULL); 127 | spatial_index_->index->saveIndex(spatial_index_file); 128 | fclose(spatial_index_file); 129 | std::cerr << "Saved in " << GetRealTime() - real_start_time << "s.\n"; 130 | } 131 | 132 | void SpatialIndex::Load() { 133 | double real_start_time = GetRealTime(); 134 | FILE *point_cloud_file = 135 | fopen((index_file_path_prefix_ + ".pt").c_str(), "rb"); 136 | fread(&dimension_, sizeof(int), 1, point_cloud_file); 137 | fread(&max_leaf_, sizeof(int), 1, point_cloud_file); 138 | size_t point_cloud_size = 0; 139 | fread(&point_cloud_size, sizeof(size_t), 1, point_cloud_file); 140 | point_cloud_.resize(point_cloud_size); 141 | // for (size_t pi = 0; pi < point_cloud_size; ++pi) { 142 | // point_cloud_[pi].resize(dimension_); 143 | // fread(point_cloud_[pi].data(), sizeof(float), dimension_, 144 | // point_cloud_file); 145 | //} 146 | fread(point_cloud_.data(), sizeof(Point), point_cloud_size, point_cloud_file); 147 | fclose(point_cloud_file); 148 | std::cerr << "Load point cloud successfully! dim: " << dimension_ 149 | << ", max leaf: " << max_leaf_ 150 | << ", point cloud size: " << point_cloud_size << "\n"; 151 | FILE *spatial_index_file = 152 | fopen((index_file_path_prefix_ + ".si").c_str(), "rb"); 153 | assert(spatial_index_file != NULL); 154 | spatial_index_ = new SigmapAdaptor(dimension_ /*dim*/, point_cloud_, 155 | max_leaf_ /* max leaf */); 156 | spatial_index_->index->loadIndex(spatial_index_file); 157 | size_t used_memory = 158 | spatial_index_->index->usedMemory(*(spatial_index_->index)); 159 | std::cerr << "Memory: " << used_memory << ".\n"; 160 | fclose(spatial_index_file); 161 | std::cerr << "Loaded index successfully in " 162 | << GetRealTime() - real_start_time << "s.\n"; 163 | } 164 | 165 | void SpatialIndex::TracebackChains( 166 | int min_num_anchors, Direction direction, size_t chain_end_anchor_index, 167 | uint32_t chain_target_signal_index, 168 | const std::vector &chaining_scores, 169 | const std::vector &chaining_predecessors, 170 | const std::vector > &anchors_on_diff_signals, 171 | std::vector &anchor_is_used, std::vector &chains) { 172 | if (!anchor_is_used[chain_end_anchor_index]) { 173 | std::vector anchors; 174 | anchors.reserve(100); 175 | bool stop_at_an_used_anchor = false; 176 | size_t chain_start_anchor_index = chain_end_anchor_index; 177 | // Add the end anchor 178 | anchors.push_back(anchors_on_diff_signals[chain_target_signal_index] 179 | [chain_start_anchor_index]); 180 | // The end anchor has an used predecessor 181 | if (chaining_predecessors[chain_start_anchor_index] != 182 | chain_start_anchor_index && 183 | anchor_is_used[chaining_predecessors[chain_start_anchor_index]]) { 184 | stop_at_an_used_anchor = true; 185 | } 186 | anchor_is_used[chain_start_anchor_index] = true; 187 | uint32_t chain_num_anchors = 1; 188 | while (chaining_predecessors[chain_start_anchor_index] != 189 | chain_start_anchor_index && 190 | !anchor_is_used[chaining_predecessors[chain_start_anchor_index]]) { 191 | chain_start_anchor_index = 192 | chaining_predecessors[chain_start_anchor_index]; 193 | anchors.push_back(anchors_on_diff_signals[chain_target_signal_index] 194 | [chain_start_anchor_index]); 195 | if (chaining_predecessors[chain_start_anchor_index] != 196 | chain_start_anchor_index && 197 | anchor_is_used[chaining_predecessors[chain_start_anchor_index]]) { 198 | stop_at_an_used_anchor = true; 199 | } 200 | anchor_is_used[chain_start_anchor_index] = true; 201 | ++chain_num_anchors; 202 | } 203 | if (chain_num_anchors >= (uint32_t)min_num_anchors) { 204 | float adjusted_chaining_score = chaining_scores[chain_end_anchor_index]; 205 | if (stop_at_an_used_anchor) { 206 | adjusted_chaining_score -= 207 | chaining_scores[chaining_predecessors[chain_start_anchor_index]]; 208 | } 209 | chains.emplace_back( 210 | SignalAnchorChain{adjusted_chaining_score, chain_target_signal_index, 211 | anchors_on_diff_signals[chain_target_signal_index] 212 | [chain_start_anchor_index] 213 | .target_position, 214 | anchors_on_diff_signals[chain_target_signal_index] 215 | [chain_end_anchor_index] 216 | .target_position, 217 | chain_num_anchors, 0, direction, anchors}); 218 | } 219 | } 220 | } 221 | 222 | void SpatialIndex::GeneratePrimaryChains( 223 | std::vector &chains) { 224 | std::sort(chains.begin(), chains.end(), std::greater()); 225 | std::vector primary_chains; 226 | primary_chains.reserve(chains.size()); 227 | primary_chains.emplace_back(chains[0]); 228 | for (uint32_t ci = 1; ci < chains.size(); ++ci) { 229 | bool is_primary = true; 230 | if (chains[ci].score < primary_chains.back().score / 3) { 231 | break; 232 | } else { 233 | for (uint32_t pi = 0; pi < primary_chains.size(); ++pi) { 234 | if (chains[ci].reference_sequence_index == 235 | primary_chains[pi].reference_sequence_index) { 236 | if (std::max(chains[ci].start_position, 237 | primary_chains[pi].start_position) > 238 | std::min(chains[ci].end_position, 239 | primary_chains[pi].end_position)) { 240 | // primary_chains[pi].score += chains[ci].score; 241 | } else { 242 | is_primary = false; 243 | break; 244 | } 245 | } 246 | } 247 | } 248 | if (is_primary) { 249 | primary_chains.emplace_back(chains[ci]); 250 | } 251 | } 252 | chains.swap(primary_chains); 253 | } 254 | 255 | void SpatialIndex::ComputeMAPQ(std::vector &chains) { 256 | if (chains.size() == 1) { 257 | chains[0].mapq = 60; 258 | return; 259 | } else { 260 | int mapq = 261 | 40 * 262 | (1 - 263 | chains[1].score / 264 | chains[0].score); // * std::min((size_t)1, chains[0].num_anchors / 265 | // 20) * log(chains[0].score); 266 | if (mapq > 60) { 267 | mapq = 60; 268 | } 269 | if (mapq < 0) { 270 | mapq = 0; 271 | } 272 | chains[0].mapq = (uint8_t)mapq; 273 | } 274 | } 275 | 276 | void SpatialIndex::GenerateChains(const std::vector &query_signal, 277 | const std::vector &query_signal_stdvs, 278 | uint32_t query_start_offset, 279 | int query_point_cloud_step_size, 280 | float search_radius, 281 | size_t num_target_signals, 282 | std::vector &chains) { 283 | // Chaining parameters 284 | int max_gap_length = 2000; 285 | int max_target_gap_length = 5000; 286 | int chaining_band_length = 5000; 287 | int max_num_skips = 25; 288 | int min_num_anchors = 2; 289 | int num_best_chains = 3; 290 | int num_nearest_points = 5000; 291 | float min_chaining_score = 10; 292 | std::vector > > anchors_on_diff_signals( 293 | 2); 294 | anchors_on_diff_signals[0] = 295 | std::vector >(num_target_signals); 296 | anchors_on_diff_signals[1] = 297 | std::vector >(num_target_signals); 298 | std::vector > &positive_anchors_on_diff_signals = 299 | anchors_on_diff_signals[0]; 300 | std::vector > &negative_anchors_on_diff_signals = 301 | anchors_on_diff_signals[1]; 302 | // Get anchors in previous chains 303 | std::vector previous_chains; 304 | previous_chains.swap(chains); 305 | if (previous_chains.size() > 0) { 306 | for (uint32_t chain_index = 0; chain_index < previous_chains.size(); 307 | ++chain_index) { 308 | int strand = previous_chains[chain_index].direction == Positive ? 0 : 1; 309 | uint32_t reference_sequence_index = 310 | previous_chains[chain_index].reference_sequence_index; 311 | assert(previous_chains[chain_index].num_anchors == 312 | previous_chains[chain_index].anchors.size()); 313 | anchors_on_diff_signals[strand][reference_sequence_index].reserve( 314 | previous_chains[chain_index].num_anchors); 315 | for (uint32_t anchor_index = 0; 316 | anchor_index < previous_chains[chain_index].num_anchors; 317 | ++anchor_index) { 318 | anchors_on_diff_signals[strand][reference_sequence_index].emplace_back( 319 | previous_chains[chain_index].anchors[anchor_index]); 320 | } 321 | } 322 | } 323 | nanoflann::SearchParams params; 324 | params.sorted = false; 325 | std::vector > point_anchors; 326 | // Find reliable seeds 327 | std::vector > mean_diff_position; 328 | mean_diff_position.reserve( 329 | (query_signal.size() - dimension_ + 1) / query_point_cloud_step_size + 1); 330 | for (uint32_t pi = 0; pi < query_signal.size() - dimension_ + 1; ++pi) { 331 | float min_diff = std::numeric_limits::max(); 332 | // for (int di = 0; di < dimension_; ++di) { 333 | for (int di = 1; di < dimension_; ++di) { 334 | float diff = std::fabs(query_signal[pi + di] - query_signal[pi + di - 1]); 335 | // if (diff < min_diff) { 336 | min_diff += diff; 337 | //} 338 | // float diff = query_signal_stdvs[pi + di]; 339 | // if (diff < min_diff) { 340 | // min_diff = diff; 341 | //} 342 | // min_diff += query_signal_stdvs[pi + di]; 343 | } 344 | mean_diff_position.emplace_back(min_diff, pi); 345 | } 346 | std::sort(mean_diff_position.begin(), mean_diff_position.end(), compare1); 347 | // std::sort(mean_diff_position.begin(), mean_diff_position.end()); 348 | // Collect anchors 349 | uint32_t previous_position = 0; 350 | uint32_t num_positions = 0; 351 | for (uint32_t pi = 0; pi < query_signal.size() - dimension_ + 1; ++pi) { 352 | uint32_t position = mean_diff_position[pi].second; 353 | if (position < previous_position + query_point_cloud_step_size && 354 | position + query_point_cloud_step_size > previous_position) { 355 | continue; 356 | } 357 | // std::cout << position << "\n"; 358 | // size_t num_results = 100; 359 | // std::vector ret_indexes(num_results); 360 | // std::vector out_dists_sqr(num_results); 361 | // nanoflann::KNNResultSet resultSet(num_results); 362 | // resultSet.init(&ret_indexes[0], &out_dists_sqr[0] ); 363 | // size_t num_point_anchors = 364 | // spatial_index_->index->findNeighbors(resultSet, query_signal.data() + 365 | // position, nanoflann::SearchParams(10)); 366 | size_t num_point_anchors = spatial_index_->index->radiusSearch( 367 | query_signal.data() + position, search_radius, point_anchors, params); 368 | // std::cout << "radiusSearch(): radius=" << search_radius << " -> " << 369 | // num_point_anchors << " matches\n"; for (size_t ai = 0; ai < num_results; 370 | // ai++) { float previous_distance = dimension_; 371 | for (size_t ai = 0; 372 | ai < num_point_anchors && ai < (uint32_t)num_nearest_points; ai++) { 373 | // if (point_anchors[ai].second > previous_distance * 2) { 374 | // break; 375 | //} 376 | // std::cout << "cloud size =" << point_cloud_.size() << " -> " << 377 | // point_anchors[ai].first << " matches\n"; 378 | Point &point = point_cloud_[point_anchors[ai].first]; 379 | // Point &point = point_cloud_[ret_indexes[ai]]; 380 | uint32_t target_signal_index = point.position >> 33, 381 | target_signal_position = point.position >> 1; 382 | Direction target_signal_direction = 383 | (point.position & 1) == 0 ? Positive : Negative; 384 | // GetSignalIndexAndPosition(point_anchors[ai].first, num_target_signals, 385 | // target_signals, target_signal_index, target_signal_position); 386 | if (target_signal_direction == Positive) { 387 | positive_anchors_on_diff_signals[target_signal_index].emplace_back( 388 | SignalAnchor{target_signal_position, position + query_start_offset, 389 | point_anchors[ai].second}); 390 | // positive_anchors_on_diff_signals[target_signal_index].emplace_back(SignalAnchor{target_signal_position, 391 | // position, out_dists_sqr[ai]}); 392 | } else { 393 | negative_anchors_on_diff_signals[target_signal_index].emplace_back( 394 | SignalAnchor{target_signal_position, position + query_start_offset, 395 | point_anchors[ai].second}); 396 | // negative_anchors_on_diff_signals[target_signal_index].emplace_back(SignalAnchor{target_signal_position, 397 | // position, out_dists_sqr[ai]}); 398 | } 399 | // previous_distance = point_anchors[ai].second; 400 | // std::cout << "idx["<< ai << "]=" << point_anchors[ai].first << " 401 | // dist["<< ai << "]=" << point_anchors[ai].second << std::endl; 402 | } 403 | ++num_positions; 404 | if (num_positions >= 405 | (query_signal.size() - dimension_ + 1) / query_point_cloud_step_size) { 406 | break; 407 | } 408 | previous_position = position; 409 | } 410 | // Sort the anchors based on their occurrence on target signal 411 | for (size_t target_signal_index = 0; target_signal_index < num_target_signals; 412 | ++target_signal_index) { 413 | std::sort(positive_anchors_on_diff_signals[target_signal_index].begin(), 414 | positive_anchors_on_diff_signals[target_signal_index].end()); 415 | std::sort(negative_anchors_on_diff_signals[target_signal_index].begin(), 416 | negative_anchors_on_diff_signals[target_signal_index].end()); 417 | } 418 | // Chaining DP done on each individual target signal 419 | float max_chaining_score = 0; // std::numeric_limits::min(); 420 | for (size_t target_signal_index = 0; target_signal_index < num_target_signals; 421 | ++target_signal_index) { 422 | for (int direction_i = 0; direction_i < 2; ++direction_i) { 423 | std::vector chaining_scores; 424 | chaining_scores.reserve( 425 | anchors_on_diff_signals[direction_i][target_signal_index].size()); 426 | std::vector chaining_predecessors; 427 | chaining_predecessors.reserve( 428 | anchors_on_diff_signals[direction_i][target_signal_index].size()); 429 | std::vector anchor_is_used; 430 | anchor_is_used.reserve( 431 | anchors_on_diff_signals[direction_i][target_signal_index].size()); 432 | std::vector > end_anchor_index_chaining_scores; 433 | end_anchor_index_chaining_scores.reserve(10); 434 | for (size_t anchor_index = 0; 435 | anchor_index < 436 | anchors_on_diff_signals[direction_i][target_signal_index].size(); 437 | ++anchor_index) { 438 | float distance_coefficient = 439 | 1 - 0.2 * 440 | anchors_on_diff_signals[direction_i][target_signal_index] 441 | [anchor_index] 442 | .distance / 443 | search_radius; 444 | chaining_scores.emplace_back(distance_coefficient * dimension_); 445 | chaining_predecessors.emplace_back(anchor_index); 446 | anchor_is_used.push_back(false); 447 | int32_t current_anchor_target_position = 448 | anchors_on_diff_signals[direction_i][target_signal_index] 449 | [anchor_index] 450 | .target_position; 451 | int32_t current_anchor_query_position = 452 | anchors_on_diff_signals[direction_i][target_signal_index] 453 | [anchor_index] 454 | .query_position; 455 | int32_t start_anchor_index = 0; 456 | if (anchor_index > (size_t)chaining_band_length) { 457 | start_anchor_index = anchor_index - chaining_band_length; 458 | } 459 | int32_t previous_anchor_index = anchor_index - 1; 460 | int32_t num_skips = 0; 461 | for (; previous_anchor_index >= start_anchor_index; 462 | --previous_anchor_index) { 463 | // std::cerr << previous_anchor_index << " " << start_anchor_index << 464 | // " " << anchor_index << "\n"; 465 | int32_t previous_anchor_target_position = 466 | anchors_on_diff_signals[direction_i][target_signal_index] 467 | [previous_anchor_index] 468 | .target_position; 469 | int32_t previous_anchor_query_position = 470 | anchors_on_diff_signals[direction_i][target_signal_index] 471 | [previous_anchor_index] 472 | .query_position; 473 | if (previous_anchor_query_position == current_anchor_query_position) { 474 | continue; 475 | } 476 | if (previous_anchor_target_position == 477 | current_anchor_target_position) { 478 | continue; 479 | } 480 | if (previous_anchor_target_position + max_target_gap_length < 481 | current_anchor_target_position) { 482 | break; 483 | } 484 | int32_t target_position_diff = 485 | current_anchor_target_position - previous_anchor_target_position; 486 | assert(target_position_diff > 0); 487 | int32_t query_position_diff = 488 | current_anchor_query_position - previous_anchor_query_position; 489 | float current_chaining_score = 0; 490 | // std::cerr << "curr_ai: " << anchor_index << ", adjusted_d: " << 491 | // dimension_ * distance_coefficient << ", pre_ai: " << 492 | // previous_anchor_index << ", "; std::cerr << "target_diff: " << 493 | // target_position_diff << ", query_diff: " << query_position_diff << 494 | // "\n"; 495 | if (query_position_diff < 0) { 496 | // current_chaining_score = std::numeric_limits::min(); 497 | continue; 498 | } else { 499 | float matching_dimensions = 500 | std::min(std::min(target_position_diff, query_position_diff), 501 | dimension_) * 502 | distance_coefficient; 503 | int gap_length = 504 | std::abs(target_position_diff - query_position_diff); 505 | float gap_scale = 506 | target_position_diff > 0 507 | ? (float)query_position_diff / target_position_diff 508 | : 1; 509 | // float gap_cost = 0; 510 | // if (gap_length != 0) { 511 | if (gap_length < max_gap_length && gap_scale < 5 && 512 | gap_scale > 0.75) { 513 | current_chaining_score = chaining_scores[previous_anchor_index] + 514 | matching_dimensions; // - gap_cost; 515 | } else { 516 | // gap_cost = std::numeric_limits::max(); 517 | // current_chaining_score = 518 | // std::numeric_limits::min();//chaining_scores[previous_anchor_index] 519 | // + matching_dimensions - gap_cost; 520 | } 521 | //} 522 | // std::cerr << ", matching_d: " << matching_dimensions; 523 | // std::cerr << ", gap_len: " << gap_length; 524 | // std::cerr << ", gap_cost: " << gap_cost; 525 | // std::cerr << ", current chaining score: " << 526 | // current_chaining_score << "\n"; 527 | } 528 | if (current_chaining_score > chaining_scores[anchor_index]) { 529 | chaining_scores[anchor_index] = current_chaining_score; 530 | chaining_predecessors[anchor_index] = previous_anchor_index; 531 | --num_skips; 532 | // std::cerr << "update_curr_max: " << current_chaining_score << 533 | // "\n"; 534 | } else { 535 | ++num_skips; 536 | if (num_skips > max_num_skips) { 537 | break; 538 | } 539 | } 540 | } 541 | // Update chain with max score 542 | if (chaining_scores[anchor_index] > max_chaining_score) { 543 | max_chaining_score = chaining_scores[anchor_index]; 544 | } 545 | if (chaining_scores.back() >= min_chaining_score && 546 | chaining_scores.back() > max_chaining_score / 2) { 547 | end_anchor_index_chaining_scores.emplace_back(chaining_scores.back(), 548 | anchor_index); 549 | } 550 | } 551 | // Sort a vector of 552 | std::sort(end_anchor_index_chaining_scores.begin(), 553 | end_anchor_index_chaining_scores.end(), compare); 554 | // Traceback all chains from higest score to lowest 555 | for (size_t anchor_index = 0; 556 | anchor_index < end_anchor_index_chaining_scores.size() && 557 | anchor_index < (size_t)num_best_chains; 558 | ++anchor_index) { 559 | TracebackChains( 560 | min_num_anchors, direction_i == 0 ? Positive : Negative, 561 | end_anchor_index_chaining_scores[anchor_index].second, 562 | target_signal_index, chaining_scores, chaining_predecessors, 563 | anchors_on_diff_signals[direction_i], anchor_is_used, chains); 564 | if (chaining_scores[end_anchor_index_chaining_scores[anchor_index] 565 | .second] < max_chaining_score / 2) { 566 | break; 567 | } 568 | } 569 | } 570 | } 571 | if (chains.size() > 0) { 572 | // Generate primary chains 573 | GeneratePrimaryChains(chains); 574 | // Compute MAPQ 575 | ComputeMAPQ(chains); 576 | } 577 | } 578 | } // namespace sigmap 579 | -------------------------------------------------------------------------------- /src/spatial_index.h: -------------------------------------------------------------------------------- 1 | #ifndef SPATIALINDEX_H_ 2 | #define SPATIALINDEX_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include "nanoflann.hpp" 8 | #include "sequence_batch.h" 9 | #include "sigmap_adaptor.h" 10 | #include "signal_batch.h" 11 | 12 | namespace sigmap { 13 | enum Direction { 14 | Negative = 0, 15 | Positive = 1, 16 | }; 17 | 18 | struct SignalAnchor { 19 | uint32_t target_position; 20 | uint32_t query_position; 21 | float distance; 22 | bool operator<(const SignalAnchor &a) const { 23 | return std::tie(target_position, query_position, distance) < 24 | std::tie(a.target_position, a.query_position, a.distance); 25 | } 26 | }; 27 | 28 | struct SignalAnchorChain { 29 | float score; 30 | uint32_t reference_sequence_index; 31 | uint32_t start_position; 32 | uint32_t end_position; 33 | uint32_t num_anchors; 34 | uint8_t mapq; 35 | Direction direction; 36 | // bool is_primary_chain; 37 | std::vector anchors; 38 | bool operator>(const SignalAnchorChain &b) const { 39 | return std::tie(score, num_anchors, direction, reference_sequence_index, 40 | start_position, end_position) > 41 | std::tie(b.score, b.num_anchors, b.direction, 42 | b.reference_sequence_index, b.start_position, 43 | b.end_position); 44 | } 45 | }; 46 | 47 | class SpatialIndex { 48 | public: 49 | SpatialIndex(int min_num_seeds_required_for_mapping, 50 | const std::vector &max_seed_frequencies, 51 | const std::string &index_file_path_prefix) 52 | : min_num_seeds_required_for_mapping_(min_num_seeds_required_for_mapping), 53 | max_seed_frequencies_(max_seed_frequencies), 54 | index_file_path_prefix_(index_file_path_prefix) { // for read mapping 55 | spatial_index_ = nullptr; 56 | } 57 | SpatialIndex(int dimension, int max_leaf, int num_threads, 58 | const std::string &index_file_path_prefix) 59 | : dimension_(dimension), 60 | max_leaf_(max_leaf), 61 | num_threads_(num_threads), 62 | index_file_path_prefix_( 63 | index_file_path_prefix) { // for index construction 64 | spatial_index_ = nullptr; 65 | } 66 | ~SpatialIndex() { 67 | if (spatial_index_ != nullptr) { 68 | delete spatial_index_; 69 | } 70 | } 71 | void GeneratePointCloudOnOneDirection( 72 | Direction direction, uint32_t signal_index, 73 | const std::vector > &is_masked, 74 | const float *signal_values, size_t signal_length, int step_size, 75 | std::vector &point_cloud); 76 | // void GetSignalIndexAndPosition(size_t point_index, size_t num_signals, 77 | // const std::vector > &signals, size_t &signal_index, 78 | // size_t &signal_position); 79 | void Construct(size_t num_signals, 80 | const std::vector > &positive_is_masked, 81 | const std::vector > &negative_is_masked, 82 | const std::vector > &positive_signals, 83 | const std::vector > &negative_signals); 84 | void Save(); 85 | void Load(); 86 | 87 | void GenerateChains(const std::vector &query_signal, 88 | const std::vector &query_signal_stdvs, 89 | uint32_t query_start_offset, 90 | int query_point_cloud_step_size, float search_radius, 91 | size_t num_target_signals, 92 | std::vector &chains); 93 | void TracebackChains( 94 | int min_num_anchors, Direction direction, size_t chain_end_anchor_index, 95 | uint32_t chain_target_signal_index, 96 | const std::vector &chaining_scores, 97 | const std::vector &chaining_predecessors, 98 | const std::vector > &anchors_on_diff_signals, 99 | std::vector &anchor_is_used, 100 | std::vector &chains); 101 | void GeneratePrimaryChains(std::vector &chains); 102 | void ComputeMAPQ(std::vector &chains); 103 | 104 | protected: 105 | int dimension_; 106 | int max_leaf_ = 10; 107 | // int window_size_; 108 | int min_num_seeds_required_for_mapping_; 109 | std::vector max_seed_frequencies_; 110 | int num_threads_; 111 | std::string index_file_path_prefix_; // For now, I have to use two files *.pt 112 | // for dim, max leaf, points and *.si 113 | // for spatial index. 114 | SigmapAdaptor *spatial_index_; 115 | std::vector point_cloud_; // TODO(Haowen): remove this duplicate later 116 | }; 117 | } // namespace sigmap 118 | 119 | #endif // SPATIALINDEX_H_ 120 | -------------------------------------------------------------------------------- /src/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef UTILS_H_ 2 | #define UTILS_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #include "cwt.h" 18 | 19 | //#define DEBUG 20 | #define LEGACY_FAST5_RAW_ROOT "/Raw/Reads/" 21 | 22 | namespace sigmap { 23 | struct FAST5File { 24 | hid_t hdf5_file; 25 | bool is_multi_fast5; 26 | }; 27 | 28 | inline static bool IsDirectory(const std::string &dir_path) { 29 | auto dir = opendir(dir_path.c_str()); 30 | if (not dir) { 31 | return false; 32 | } 33 | closedir(dir); 34 | return true; 35 | } 36 | 37 | inline static std::vector ListDirectory( 38 | const std::string &dir_path) { 39 | std::vector res; 40 | DIR *dir; 41 | struct dirent *ent; 42 | dir = opendir(dir_path.c_str()); 43 | if (not dir) { 44 | return res; 45 | } 46 | while ((ent = readdir(dir)) != nullptr) { 47 | res.push_back(ent->d_name); 48 | } 49 | closedir(dir); 50 | return res; 51 | } 52 | 53 | inline static double GetRealTime() { 54 | struct timeval tp; 55 | struct timezone tzp; 56 | gettimeofday(&tp, &tzp); 57 | return tp.tv_sec + tp.tv_usec * 1e-6; 58 | } 59 | 60 | inline static double GetCPUTime() { 61 | struct rusage r; 62 | getrusage(RUSAGE_SELF, &r); 63 | return r.ru_utime.tv_sec + r.ru_stime.tv_sec + 64 | 1e-6 * (r.ru_utime.tv_usec + r.ru_stime.tv_usec); 65 | } 66 | 67 | inline static void ExitWithMessage(const std::string &message) { 68 | std::cerr << message << std::endl; 69 | exit(-1); 70 | } 71 | 72 | // For sequence manipulation 73 | static constexpr uint8_t char_to_uint8_table_[256] = { 74 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 75 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 76 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 77 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 78 | 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 79 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 80 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 81 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 82 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 83 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 84 | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; 85 | static constexpr char uint8_to_char_table_[8] = {'A', 'C', 'G', 'T', 86 | 'N', 'N', 'N', 'N'}; 87 | 88 | inline static uint8_t CharToUint8(const char c) { 89 | return char_to_uint8_table_[(uint8_t)c]; 90 | } 91 | 92 | inline static char Uint8ToChar(const uint8_t i) { 93 | return uint8_to_char_table_[i]; 94 | } 95 | 96 | inline static uint64_t GenerateSeedFromSequence(const char *sequence, 97 | size_t sequence_length, 98 | uint32_t start_position, 99 | uint32_t seed_length) { 100 | uint64_t mask = (((uint64_t)1) << (2 * seed_length)) - 1; 101 | uint64_t seed = 0; 102 | for (uint32_t i = 0; i < seed_length; ++i) { 103 | if (start_position + i < sequence_length) { 104 | uint8_t current_base = CharToUint8(sequence[i + start_position]); 105 | if (current_base < 4) { // not an ambiguous base 106 | seed = ((seed << 2) | current_base) & mask; // forward k-mer 107 | } else { 108 | seed = (seed << 2) & mask; // N->A 109 | } 110 | } else { 111 | seed = (seed << 2) & mask; // Pad A 112 | } 113 | } 114 | return seed; 115 | } 116 | 117 | // For FAST5 manipulation 118 | inline static FAST5File OpenFAST5(const std::string &fast5_file_path) { 119 | FAST5File fast5_file; 120 | fast5_file.hdf5_file = 121 | H5Fopen(fast5_file_path.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); 122 | if (fast5_file.hdf5_file < 0) { 123 | fprintf(stderr, "could not open fast5 file: %s\n", fast5_file_path.c_str()); 124 | } 125 | // Check for attribute that indicates whether it is single or multi-fast5 126 | // see: https://community.nanoporetech.com/posts/multi-fast5-format 127 | const std::string indicator_p1 = "/UniqueGlobalKey/"; 128 | const std::string indicator_p2 = indicator_p1 + "tracking_id/"; 129 | bool has_indicator = 130 | H5Lexists(fast5_file.hdf5_file, indicator_p1.c_str(), H5P_DEFAULT) && 131 | H5Lexists(fast5_file.hdf5_file, indicator_p2.c_str(), H5P_DEFAULT); 132 | fast5_file.is_multi_fast5 = !has_indicator; 133 | return fast5_file; 134 | } 135 | 136 | inline static void CloseFAST5(FAST5File &fast5_file) { 137 | H5Fclose(fast5_file.hdf5_file); 138 | } 139 | 140 | inline static float GetFloatAttributeInGroup(hid_t group_id, 141 | const char *attribute_name) { 142 | // The group_id should be checked somewhere else! 143 | float attribute_value = NAN; 144 | hid_t attribute_id = H5Aopen(group_id, attribute_name, H5P_DEFAULT); 145 | if (attribute_id < 0) { 146 | fprintf(stderr, "Failed to open attribute '%s' for reading.", 147 | attribute_name); 148 | return attribute_value; 149 | } 150 | herr_t err = H5Aread(attribute_id, H5T_NATIVE_FLOAT, &attribute_value); 151 | if (err < 0) { 152 | fprintf(stderr, "error reading attribute %s\n", attribute_name); 153 | exit(EXIT_FAILURE); 154 | } 155 | H5Aclose(attribute_id); 156 | return attribute_value; 157 | } 158 | 159 | inline static void GetStringAttributeInGroup(hid_t group_id, 160 | const char *attribute_name, 161 | char **string_attribute) { 162 | // The group_id should be checked somewhere else! 163 | hid_t attribute_id = H5Aopen(group_id, attribute_name, H5P_DEFAULT); 164 | hid_t attribute_type_id; 165 | hid_t native_type_id; 166 | htri_t is_variable_string; 167 | if (attribute_id < 0) { 168 | fprintf(stderr, "Failed to open attribute '%s' for reading.", 169 | attribute_name); 170 | *string_attribute = NULL; 171 | goto close_attr; 172 | } 173 | // Get data type and check it is a fixed-length string 174 | attribute_type_id = H5Aget_type(attribute_id); 175 | if (attribute_type_id < 0) { 176 | fprintf(stderr, "failed to get attribute type %s\n", attribute_name); 177 | *string_attribute = NULL; 178 | goto close_type; 179 | } 180 | if (H5Tget_class(attribute_type_id) != H5T_STRING) { 181 | fprintf(stderr, "attribute %s is not a string\n", attribute_name); 182 | *string_attribute = NULL; 183 | goto close_type; 184 | } 185 | native_type_id = H5Tget_native_type(attribute_type_id, H5T_DIR_ASCEND); 186 | if (native_type_id < 0) { 187 | fprintf(stderr, "failed to get native type for %s\n", attribute_name); 188 | *string_attribute = NULL; 189 | goto close_native_type; 190 | } 191 | is_variable_string = H5Tis_variable_str(attribute_type_id); 192 | if (is_variable_string > 0) { 193 | // variable length string 194 | // char* buffer; 195 | // herr_t err = H5Aread(attribute_id, native_type_id, &string_attribute); 196 | herr_t err = H5Aread(attribute_id, native_type_id, string_attribute); 197 | if (err < 0) { 198 | fprintf(stderr, "error reading attribute %s\n", attribute_name); 199 | exit(EXIT_FAILURE); 200 | } 201 | // out = buffer; 202 | // free(buffer); 203 | // buffer = NULL; 204 | } else if (is_variable_string == 0) { 205 | // fixed length string 206 | // Get the storage size and allocate 207 | size_t storage_size = H5Aget_storage_size(attribute_id); 208 | ; 209 | // char* buffer; 210 | // buffer = (char*)calloc(storage_size + 1, sizeof(char)); 211 | *string_attribute = (char *)calloc(storage_size + 1, sizeof(char)); 212 | // finally read the attribute 213 | herr_t err = H5Aread(attribute_id, attribute_type_id, *string_attribute); 214 | if (err < 0) { 215 | fprintf(stderr, "error reading attribute %s\n", attribute_name); 216 | exit(EXIT_FAILURE); 217 | } 218 | // clean up 219 | // free(buffer); 220 | } else { 221 | fprintf(stderr, 222 | "error when determing whether it is a variable string for " 223 | "attribute %s\n", 224 | attribute_name); 225 | exit(EXIT_FAILURE); 226 | } 227 | // H5Aread(attribute_id, H5T_NATIVE_FLOAT, &attribute_value); 228 | // H5Aclose(attribute_id); 229 | close_native_type: 230 | H5Tclose(native_type_id); 231 | close_type: 232 | H5Tclose(attribute_type_id); 233 | close_attr: 234 | H5Aclose(attribute_id); 235 | // close_group: 236 | // H5Gclose(group); 237 | } 238 | 239 | // For signal processing 240 | static inline void GetSignalMinAndMax(const float *signal_values, 241 | size_t signal_length, float &min, 242 | float &max) { 243 | min = signal_values[0]; 244 | max = signal_values[0]; 245 | for (size_t position = 0; position < signal_length; ++position) { 246 | if (signal_values[position] < min) { 247 | min = signal_values[position]; 248 | } 249 | if (signal_values[position] > max) { 250 | max = signal_values[position]; 251 | } 252 | } 253 | } 254 | 255 | static inline size_t GetSignalsTotalLength( 256 | const std::vector > &signals) { 257 | size_t length = 0; 258 | for (size_t i = 0; i < signals.size(); ++i) { 259 | length += signals[i].size(); 260 | } 261 | return length; 262 | } 263 | 264 | static inline void SaveVectorToFile(const float *signal_values, 265 | size_t signal_length, 266 | const std::string &file_path) { 267 | FILE *output_file = fopen(file_path.c_str(), "w"); 268 | assert(output_file != NULL); 269 | for (size_t signal_position = 0; signal_position < signal_length - 1; 270 | ++signal_position) { 271 | fprintf(output_file, "%f\t", signal_values[signal_position]); 272 | } 273 | fprintf(output_file, "%f\n", signal_values[signal_length - 1]); 274 | fclose(output_file); 275 | } 276 | 277 | static inline void SaveVectorToFile(const size_t *positions, 278 | size_t signal_length, 279 | const std::string &file_path) { 280 | FILE *output_file = fopen(file_path.c_str(), "w"); 281 | assert(output_file != NULL); 282 | for (size_t signal_position = 0; signal_position < signal_length - 1; 283 | ++signal_position) { 284 | fprintf(output_file, "%lu\t", positions[signal_position]); 285 | } 286 | fprintf(output_file, "%lu\n", positions[signal_length - 1]); 287 | fclose(output_file); 288 | } 289 | } // namespace sigmap 290 | 291 | #endif // UTILS_H_ 292 | --------------------------------------------------------------------------------