├── .idea
├── .gitignore
├── inspectionProfiles
│ └── profiles_settings.xml
├── libraries
│ └── R_User_Library.xml
├── misc.xml
├── modules.xml
├── vcs.xml
└── victor.iml
├── LICENSE
├── README.md
├── docker
├── Dockerfile
└── environment.yaml
├── evaluation
├── assembly_evaluation.py
├── average_stats.py
├── contig_abundance_evaluation.py
├── plot_prec_recall.py
└── plot_prec_recall_av.py
├── example
├── reads.fa
└── ref.fa
├── reproduce.sh
└── src
├── bam2clip_fa.py
├── clustering.py
├── compute_ANI.py
├── est_abundance.sh
├── filter_ovlps.py
├── genome_divergence.py
├── reformat_fa.py
├── rm_misassembly.clip.py
├── rm_misassembly.py
├── rm_redundant_genomes.py
├── sort_reads.py
├── strainline.only_iter.sh
└── strainline.sh
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /workspace.xml
3 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/libraries/R_User_Library.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/victor.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/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 |
635 | Copyright (C)
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 | Copyright (C) <2021>
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Strainline
2 | ## Description
3 |
4 | Haplotype-resolved de novo assembly of highly diverse virus genomes is critical in prevention, control and treatment of viral diseases. Current methods either can handle only relatively accurate short read data, or collapse haplotype-specific variations into consensus sequence. Here, we present Strainline, a novel approach to assemble viral haplotypes from noisy long reads without a reference genome. As a crucial consequence, Strainline is the first approach to provide strain-resolved, full-length de novo assemblies of viral quasispecies from noisy third-generation sequencing data. Benchmarking experiments on both simulated and real datasets of varying complexity and diversity confirm this novelty, by demonstrating the superiority of Strainline in terms of relevant criteria in comparison with the state of the art.
5 |
6 | ## Installation and dependencies
7 |
8 | Strainline relies on the following dependencies:
9 | - [minimap2](https://github.com/lh3/minimap2)
10 | - [daccord](https://github.com/gt1/daccord)
11 | - [samtools](http://www.htslib.org/)
12 | - [spoa](https://github.com/rvaser/spoa)
13 | - `jgi_summarize_bam_contig_depths` program from [metabat2](https://bitbucket.org/berkeleylab/metabat/src/master/)
14 | - Python v3.6+
15 |
16 |
17 | To run Strainline, firstly, it is recommended to install the dependencies through [Conda](https://docs.conda.io/en/latest/).
18 | Also, [DAZZ_DB](https://github.com/thegenemyers/DAZZ_DB) and [DALIGNER](https://github.com/thegenemyers/DALIGNER)
19 | are required before running `daccord`.
20 | ```
21 | conda create -n strainline
22 | conda activate strainline
23 | conda install -c bioconda minimap2 spoa samtools dazz_db daligner metabat2
24 | ```
25 | Then, one could just download executable program and link `daccord` to the `/path/to/envs/strainline/bin/`. Change the `/path/to/` as your own path to conda. Make sure that `daccord -h` can work successfully.
26 | ```
27 | wget https://github.com/gt1/daccord/releases/download/0.0.10-release-20170526170720/daccord-0.0.10-release-20170526170720-x86_64-etch-linux-gnu.tar.gz
28 | tar -zvxf daccord-0.0.10-release-20170526170720-x86_64-etch-linux-gnu.tar.gz
29 | ln -fs $PWD/daccord-0.0.10-release-20170526170720-x86_64-etch-linux-gnu/bin/daccord /path/to/envs/strainline/bin/daccord
30 | ```
31 |
32 | You can also install with docker directly, please see the end.
33 |
34 | ## Running and options
35 | The input read file is required and the format should be FASTA. Other parameters are optional.
36 | Please run `strainline.sh -h` to get details of optional parameters setting.
37 | Before running Strainline, please read through the following basic parameter settings,
38 | which may be helpful to achieve better assemblies.
39 | ```
40 | Usage: strainline.sh [options] -i reads.fasta -o out -p sequencingPlatform
41 |
42 | Input:
43 | reads.fasta: fasta file of input long reads.
44 | out: directory where to output the results.
45 | sequencingPlatform: long read sequencing platform: PacBio (-p pb) or Oxford Nanopore (-p ont)
46 |
47 | Options:
48 | --minTrimmedLen INT: Minimum trimmed read length. (default: 1000)
49 | --topk INT, -k INT: Choose top k seed reads. (default: 50)
50 | --minOvlpLen INT: Minimum read overlap length. (default: 1000)
51 | --minIdentity FLOAT: Minimum identity of overlaps. (default: 0.99)
52 | --minSeedLen INT: Minimum seed read length. (default: 3000)
53 | --maxOH INT: Maximum overhang length allowed for overlaps. (default: 30)
54 | --iter INT: Number of iterations for contig extension. (default: 2)
55 | --maxGD FLOAT: Maximum global divergence allowed for merging haplotypes. (default: 0.01)
56 | --maxLD FLOAT: Maximum local divergence allowed for merging haplotypes. (default: 0.001)
57 | --maxCO INT: Maximum overhang length allowed for contig contains. (default: 5)
58 | --minAbun FLOAT: Minimum abundance for filtering haplotypes (default: 0.02)
59 | --rmMisassembly BOOL: Break contigs at potential misassembled positions (default: False)
60 | --correctErr BOOL: Perform error correction for input reads (default: True)
61 | --threads INT, -t INT: Number of processes to run in parallel (default: 8).
62 | --help, -h: Print this help message.
63 | ```
64 |
65 |
66 | ## Examples
67 |
68 | One can test the `strainline.sh` program using the small PacBio CLR reads file `example/reads.fa`. Please use the absolute path of `strainline.sh` when running the program.
69 | - PacBio CLR reads
70 | ```
71 | cd example
72 | /abspath/Strainline/src/strainline.sh -i reads.fa -o out -p pb -k 20 -t 32
73 | ```
74 |
75 | - ONT reads
76 | ```
77 | /abspath/Strainline/src/strainline.sh -i reads.fa -o out -p ont -t 32
78 | ```
79 |
80 | ## Installation with docker and example test
81 |
82 | ```
83 | git clone https://github.com/HaploKit/Strainline.git
84 | cd Strainline/docker
85 | docker build -t strainline .
86 |
87 | cd ../example
88 |
89 | # 1. run directly in your path with data
90 | docker run -v $PWD:$PWD -w $PWD strainline strainline.sh -i reads.fa -o out -p pb -k 20 -t 16
91 | # 2. start an interactive docker container session and run in your path with data
92 | docker run -it --rm -v $PWD:/wd -w /wd -v /var/run/docker.sock:/var/run/docker.sock strainline /bin/bash
93 | strainline.sh -i reads.fa -o out -p pb -k 20 -t 16
94 | ```
95 |
96 | ## Citation
97 | Luo, X., Kang, X. & Schönhuth, A. Strainline: full-length de novo viral haplotype reconstruction from noisy long reads. Genome Biol 23, 29 (2022). https://doi.org/10.1186/s13059-021-02587-6
98 |
--------------------------------------------------------------------------------
/docker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM continuumio/miniconda3
2 | SHELL ["/bin/bash", "-c"]
3 |
4 | RUN apt-get update && \
5 | apt-get install -y build-essential
6 |
7 | RUN mkdir /tools
8 | WORKDIR /tools
9 | COPY environment.yaml .
10 | RUN . /opt/conda/bin/activate && \
11 | conda env create -n strainline -f environment.yaml && \
12 | conda clean -a && \
13 | wget https://github.com/gt1/daccord/releases/download/0.0.10-release-20170526170720/daccord-0.0.10-release-20170526170720-x86_64-etch-linux-gnu.tar.gz && \
14 | tar -zvxf daccord-0.0.10-release-20170526170720-x86_64-etch-linux-gnu.tar.gz && \
15 | ln -fs /tools/daccord-0.0.10-release-20170526170720-x86_64-etch-linux-gnu/bin/daccord /opt/conda/envs/strainline/bin/daccord && \
16 | git clone https://github.com/HaploKit/Strainline.git && \
17 | rm daccord-0.0.10-release-20170526170720-x86_64-etch-linux-gnu.tar.gz environment.yaml
18 | ENV PATH=/opt/conda/envs/strainline/bin/:$PATH
19 | ENV PATH=/tools/Strainline/src/:$PATH
20 |
--------------------------------------------------------------------------------
/docker/environment.yaml:
--------------------------------------------------------------------------------
1 | name: strainline
2 | channels:
3 | - bioconda
4 | - conda-forge
5 | - defaults
6 | dependencies:
7 | - _libgcc_mutex=0.1=conda_forge
8 | - _openmp_mutex=4.5=2_gnu
9 | - bzip2=1.0.8=h7f98852_4
10 | - c-ares=1.20.1=hd590300_1
11 | - ca-certificates=2023.7.22=hbcca054_0
12 | - daligner=1.0.20230620=h031d066_0
13 | - dazz_db=1.0=0
14 | - htslib=1.18=h81da01d_0
15 | - k8=0.2.5=hdcf5f25_4
16 | - keyutils=1.6.1=h166bdaf_0
17 | - krb5=1.21.2=h659d440_0
18 | - ld_impl_linux-64=2.40=h41732ed_0
19 | - libcurl=8.4.0=hca28451_0
20 | - libdeflate=1.19=hd590300_0
21 | - libedit=3.1.20191231=he28a2e2_2
22 | - libev=4.33=h516909a_1
23 | - libffi=3.4.2=h7f98852_5
24 | - libgcc=7.2.0=h69d50b8_2
25 | - libgcc-ng=13.2.0=h807b86a_2
26 | - libgomp=13.2.0=h807b86a_2
27 | - libnghttp2=1.55.1=h47da74e_0
28 | - libnsl=2.0.1=hd590300_0
29 | - libsqlite=3.43.2=h2797004_0
30 | - libssh2=1.11.0=h0841786_0
31 | - libstdcxx-ng=13.2.0=h7e041cc_2
32 | - libuuid=2.38.1=h0b41bf4_0
33 | - libzlib=1.2.13=hd590300_5
34 | - metabat2=2.15=h986a166_1
35 | - minimap2=2.26=he4a0461_2
36 | - ncurses=6.4=h59595ed_2
37 | - openssl=3.1.4=hd590300_0
38 | - perl=5.32.1=4_hd590300_perl5
39 | - pip=23.3.1=pyhd8ed1ab_0
40 | - python=3.10.13=hd12c33a_0_cpython
41 | - readline=8.2=h8228510_1
42 | - samtools=1.18=h50ea8bc_1
43 | - setuptools=68.2.2=pyhd8ed1ab_0
44 | - spoa=4.1.3=hdcf5f25_0
45 | - tk=8.6.13=h2797004_0
46 | - tzdata=2023c=h71feb2d_0
47 | - wheel=0.41.3=pyhd8ed1ab_0
48 | - xz=5.2.6=h166bdaf_0
49 | - zlib=1.2.13=hd590300_5
50 | - zstd=1.5.5=hfc55251_0
51 | prefix: /home/wenhai/miniconda3/envs/strainline
52 |
--------------------------------------------------------------------------------
/evaluation/assembly_evaluation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import os
3 | import sys
4 | import subprocess
5 | import copy
6 | import multiprocessing as mp
7 | import numpy as np # array, arange, minimum, add (levenshtein)
8 | import itertools # groupby()
9 | import argparse
10 |
11 | def main():
12 | parser = argparse.ArgumentParser(prog='assembly_evaluation.py', description='Compare assembled contigs to ground truth haplotypes.')
13 | parser.add_argument('contigs', nargs='*', type=str)
14 | parser.add_argument('-gt', '--ground_truth', dest='truth', type=str, required=True)
15 | parser.add_argument('-m', '--max_edit', dest='max_edit', type=float, default=0.05)
16 | parser.add_argument('-c', '--min_HC', dest='min_HC', type=float, default=0.5)
17 | parser.add_argument('-o', '--outdir', dest='outdir', default=".", help="write output files to this directory")
18 | parser.add_argument('-f', '--freq_truth', dest='freq_truth', help="file containing true frequency per ground truth strain")
19 | args = parser.parse_args()
20 |
21 | if not args.contigs:
22 | print("No contig files given. Aborting evaluation.")
23 | sys.exit(1)
24 |
25 | main_outfile = args.outdir.rstrip('/') + '/extra_stats.tsv'
26 | dist_outfile = args.outdir.rstrip('/') + '/min_dist.tsv'
27 | freq_outfile = args.outdir.rstrip('/') + '/freq_true_est.tsv'
28 | assignment_outfile = args.outdir.rstrip('/') + '/contig_assignments.tsv'
29 |
30 | if os.path.exists(freq_outfile):
31 | os.remove(freq_outfile)
32 | if os.path.exists(assignment_outfile):
33 | os.remove(assignment_outfile)
34 |
35 | truth_file = args.truth # "/home/jasmijn/HLA_real/ground_truth/NA12878.HLA-A.fasta"
36 | contig_files = args.contigs # "/home/jasmijn/HLA_real/GIAB_NA12878/savage-lc/contigs_diploid.fasta"
37 | bwa_mode = True
38 |
39 | # read in reference sequences
40 | ground_truth, empty = read_fasta(truth_file)
41 |
42 | # process assemblies
43 | header_line = "Assembly"
44 | sens_line = "Sensitivity"
45 | ppv_line = "PPV"
46 | freq_line = "Rel freq error (%)"
47 | freq_line2 = "Abs freq error (%)"
48 | min_dist_data = {}
49 | for file in contig_files:
50 | header_line += "\t{}".format(file)
51 | stats = evaluate_assembly(file, ground_truth, bwa_mode, args.max_edit,
52 | args.freq_truth, truth_file, args.min_HC, freq_outfile,
53 | args.outdir, assignment_outfile)
54 | sens_line += "\t{:.2f}".format(stats[0])
55 | ppv_line += "\t{:.2f}".format(stats[1])
56 | freq = stats[2]
57 | freq_abs = stats[3]
58 | if freq >= 0:
59 | freq_line += "\t{:.2f}".format(freq)
60 | freq_line2 += "\t{:.2f}".format(freq_abs)
61 | else:
62 | freq_line += "\t-"
63 | freq_line2 += "\t-"
64 | min_dist_data[file] = stats[4]
65 |
66 | with open(main_outfile, 'w') as f:
67 | f.write(header_line + '\n')
68 | f.write(sens_line + '\n')
69 | f.write(ppv_line + '\n')
70 | f.write(freq_line + '\n')
71 | f.write(freq_line2 + '\n')
72 |
73 | with open(dist_outfile, 'w') as f:
74 | f.write(header_line + '\n')
75 | for strain in min_dist_data[contig_files[0]].keys():
76 | line = strain
77 | for file in contig_files:
78 | dist = min_dist_data[file][strain]
79 | if dist == 100:
80 | line += "\t-"
81 | else:
82 | line += "\t{:.1f}".format(min_dist_data[file][strain])
83 | f.write(line + '\n')
84 |
85 | return
86 |
87 | ################################################################################
88 |
89 | def evaluate_assembly(contig_file, ground_truth, bwa_mode, max_edit, freq_truth,
90 | truth_file, min_HC, freq_out, outdir, assignment_out):
91 | contigs, ab_est = read_fasta(contig_file, True)
92 | print("------------------------------------------")
93 | print("Number of contigs: {}".format(len(contigs)))
94 |
95 | contigs2aln= {}
96 |
97 | if bwa_mode:
98 | # run bwa mem -a to align contigs to ground truth
99 | print("\nAligning contigs against ground truth...")
100 | sam_file = "{}/contigs_to_truth.sam".format(outdir.rstrip('/'))
101 | subprocess.check_call("bwa index {} 2>/dev/null".format(truth_file),
102 | shell=True)
103 | subprocess.check_call(
104 | "bwa mem -a -L1000 -t 12 {0} {1} > {2} 2>/dev/null".format(
105 | truth_file, contig_file, sam_file),
106 | shell=True)
107 | print()
108 | # score all alignments per contig and select the good alignment(s)
109 | [alignments, unmapped_ids] = read_sam(sam_file)
110 | print("#alignments: {}".format(len(alignments)))
111 | print("#unmapped: {}".format(len(unmapped_ids)))
112 | for contig in contigs:
113 | contigs2aln[contig] = []
114 | # score and store alignments
115 | for aln in alignments:
116 | #print aln
117 | [contig_id, ref_id] = aln[0:2]
118 | contig_seq = contigs[contig_id]
119 | truth_seq = ground_truth[ref_id]
120 | [score, aln_range] = score_alignment(aln, contig_seq, truth_seq)
121 | if score[0] <= max_edit:
122 | contigs2aln[contig_id].append([score, aln, aln_range])
123 | os.remove(sam_file)
124 | else:
125 | print("\nPerforming pairwise alignments...")
126 | for contig_id, contig_seq in contigs.items():
127 | aln_list = []
128 | for truth_id, truth_seq in ground_truth.items():
129 | for ori in ["+", "-"]:
130 | if ori == "+":
131 | dt, bt = align2(truth_seq, contig_seq)
132 | else:
133 | dt, bt = align2(truth_seq, revcomp(contig_seq))
134 | cigar, pos = backtrace_to_cigar(bt)
135 | aln = [contig_id, truth_id, pos, ori, cigar]
136 | [score, aln_range] = score_alignment(aln, contig_seq, truth_seq)
137 | if score[0] <= max_edit:
138 | aln_list.append([score, aln, aln_range])
139 | contigs2aln[contig_id] = aln_list
140 |
141 | # select optimal alignment(s)
142 | contig_assignments = {}
143 | for contig, aln_list in contigs2aln.items():
144 | min_score = 1
145 | opt_aln = []
146 | #print contig
147 | #print aln_list
148 | for i in range(len(aln_list)):
149 | info1 = aln_list[i]
150 | if info1 in opt_aln:
151 | # alignment already paired with another alignment
152 | continue
153 | scores1 = info1[0]
154 | combined = False
155 | for j in range(i+1, len(aln_list)):
156 | info2 = aln_list[j]
157 | # check if these alignments can be combined
158 | if info2[1][1] != info1[1][1]: # not to same ref sequence
159 | continue
160 | elif not (info2[2][1] <= info1[2][0]
161 | or info2[2][0] >= info1[2][1]):
162 | # overlapping alignments
163 | if info2[2][1] >= info1[2][0] and info1[2][1] >= info2[2][0]:
164 | ov_len = info1[2][1]-info2[2][0]
165 | elif info1[2][1] >= info2[2][0] and info2[2][1] >= info1[2][0]:
166 | ov_len = info2[2][1]-info1[2][0]
167 | else:
168 | print("no overlap???")
169 | sys.exit(1)
170 | print("\noverlap of length {} for contig {} on ref {}\n".format(ov_len, contig, info1[1][1]))
171 | ref_len = info1[2][2]
172 | if ov_len > 0.1*ref_len:
173 | print("overlap too long, skipping")
174 | continue
175 | # compute combined score (assigning contig to 2 allele sequences)
176 | combined = True
177 | combined_score = (info1[0][0]*info1[2][2]
178 | + info2[0][0]*info2[2][2]) / (info1[2][2] + info2[2][2])
179 | # now check if this alignment is optimal
180 | if combined_score == min_score:
181 | ref_id = info1[1][1]
182 | new_aln = True
183 | for aln in opt_aln:
184 | if aln[1][1] != ref_id:
185 | continue
186 | else:
187 | new_aln = False
188 | break
189 | if new_aln:
190 | opt_aln.append(info1)
191 | opt_aln.append(info2)
192 | elif combined_score < min_score:
193 | opt_aln = [info1, info2]
194 | min_score = combined_score
195 | # if there is no pairing, check single alignemnt
196 | if not combined:
197 | scores = scores1
198 | if scores[0] == min_score:
199 | ref_id = info1[1][1]
200 | new_aln = True
201 | for aln in opt_aln:
202 | if aln[1][1] != ref_id:
203 | continue
204 | else:
205 | new_aln = False
206 | break
207 | if new_aln:
208 | opt_aln.append(info1)
209 | elif scores[0] < min_score:
210 | opt_aln = [info1]
211 | min_score = scores[0]
212 | contig_assignments[contig] = opt_aln
213 | count = len(opt_aln)
214 | if count > 1:
215 | print("NOTE: contig {} has {} assignments!".format(contig, count))
216 |
217 | # build a dict mapping ground truth fragments to contig alignments
218 | truth2aln = {}
219 | for ref_id in ground_truth:
220 | truth2aln[ref_id] = []
221 | for contig, aln_list in contig_assignments.items():
222 | for info in aln_list:
223 | scores = info[0]
224 | aln = info[1]
225 | ref_id = aln[1]
226 | aln_range = info[2]
227 | truth2aln[ref_id].append([aln, scores, aln_range])
228 |
229 | # for ref, aln_list in truth2aln.items():
230 | # print ref
231 | # for aln in aln_list:
232 | # print aln
233 |
234 | # evaluate assembly
235 | contig_lengths = [len(seq) for contig,seq in contigs.items()]
236 | total_assembly_len = sum(contig_lengths)
237 | N50_all_contigs = compute_NX(contig_lengths, 50)
238 | outfile_line, sensitivity, ppv, min_dist_map = get_assembly_stats(truth2aln,
239 | total_assembly_len, N50_all_contigs, ground_truth, len(contigs2aln),
240 | assignment_out, contig_file)
241 | if freq_truth and len(ab_est) > 0:
242 | av_rel_err, av_abs_err, median = check_frequencies(
243 | freq_truth, ab_est, truth2aln, contigs, ground_truth, min_HC,
244 | freq_out)
245 | if av_rel_err >= 0:
246 | print("average relative abundance error: {:.2f}%".format(av_rel_err))
247 | print("average absolute abundance error: {:.2f}%".format(av_abs_err))
248 | print("median abundance error: {:.1f}%\n".format(100*median))
249 | else:
250 | av_rel_err = -1
251 | av_abs_err = -1
252 |
253 | return sensitivity, ppv, av_rel_err, av_abs_err, min_dist_map
254 |
255 |
256 | def check_frequencies(freq_truth, ab_est, truth2aln, contigs, ground_truth,
257 | min_HC, outfile):
258 | # read true frequencies
259 | true_frequencies = {}
260 | with open(freq_truth, 'r') as f:
261 | for line in f:
262 | [seq_id, freq] = line.strip('\n').split()
263 | true_frequencies[seq_id] = float(freq)
264 |
265 | total_abundance = sum(ab_est.values())
266 |
267 | # compute relative true frequencies, leaving out any missing haps
268 | total_true_freqs = 0
269 | for truth_id, freq in true_frequencies.items():
270 | aln_list = truth2aln[truth_id]
271 | truth_len = len(ground_truth[truth_id])
272 | aln_lengths = [len(contigs[aln[0][0]]) for aln in aln_list]
273 | if len(aln_list) > 0 and max(aln_lengths) > min_HC*truth_len:
274 | total_true_freqs += freq
275 | if total_true_freqs == 0:
276 | print("No contigs of sufficient length, can't evaluate frequencies.\n")
277 | return -1, -1, -1
278 |
279 | total_ab = 0
280 | for truth_id, aln_list in truth2aln.items():
281 | truth_len = len(ground_truth[truth_id])
282 | for info in aln_list:
283 | contig_id = info[0][0]
284 | contig_ab = ab_est[contig_id]
285 | if len(contigs[contig_id]) > min_HC*truth_len:
286 | total_ab += contig_ab
287 | if total_ab == 0:
288 | print("No contigs of sufficient length, can't evaluate frequencies.\n")
289 | return -1, -1, -1
290 |
291 | # check assignments and evaluate
292 | err_list = []
293 | abs_err_list = []
294 | contigs_seen = []
295 | f = open(outfile, 'a')
296 | for truth_id, aln_list in truth2aln.items():
297 | truth_len = len(ground_truth[truth_id])
298 | true_freq = true_frequencies[truth_id]
299 | if len(aln_list) == 0: # don't evaluate missing strains as wrong estimation
300 | continue
301 | total_ab_est = 0
302 | for info in aln_list:
303 | aln = info[0]
304 | contig_id = aln[0]
305 | if contig_id in contigs_seen:
306 | print("WARNING: duplicate contig assignment")
307 | continue
308 | else:
309 | contigs_seen.append(contig_id)
310 | contig_len = len(contigs[contig_id])
311 | contig_ab = ab_est[contig_id]
312 | if contig_len > min_HC*truth_len:
313 | # full length contig -> add estimated abundances
314 | total_ab_est += contig_ab
315 | else:
316 | # if not full length, evaluate frequencies manually
317 | print("WARNING: contig not full length")
318 | continue
319 | # return -1, -1
320 | freq_est = total_ab_est/total_ab*100
321 | cor_true_freq = true_freq/total_true_freqs*100
322 | if total_ab_est > 0:
323 | print("{}\t{}".format(cor_true_freq, freq_est))
324 | f.write("{}\t{}\n".format(cor_true_freq, freq_est))
325 | abs_err = abs(freq_est - cor_true_freq)
326 | rel_err = abs(freq_est - cor_true_freq)/cor_true_freq
327 | err_list.append(rel_err)
328 | abs_err_list.append(abs_err)
329 | #print truth_id, true_freq, freq_est, len(aln_list)
330 | f.close()
331 | if len(abs_err_list) == 1:
332 | print("Only 1 strain reconstructed, hence perfect frequency estimation.")
333 | return -1, -1, -1
334 | average_rel_err = sum(err_list)/len(err_list)*100
335 | average_abs_err = sum(abs_err_list)/len(abs_err_list)
336 | print("average rel error: {:.2f}%".format(average_rel_err))
337 | print("average abs error: {:.2f}%".format(average_abs_err))
338 | print("\nLatex abs/rel error: {:.2f} & {:.2f} \cr\n\n".format(average_abs_err,average_rel_err))
339 | print("min error: {:.3f}".format(min(err_list)))
340 | print("max error: {:.3f}".format(max(err_list)))
341 | median = np.median(np.array(sorted(err_list)))
342 | return average_rel_err, average_abs_err, median
343 |
344 | def read_fasta(filename, read_ab=False):
345 | # returns ID to sequence dict
346 | id2seq = {}
347 | ab_est = {}
348 | with open(filename, 'r') as f:
349 | seq_id = ""
350 | seq = ""
351 | for line in f:
352 | if line[0] == '>':
353 | if seq_id != "" and seq != "":
354 | id2seq[seq_id] = seq
355 | if read_ab:
356 | ab_est[seq_id] = ab # estimated abundance
357 | seq_id = line.lstrip('>').rstrip('\n').split()[0]
358 | if read_ab:
359 | try:
360 | ab = float(line.lstrip('>').rstrip('\n').split()[-1].lstrip('frequency='))
361 | except ValueError:
362 | print("WARNING: could not read abundance estimates from fasta")
363 | read_ab = False
364 | seq = ""
365 | else:
366 | seq += line.rstrip('\n')
367 | # add final entry
368 | if seq_id != "" and seq != "":
369 | id2seq[seq_id] = seq
370 | if read_ab:
371 | ab_est[seq_id] = ab # estimated abundance
372 | return id2seq, ab_est
373 |
374 | def read_sam(filename):
375 | # returns a list of all alignments, where each alignment is presented in the
376 | # following format: [seq_id, ref_id, pos, ori, cigar]
377 | aln_list = []
378 | unmapped_ids = []
379 | with open(filename, 'r') as f:
380 | for line in f:
381 | if line[0] == "@":
382 | continue
383 | line = line.rstrip('\n').split()
384 | [seq_id, flag, ref_id, pos] = line[0:4]
385 | cigar = line[5]
386 | bits_flag = power_find(int(flag))
387 | if 4 in bits_flag: # unmapped contig
388 | unmapped_ids.append(seq_id)
389 | continue
390 | elif 16 in bits_flag: # reversed contig
391 | ori = "-"
392 | else:
393 | ori = "+"
394 | aln_list.append([seq_id, ref_id, int(pos)-1, ori, cigar]) # SAM-format is 1-based; switching to 0-based here
395 | return [aln_list, unmapped_ids]
396 |
397 | def power_find(n):
398 | try:
399 | int(n)
400 | except TypeError:
401 | print("power_find TypeError")
402 | print("n = {}".format(n))
403 | sys.exit(1)
404 | result = []
405 | binary = bin(n)[:1:-1]
406 | for x in range(len(binary)):
407 | if int(binary[x]):
408 | result.append(2**x)
409 | return result
410 |
411 | def score_alignment(aln, contig, truth):
412 | [seq_id, ref_id, pos, ori, cigar] = aln
413 | if ori == "-":
414 | contig = revcomp(contig)
415 | # split cigar into numbers and characters all separately
416 | splitcigar = ["".join(x) for _, x in itertools.groupby(cigar,
417 | key=str.isdigit)]
418 | # count mismatches, insertions, deletions and N's
419 | mismatch_count = 0
420 | ins_count = 0
421 | ins_len = 0
422 | del_count = 0
423 | del_len = 0
424 | N_count = 0
425 | length = len(contig)
426 | # keep track of position and cigar index
427 | contig_pos = 0
428 | truth_pos = pos
429 | start_pos = pos
430 | i = 0
431 | while i+1 < len(splitcigar):
432 | aln_len = int(splitcigar[i])
433 | aln_type = splitcigar[i+1]
434 | if aln_type == "S" or aln_type == "H":
435 | if i == 0: # front end clipped
436 | # if pos > 0:
437 | # del_count += 1
438 | # del_len += pos
439 | clipped_truth = min(aln_len, pos)
440 | length -= aln_len - clipped_truth # correct for overhanging contig length
441 | start_pos -= clipped_truth
442 | contig_pos += aln_len
443 | elif i > 0: # back end clipped
444 | clipped_truth = min(aln_len, len(truth)-truth_pos)
445 | # clipped_truth = len(truth) - truth_pos
446 | # if clipped_truth < 0:
447 | # del_count += 1
448 | # del_len += clipped_truth
449 | length -= aln_len - clipped_truth
450 | contig_pos += aln_len
451 | # truth_pos = len(truth) - clipped_truth
452 | truth_pos += clipped_truth
453 | # compare (partially) aligned sequences
454 | contig_part = contig[contig_pos-clipped_truth : contig_pos]
455 | truth_part = truth[truth_pos-clipped_truth : truth_pos]
456 | [mismatches, Ns] = count_mismatches(contig_part, truth_part)
457 | mismatch_count += mismatches
458 | N_count += Ns
459 | elif aln_type == "I":
460 | if i > 0 and i < len(splitcigar)-2:
461 | ins_count += 1
462 | ins_len += aln_len
463 | N_count += contig[contig_pos:contig_pos+aln_len].count('N')
464 | contig_pos += aln_len
465 | elif aln_type == "D":
466 | del_count += 1
467 | del_len += aln_len
468 | truth_pos += aln_len
469 | elif aln_type == "M":
470 | if contig_pos + aln_len > len(contig):
471 | print("contig {} too short?".format(seq_id))
472 | print(contig_pos, aln_len, len(contig))
473 | print(pos, cigar)
474 | if truth_pos + aln_len > len(truth):
475 | print("truth too short?")
476 | print(truth_pos, aln_len, len(truth))
477 | print(pos, cigar)
478 | contig_part = contig[contig_pos : contig_pos + aln_len]
479 | truth_part = truth[truth_pos : truth_pos + aln_len]
480 | [mismatches, Ns] = count_mismatches(contig_part, truth_part)
481 | mismatch_count += mismatches
482 | N_count += Ns
483 | truth_pos += aln_len
484 | contig_pos += aln_len
485 | else:
486 | print("ERROR: cigar string not recognized.")
487 | sys.exit(1)
488 | i += 2
489 | # compute percent identity
490 | if length > 0:
491 | score = (mismatch_count + ins_len + del_len) / float(length)
492 | else:
493 | score = 0
494 | aln_scores = [score, mismatch_count, ins_count, ins_len, del_count, del_len,
495 | N_count]
496 | assert start_pos >= 0
497 | assert truth_pos <= len(truth)
498 | assert start_pos <= truth_pos
499 | aln_range = [start_pos, truth_pos, len(truth)]
500 | return [aln_scores, aln_range]
501 |
502 | def count_mismatches(seq1, seq2):
503 | assert len(seq1) == len(seq2)
504 | mismatches = 0
505 | Ns = 0
506 | for i in range(len(seq1)):
507 | if seq1[i] == "N": # truth has N
508 | Ns += 1
509 | elif seq2[i] == "N": # contig has N
510 | Ns += 1
511 | elif seq1[i] != seq2[i]:
512 | mismatches += 1
513 | return [mismatches, Ns]
514 |
515 | def revcomp(seq):
516 | complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}
517 | revcomp = "".join(complement.get(base, base) for base in reversed(seq))
518 | assert len(seq) == len(revcomp)
519 | return revcomp
520 |
521 | def get_assembly_stats(truth2aln, total_assembly_len, N50_all_contigs,
522 | ground_truth, ncontigs, outfile, method):
523 | # prints all assembly statistics of interest
524 | mismatch_count = 0
525 | ins_count = 0
526 | ins_len = 0
527 | del_count = 0
528 | del_len = 0
529 | N_count = 0
530 | target_cov_len = 0 # target bases covered
531 | total_target_len = 0
532 | breakpoints = 0
533 | true_positives = set()
534 | exactly_matched = 0
535 | aln_contig_lengths = []
536 | min_dist_map = {}
537 | f = open(outfile, 'a')
538 | for truth_id, aln in truth2aln.items():
539 | print('\n' + truth_id + ':',)
540 | if len(aln) == 0:
541 | truth_seq_len = len(ground_truth[truth_id])
542 | breakpoints = 0
543 | else:
544 | truth_seq_len = aln[0][2][2]
545 | breakpoints += len(aln)-1
546 | total_target_len += truth_seq_len
547 | target_cov = [0 for i in range(truth_seq_len)]
548 | local_mismatches = 0
549 | local_ins_len = 0
550 | local_del_len = 0
551 | min_dist = 1
552 | for info in aln:
553 | seq_id = info[0][0]
554 | print("{} ({});".format(seq_id, info[0][4]),)
555 | scores = info[1]
556 | mismatch_count += scores[1]
557 | local_mismatches += scores[1]
558 | ins_count += scores[2]
559 | ins_len += scores[3]
560 | local_ins_len += scores[3]
561 | del_count += scores[4]
562 | del_len += scores[5]
563 | local_del_len += scores[5]
564 | N_count += scores[6]
565 | aln_range = info[2]
566 | aln_contig_lengths.append(aln_range[1] - aln_range[0])
567 | for i in range(aln_range[0], aln_range[1]):
568 | target_cov[i] = 1
569 | dist = scores[1] + scores[3] + scores[5]
570 | if dist == 0:
571 | true_positives.add(seq_id)
572 | assignment = [
573 | method, seq_id, truth_id, aln_range[1] - aln_range[0], dist,
574 | scores[1], scores[3], scores[5]
575 | ]
576 | f.write('\t'.join([str(x) for x in assignment]) + '\n')
577 | min_dist = min(min_dist, dist/(aln_range[1] - aln_range[0]))
578 | target_cov_len += sum(target_cov)
579 | min_dist_map[truth_id] = min_dist*100
580 | if min_dist == 0:
581 | exactly_matched += 1
582 | print("\ntarget coverage: {} of {} ({:.1f}%)".format(sum(target_cov), truth_seq_len, 100*sum(target_cov)/truth_seq_len))
583 | print("# contigs: {}".format(len(aln)))
584 | print("minimal contig distance: {:.2f}%".format(min_dist*100))
585 | print("mismatches, ins_len, del_len: {} {} {}".format(local_mismatches, local_ins_len, local_del_len))
586 | f.close()
587 | print()
588 | print("-----------------------")
589 | print("- Assembly statistics -")
590 | print("-----------------------")
591 | print("Total assembly length:\t{} bp".format(total_assembly_len))
592 | if total_assembly_len == 0:
593 | outfile_line = "{0}\t{0}\t{0}\t{0}\t{0}\t{0}\t{0}".format(0)
594 | sensitivity = 0
595 | ppv = 0
596 | return outfile_line, sensitivity, ppv, min_dist_map
597 | total_aln_len = sum(aln_contig_lengths)
598 | total_unaligned_len = total_assembly_len - total_aln_len
599 | unaligned_perc = float(total_unaligned_len)/total_assembly_len*100.0
600 | print("Total unaligned length:\t{} bp ({:.1f}%)".format(total_unaligned_len, unaligned_perc))
601 | edit_distance = float(mismatch_count + ins_len + del_len)/total_aln_len*100 if total_aln_len > 0 else 0
602 | print("Overall edit distance:\t{:5.3f}%".format(edit_distance))
603 | mismatch_rate = float(mismatch_count)/total_aln_len*100 if total_aln_len > 0 else 0
604 | print("Mismatch rate:\t{:5.3f}%".format(mismatch_rate))
605 | N_rate = float(N_count)/total_aln_len*100 if total_aln_len > 0 else 0
606 | print("'N' rate:\t{:5.3f}%".format(N_rate))
607 | insertion_rate = float(ins_len)/total_aln_len*100 if total_aln_len > 0 else 0
608 | print("Total insertion count:\t{}".format(ins_count))
609 | print("Total insertion length:\t{} bp ({:5.3f}%)".format(ins_len, insertion_rate))
610 | #print "Total insertion length:\t{:5.3f}%".format(insertion_rate)
611 | deletion_rate = float(del_len)/total_aln_len*100 if total_aln_len > 0 else 0
612 | print("Total deletion count:\t{}".format(del_count))
613 | print("Total deletion length:\t{} bp ({:5.3f}%)".format(del_len, deletion_rate))
614 | #print "Total deletion length:\t{:5.3f}%".format(deletion_rate)
615 |
616 | total_target_cov = float(target_cov_len)/total_target_len*100
617 | print("Target coverage:\t{:4.1f}%".format(total_target_cov))
618 |
619 | N50_aln = compute_NX(aln_contig_lengths, 50)
620 | print("N50 aligned sequence:\t{}".format(N50_aln))
621 | print("N50 all contigs:\t{}".format(N50_all_contigs))
622 | # TODO: minimum contig size to cover at least 50% of the ground truth
623 |
624 | print("Breakpoint number:\t{}".format(breakpoints))
625 | # TODO: number of unnecessary breakpoints
626 | # TODO: number of conflict cliques larger than known ploidy
627 | print("# true positives = {}".format(len(true_positives)))
628 | sensitivity = exactly_matched/len(truth2aln)
629 | ppv = len(true_positives)/ncontigs
630 | print("Sensitivity = {:.2f}".format(sensitivity))
631 | print("PPV = {:.2f}".format(ppv))
632 | print()
633 | outfile_line = "{}\t{}\t{}\t{}\t{:.3f}\t{}\t{:.5f}".format(N50_all_contigs,
634 | total_aln_len, total_target_len, target_cov_len, total_target_cov/100,
635 | mismatch_count+ins_len+del_len, edit_distance/100)
636 | return outfile_line, sensitivity, ppv, min_dist_map
637 |
638 | def compute_NX(contig_lengths, X):
639 | assert X > 0
640 | assert X <= 100
641 | factor = X/100.0
642 | contig_lengths.sort(reverse=True)
643 | total_len = sum(contig_lengths)
644 | current_len = 0
645 | NX = 0
646 | for l in contig_lengths:
647 | current_len += l
648 | if current_len >= factor*total_len:
649 | NX = l
650 | break
651 | assert NX >= 0
652 | return NX
653 |
654 |
655 | if __name__ == '__main__':
656 | sys.exit(main())
657 |
--------------------------------------------------------------------------------
/evaluation/average_stats.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import csv
3 | import sys, os
4 | import argparse
5 |
6 | # df = pd.read_csv("test_quast_report.tsv", sep='\t')
7 | # n_files = len(df.columns)-1
8 | # print(n_files)
9 |
10 |
11 | int_stats = ["# contigs", "N50", "NGA50"]
12 | f1_stats = ["Genome fraction (%)"]
13 | f2_stats = []
14 | f3_stats = ["Error rate (%)", "Sensitivity", "PPV", "Rel freq error (%)",
15 | "Abs freq error (%)"]
16 | output_stats = ["# contigs", "Genome fraction (%)", "N50", "NGA50",
17 | "Error rate (%)", "Sensitivity", "PPV", "Rel freq error (%)",
18 | "Abs freq error (%)"]
19 |
20 | ER_stats = [
21 | "# N's per 100 kbp",
22 | "# mismatches per 100 kbp",
23 | "# indels per 100 kbp"
24 | ]
25 | suppl_stats = [
26 | "# N's per 100 kbp",
27 | "# mismatches per 100 kbp",
28 | "# indels per 100 kbp",
29 | "Unaligned length"
30 | ]
31 |
32 | def main():
33 | parser = argparse.ArgumentParser(prog='average_stats.py', description='Compute average assembly statistics from multiple input files.')
34 | parser.add_argument('reports', nargs='*', type=str)
35 | parser.add_argument('--dist', action='store_true')
36 | parser.add_argument('--skip_freq', action='store_true')
37 | parser.add_argument('--suppl', action='store_true')
38 | args = parser.parse_args()
39 |
40 | if not args.reports:
41 | print("No input files given. Use --help for usage information.")
42 | sys.exit(1)
43 | quast_reports = args.reports
44 | # quast_reports = ['test_quast_report.tsv']
45 |
46 | if args.dist:
47 | stats = []
48 | with open(quast_reports[0], 'r') as f:
49 | for line in f:
50 | strain = line.rstrip('\n').split('\t')[0]
51 | stats.append(strain)
52 | stats = sorted(stats[1:])
53 | else:
54 | if args.suppl:
55 | stats = output_stats + suppl_stats
56 | else:
57 | stats = output_stats
58 | if args.skip_freq:
59 | stats.remove("Rel freq error (%)")
60 | stats.remove("Abs freq error (%)")
61 |
62 | latex_table = []
63 | print('\nfilename\t' + '\t'.join(stats))
64 | for file in quast_reports:
65 | results = compute_average_stats(file, stats+ER_stats)
66 | result_line = file
67 | latex_line = file
68 | for stat in stats:
69 | if stat == "Error rate (%)":
70 | result = sum([results[stat] for stat in ER_stats])/1000
71 | else:
72 | try:
73 | result = results[stat]
74 | except KeyError:
75 | result = '-'
76 | # format output with desired floating point precision
77 | if result == '-':
78 | result_line += '\t{}'.format(result)
79 | latex_line += ' & {}'.format(result)
80 | elif stat in int_stats + suppl_stats:
81 | result_line += '\t{}'.format(int(round(result)))
82 | latex_line += ' & {}'.format(int(round(result)))
83 | elif stat in f1_stats:
84 | result_line += '\t{:.1f}'.format(result)
85 | latex_line += ' & {:.1f}'.format(result)
86 | elif stat in f2_stats:
87 | result_line += '\t{:.2f}'.format(result)
88 | latex_line += ' & {:.2f}'.format(result)
89 | elif stat in f3_stats:
90 | result_line += '\t{:.3f}'.format(result)
91 | latex_line += ' & {:.3f}'.format(result)
92 | elif args.dist:
93 | result_line += '\t{:.1f}'.format(result)
94 | latex_line += ' & {:.1f}'.format(result)
95 | print(result_line)
96 | latex_table.append(latex_line + '\\\\')
97 | print()
98 | print('\n'.join(latex_table))
99 | print()
100 |
101 | return
102 |
103 |
104 | def compute_average_stats(file, stats="all"):
105 | results = {}
106 | with open(file, 'r') as tsv:
107 | tsv = csv.reader(tsv, delimiter='\t')
108 | for line in tsv:
109 | # print(line)
110 | stat = line[0]
111 | values = [x for x in line[1:] if x!='-']
112 | if stats=="all" or stat in stats:
113 | try:
114 | av = sum([float(x) for x in values])/len(values)
115 | results[stat] = av
116 | except ZeroDivisionError as e:
117 | # all values were '-' i.e. not available
118 | av = '-'
119 | # print(stat, av)
120 | return results
121 |
122 | if __name__ == '__main__':
123 | sys.exit(main())
124 |
--------------------------------------------------------------------------------
/evaluation/contig_abundance_evaluation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import os
3 | import sys
4 | import subprocess
5 | import copy
6 | import multiprocessing as mp
7 | import numpy as np # array, arange, minimum, add (levenshtein)
8 | import itertools # groupby()
9 | import argparse
10 |
11 | def main():
12 | parser = argparse.ArgumentParser(prog='assembly_evaluation.py', description='Compare assembled contigs to ground truth haplotypes.')
13 | parser.add_argument('-c', '--contigs', type=str, required=True)
14 | parser.add_argument('-gt', '--ground_truth', dest='truth', type=str, required=True)
15 | parser.add_argument('-m', '--max_edit', dest='max_edit', type=float, default=0)
16 | parser.add_argument('-o', '--outdir', dest='outdir', default=".", help="write output files to this directory")
17 | parser.add_argument('-f', '--freq_truth', dest='freq_truth', help="file containing true frequency per ground truth strain")
18 | parser.add_argument('--total_cov', dest='total_cov', type=float, required=True)
19 | args = parser.parse_args()
20 |
21 | print("-----------------------------------------------")
22 | if not args.contigs:
23 | print("No contig file given. Aborting evaluation.")
24 | sys.exit(1)
25 | else:
26 | print("Contig file = {}".format(args.contigs))
27 | print("Truth file = {}".format(args.truth))
28 |
29 | # read contig abundance estimates and true haplotypes
30 | contigs, ab_est = read_fasta(args.contigs, read_ab=True)
31 | ground_truth, empty = read_fasta(args.truth)
32 | freq_truth = read_frequencies(args.freq_truth)
33 | print("Number of contigs: {}".format(len(contigs)))
34 | print("Number of reference sequences: {}".format(len(ground_truth)))
35 | if not contigs:
36 | print("No contigs found, exiting.")
37 | sys.exit(1)
38 |
39 | # assign contigs to strains -- note that:
40 | # (1) a contig may be assigned to multiple strains (conserved region)
41 | # (2) multiple contigs could map to the same strain, in the same region,
42 | # due to uncorrected errors. To avoid this situation we only evaluate
43 | # perfectly matching contigs
44 | # format: {contig id : [score, aln, aln_range]}
45 | contig_assignments = assign_contigs(args.contigs, args.truth, args.max_edit,
46 | args.outdir)
47 |
48 | # how many contigs match perfectly?
49 | evaluation_ratio = len(contig_assignments) / len(contigs)
50 | discarded = len(contigs) - len(contig_assignments)
51 | print("# contigs excluded from evaluation = {}".format(discarded))
52 | print("Evaluation ratio = {:.2f}\n".format(evaluation_ratio))
53 |
54 | total_assembly_freq = 0
55 | assembled_seqs = set([x[1][1] for l in contig_assignments.values() for x in l])
56 | for seq, freq in freq_truth.items():
57 | if seq in assembled_seqs:
58 | total_assembly_freq += freq
59 |
60 | # calculate true contig abundances
61 | results = []
62 | with open("{}/contig_abundance_estimates.txt".format(args.outdir), 'w') as f:
63 | for contig_id, assignment in contig_assignments.items():
64 | true_freq = calculate_freq(assignment, freq_truth, total_assembly_freq)
65 | true_ab = true_freq * args.total_cov
66 | estimate = ab_est[contig_id]
67 | results.append((true_ab, estimate))
68 | pos = assignment[0][1][2]
69 | f.write("{} {} {}\n".format(true_ab, estimate, pos))
70 | print(contig_id, assignment[0][1][1], len(contigs[contig_id]),
71 | true_ab, estimate)
72 | if not results:
73 | print("No results calculated, exiting.")
74 | sys.exit(1)
75 |
76 | # evaluate estimates
77 | total_error = 0
78 | abs_err = 0
79 | for (v1, v2) in results:
80 | if v1 + v2 > 0:
81 | total_error += abs(v1-v2) / (0.5 * (v1+v2))
82 | abs_err += abs(v1-v2) / args.total_cov
83 | rel_error = total_error / len(results) * 100
84 | abs_err = abs_err / len(results) * 100
85 | print("Relative abundance estimation error = {:.1f}%".format(rel_error))
86 | # print("Absolute abundance estimation error = {:.1f}%".format(abs_err))
87 | print("-----------------------------------------------")
88 | return
89 |
90 |
91 | def calculate_freq(assignment, freq_truth, total_assembly_freq):
92 | true_freq = 0
93 | for aln_info in assignment:
94 | [score, aln, aln_range] = aln_info
95 | truth_id = aln[1]
96 | true_freq += freq_truth[truth_id]
97 | if true_freq == 0:
98 | print(assignment)
99 | assert true_freq > 0
100 | return true_freq / total_assembly_freq
101 |
102 |
103 | def assign_contigs(contig_file, truth_file, max_edit, outdir):
104 | contigs, empty = read_fasta(contig_file)
105 | ground_truth, empty = read_fasta(truth_file)
106 | contigs2aln= {contig_id : [] for contig_id in contigs.keys()}
107 |
108 | # run bwa mem -a to align contigs to ground truth
109 | print("\nAligning contigs against ground truth...")
110 | sam_file = "{}/contigs_to_truth.sam".format(outdir.rstrip('/'))
111 | subprocess.check_call("bwa index {} 2>/dev/null".format(truth_file),
112 | shell=True)
113 | subprocess.check_call(
114 | "bwa mem -a -L1000 -t 12 {0} {1} > {2} 2>/dev/null".format(
115 | truth_file, contig_file, sam_file),
116 | shell=True)
117 | print()
118 | # score all alignments per contig and select the good alignment(s)
119 | [alignments, unmapped_ids] = read_sam(sam_file)
120 | print("#alignments: {}".format(len(alignments)))
121 | print("#unmapped: {}".format(len(unmapped_ids)))
122 | # score and store alignments
123 | for aln in alignments:
124 | #print aln
125 | [contig_id, ref_id] = aln[0:2]
126 | contig_seq = contigs[contig_id]
127 | truth_seq = ground_truth[ref_id]
128 | [score, aln_range] = score_alignment(aln, contig_seq, truth_seq)
129 | if score[0] <= max_edit:
130 | contigs2aln[contig_id].append([score, aln, aln_range])
131 | os.remove(sam_file)
132 |
133 | # select optimal alignment(s)
134 | contig_assignments = {}
135 | for contig, aln_list in contigs2aln.items():
136 | min_score = 1
137 | opt_aln = []
138 | #print contig
139 | #print aln_list
140 | for i in range(len(aln_list)):
141 | info1 = aln_list[i]
142 | if info1 in opt_aln:
143 | # alignment already paired with another alignment
144 | continue
145 | scores1 = info1[0]
146 | combined = False
147 | for j in range(i+1, len(aln_list)):
148 | info2 = aln_list[j]
149 | # check if these alignments can be combined
150 | if info2[1][1] != info1[1][1]: # not to same ref sequence
151 | continue
152 | elif not (info2[2][1] <= info1[2][0]
153 | or info2[2][0] >= info1[2][1]):
154 | # overlapping alignments
155 | if info2[2][1] >= info1[2][0] and info1[2][1] >= info2[2][0]:
156 | ov_len = info1[2][1]-info2[2][0]
157 | elif info1[2][1] >= info2[2][0] and info2[2][1] >= info1[2][0]:
158 | ov_len = info2[2][1]-info1[2][0]
159 | else:
160 | print("no overlap???")
161 | sys.exit(1)
162 | print("\noverlap of length {} for contig {} on ref {}\n".format(ov_len, contig, info1[1][1]))
163 | ref_len = info1[2][2]
164 | if ov_len > 0.1*ref_len:
165 | print("overlap too long, skipping")
166 | continue
167 | # compute combined score (assigning contig to 2 allele sequences)
168 | combined = True
169 | combined_score = (info1[0][0]*info1[2][2]
170 | + info2[0][0]*info2[2][2]) / (info1[2][2] + info2[2][2])
171 | # now check if this alignment is optimal
172 | if combined_score == min_score:
173 | ref_id = info1[1][1]
174 | new_aln = True
175 | for aln in opt_aln:
176 | if aln[1][1] != ref_id:
177 | continue
178 | else:
179 | new_aln = False
180 | break
181 | if new_aln:
182 | opt_aln.append(info1)
183 | opt_aln.append(info2)
184 | elif combined_score < min_score:
185 | opt_aln = [info1, info2]
186 | min_score = combined_score
187 | # if there is no pairing, check single alignemnt
188 | if not combined:
189 | scores = scores1
190 | if scores[0] == min_score:
191 | ref_id = info1[1][1]
192 | new_aln = True
193 | for aln in opt_aln:
194 | if aln[1][1] != ref_id:
195 | continue
196 | else:
197 | new_aln = False
198 | break
199 | if new_aln:
200 | opt_aln.append(info1)
201 | elif scores[0] < min_score:
202 | opt_aln = [info1]
203 | min_score = scores[0]
204 | if opt_aln:
205 | contig_assignments[contig] = opt_aln
206 | count = len(opt_aln)
207 | if count > 1:
208 | print("NOTE: contig {} has {} assignments!".format(contig, count))
209 | return contig_assignments
210 |
211 |
212 | def score_alignment(aln, contig, truth):
213 | [seq_id, ref_id, pos, ori, cigar] = aln
214 | if ori == "-":
215 | contig = revcomp(contig)
216 | # split cigar into numbers and characters all separately
217 | splitcigar = ["".join(x) for _, x in itertools.groupby(cigar,
218 | key=str.isdigit)]
219 | # count mismatches, insertions, deletions and N's
220 | mismatch_count = 0
221 | ins_count = 0
222 | ins_len = 0
223 | del_count = 0
224 | del_len = 0
225 | N_count = 0
226 | length = len(contig)
227 | # keep track of position and cigar index
228 | contig_pos = 0
229 | truth_pos = pos
230 | start_pos = pos
231 | i = 0
232 | while i+1 < len(splitcigar):
233 | aln_len = int(splitcigar[i])
234 | aln_type = splitcigar[i+1]
235 | if aln_type == "S" or aln_type == "H":
236 | if i == 0: # front end clipped
237 | # if pos > 0:
238 | # del_count += 1
239 | # del_len += pos
240 | clipped_truth = min(aln_len, pos)
241 | length -= aln_len - clipped_truth # correct for overhanging contig length
242 | start_pos -= clipped_truth
243 | contig_pos += aln_len
244 | elif i > 0: # back end clipped
245 | clipped_truth = min(aln_len, len(truth)-truth_pos)
246 | # clipped_truth = len(truth) - truth_pos
247 | # if clipped_truth < 0:
248 | # del_count += 1
249 | # del_len += clipped_truth
250 | length -= aln_len - clipped_truth
251 | contig_pos += aln_len
252 | # truth_pos = len(truth) - clipped_truth
253 | truth_pos += clipped_truth
254 | # compare (partially) aligned sequences
255 | contig_part = contig[contig_pos-clipped_truth : contig_pos]
256 | truth_part = truth[truth_pos-clipped_truth : truth_pos]
257 | [mismatches, Ns] = count_mismatches(contig_part, truth_part)
258 | mismatch_count += mismatches
259 | N_count += Ns
260 | elif aln_type == "I":
261 | if i > 0 and i < len(splitcigar)-2:
262 | ins_count += 1
263 | ins_len += aln_len
264 | N_count += contig[contig_pos:contig_pos+aln_len].count('N')
265 | contig_pos += aln_len
266 | elif aln_type == "D":
267 | del_count += 1
268 | del_len += aln_len
269 | truth_pos += aln_len
270 | elif aln_type == "M":
271 | if contig_pos + aln_len > len(contig):
272 | print("contig {} too short?".format(seq_id))
273 | print(contig_pos, aln_len, len(contig))
274 | print(pos, cigar)
275 | if truth_pos + aln_len > len(truth):
276 | print("truth too short?")
277 | print(truth_pos, aln_len, len(truth))
278 | print(pos, cigar)
279 | contig_part = contig[contig_pos : contig_pos + aln_len]
280 | truth_part = truth[truth_pos : truth_pos + aln_len]
281 | [mismatches, Ns] = count_mismatches(contig_part, truth_part)
282 | mismatch_count += mismatches
283 | N_count += Ns
284 | truth_pos += aln_len
285 | contig_pos += aln_len
286 | else:
287 | print("ERROR: cigar string not recognized.")
288 | sys.exit(1)
289 | i += 2
290 | # compute percent identity
291 | if length > 0:
292 | score = (mismatch_count + ins_len + del_len) / float(length)
293 | else:
294 | score = 0
295 | aln_scores = [score, mismatch_count, ins_count, ins_len, del_count, del_len,
296 | N_count]
297 | assert start_pos >= 0
298 | assert truth_pos <= len(truth)
299 | assert start_pos <= truth_pos
300 | aln_range = [start_pos, truth_pos, len(truth)]
301 | edit_distance = mismatch_count + ins_len + del_len
302 | return [aln_scores, aln_range]
303 |
304 | def count_mismatches(seq1, seq2):
305 | assert len(seq1) == len(seq2)
306 | mismatches = 0
307 | Ns = 0
308 | for i in range(len(seq1)):
309 | if seq1[i] == "N": # truth has N
310 | Ns += 1
311 | elif seq2[i] == "N": # contig has N
312 | Ns += 1
313 | elif seq1[i] != seq2[i]:
314 | mismatches += 1
315 | return [mismatches, Ns]
316 |
317 |
318 | def revcomp(seq):
319 | complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}
320 | revcomp = "".join(complement.get(base, base) for base in reversed(seq))
321 | assert len(seq) == len(revcomp)
322 | return revcomp
323 |
324 |
325 | def read_frequencies(freq_truth):
326 | # read true frequencies
327 | true_frequencies = {}
328 | with open(freq_truth, 'r') as f:
329 | for line in f:
330 | [seq_id, freq] = line.strip('\n').split()
331 | true_frequencies[seq_id] = float(freq)
332 | return true_frequencies
333 |
334 |
335 | def read_fasta(filename, read_ab=False):
336 | # returns ID to sequence dict
337 | id2seq = {}
338 | ab_est = {}
339 | with open(filename, 'r') as f:
340 | seq_id = ""
341 | seq = ""
342 | for line in f:
343 | if line[0] == '>':
344 | if seq_id != "" and seq != "":
345 | id2seq[seq_id] = seq
346 | if read_ab:
347 | ab_est[seq_id] = ab # estimated abundance
348 | seq_id = line.lstrip('>').rstrip('\n').split()[0]
349 | if read_ab:
350 | try:
351 | ab = float(line.lstrip('>').rstrip('\n').split()[-1].lstrip('ab=').rstrip('x'))
352 | except ValueError:
353 | print("WARNING: could not read abundance estimates from fasta")
354 | read_ab = False
355 | seq = ""
356 | else:
357 | seq += line.rstrip('\n')
358 | # add final entry
359 | if seq_id != "" and seq != "":
360 | id2seq[seq_id] = seq
361 | if read_ab:
362 | ab_est[seq_id] = ab # estimated abundance
363 | return id2seq, ab_est
364 |
365 |
366 | def read_sam(filename):
367 | # returns a list of all alignments, where each alignment is presented in the
368 | # following format: [seq_id, ref_id, pos, ori, cigar]
369 | aln_list = []
370 | unmapped_ids = []
371 | with open(filename, 'r') as f:
372 | for line in f:
373 | if line[0] == "@":
374 | continue
375 | line = line.rstrip('\n').split()
376 | [seq_id, flag, ref_id, pos] = line[0:4]
377 | cigar = line[5]
378 | bits_flag = power_find(int(flag))
379 | if 4 in bits_flag: # unmapped contig
380 | unmapped_ids.append(seq_id)
381 | continue
382 | elif 16 in bits_flag: # reversed contig
383 | ori = "-"
384 | else:
385 | ori = "+"
386 | aln_list.append([seq_id, ref_id, int(pos)-1, ori, cigar]) # SAM-format is 1-based; switching to 0-based here
387 | return [aln_list, unmapped_ids]
388 |
389 | def power_find(n):
390 | try:
391 | int(n)
392 | except TypeError:
393 | print("power_find TypeError")
394 | print("n = {}".format(n))
395 | sys.exit(1)
396 | result = []
397 | binary = bin(n)[:1:-1]
398 | for x in range(len(binary)):
399 | if int(binary[x]):
400 | result.append(2**x)
401 | return result
402 |
403 |
404 | if __name__ == '__main__':
405 | sys.exit(main())
--------------------------------------------------------------------------------
/evaluation/plot_prec_recall.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import sys
3 | import matplotlib.pyplot as plt
4 | import pandas as pd
5 | import numpy as np
6 | import seaborn as sns
7 | import argparse
8 | #
9 | # INDEX = {
10 | # "savage" : 1,
11 | # "virus-vg" : 2,
12 | # "vg-flow": 8,
13 | # "abayesqr" : 5,
14 | # "pehaplo" : 7,
15 | # "predicthaplo" : 3,
16 | # "shorah" : 4
17 | # }
18 |
19 | INDEX = {
20 | "victor" : 1,
21 | "canu" : 2,
22 | "wtdgb2" : 3,
23 | }
24 |
25 | FORMAT = ["method", "contig_id", "truth_id", "aln_len", "edit_dist",
26 | "mismatches", "ins_len", "del_len"]
27 |
28 | def main():
29 | parser = argparse.ArgumentParser(prog='assembly_evaluation.py', description='Compare assembled contigs to ground truth haplotypes.')
30 | parser.add_argument('contigs', nargs='*', type=str)
31 | parser.add_argument('-a', '--assignments', dest='assignments', type=str, required=True)
32 | parser.add_argument('-n', '--num_strains', dest='num_strains', type=int, required=True)
33 | args = parser.parse_args()
34 |
35 | ref_count = args.num_strains
36 | dist_bins = range(0, 6)
37 | data = pd.read_csv(args.assignments, names=FORMAT,sep="\t")
38 | print(data)
39 | sns.set(style="ticks", context="paper", palette="muted")
40 | fig, axs = plt.subplots(1, 3, sharey=True, figsize=(10, 3), tight_layout=True)
41 | axs[0].set_title("Precision")
42 | axs[1].set_title("Recall")
43 | axs[2].set_title("F-measure")
44 | # print(data["method"].unique())
45 | for method in args.contigs:
46 | print(method)
47 | method_file = method.split('/')[-1]
48 | method_name = method_file.rstrip(".fa")
49 | color = sns.color_palette()[INDEX[method_name]]
50 | ncontigs = fasta_len(method)
51 | if ncontigs == 0:
52 | continue
53 | subdata = data.loc[data["method"] == method_file]
54 | print(subdata)
55 | stats = [compute_stats(subdata, dist, ref_count, ncontigs) for dist in dist_bins]
56 | precision = [x[0] for x in stats]
57 | recall = [x[1] for x in stats]
58 | f_score = [x[2] for x in stats]
59 | axs[0].plot(dist_bins, precision, label=method_name, color=color)
60 | axs[1].plot(dist_bins, recall, label=method_name, color=color)
61 | axs[2].plot(dist_bins, f_score, label=method_name, color=color)
62 | for ax in axs:
63 | ax.set_xticks(dist_bins)
64 | ax.set_xlabel("max % edit distance")
65 | plt.legend(loc='upper center', bbox_to_anchor=(1.35, 0.75), shadow=True, ncol=1)
66 | plt.savefig('prec_recall_fscore.png')
67 | plt.show()
68 | return
69 |
70 |
71 | def compute_stats(data, max_edit_perc, ref_count, ncontigs):
72 | true_positives = set()
73 | matched_ref = set()
74 | for index, record in data.iterrows():
75 | print(record)
76 | edit_perc = record['edit_dist'] / record['aln_len'] * 100
77 | if edit_perc <= max_edit_perc:
78 | true_positives.add(record['contig_id'])
79 | matched_ref.add(record['truth_id'])
80 | print(matched_ref)
81 | recall = len(matched_ref) / ref_count
82 | precision = len(true_positives) / ncontigs if ncontigs > 0 else 0
83 | if precision + recall > 0:
84 | f_score = 2 * precision * recall / (precision + recall)
85 | else:
86 | f_score = 0
87 | print(precision,recall,f_score)
88 | return precision, recall, f_score
89 |
90 |
91 | def fasta_len(fname):
92 | with open(fname) as f:
93 | i = 0
94 | for line in f:
95 | if line[0] == '>':
96 | i += 1
97 | return i
98 |
99 |
100 | if __name__ == '__main__':
101 | sys.exit(main())
102 |
--------------------------------------------------------------------------------
/evaluation/plot_prec_recall_av.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import sys
3 | import matplotlib.pyplot as plt
4 | import pandas as pd
5 | import numpy as np
6 | import seaborn as sns
7 | import argparse
8 |
9 | INDEX = {
10 | "savage" : 1,
11 | "virus-vg" : 2,
12 | "abayesqr" : 5,
13 | "pehaplo" : 7,
14 | "predicthaplo" : 3,
15 | "shorah" : 4
16 | }
17 |
18 | FORMAT = ["method", "contig_id", "truth_id", "aln_len", "edit_dist",
19 | "mismatches", "ins_len", "del_len"]
20 |
21 | def main():
22 | parser = argparse.ArgumentParser(prog='assembly_evaluation.py', description='Compare assembled contigs to ground truth haplotypes.')
23 | # parser.add_argument('contigs', nargs='*', type=str)
24 | parser.add_argument('-a', '--assignments', dest='assignments', type=str, required=True)
25 | parser.add_argument('-n', '--num_strains', dest='num_strains', type=int, required=True)
26 | parser.add_argument('-c', '--cov_list', dest='cov_list', type=str, required=True)
27 | args = parser.parse_args()
28 |
29 | ref_count = args.num_strains
30 | dist_bins = range(0, 6)
31 | data = pd.read_csv(args.assignments, names=FORMAT,sep="\t")
32 |
33 | # print(data)
34 | sns.set(style="ticks", context="paper", palette="muted")
35 | # print(data["method"].unique())
36 | for cov in args.cov_list.split(','):
37 | print("{}x".format(cov))
38 | fig, axs = plt.subplots(1, 3, sharey=True, figsize=(10, 3), tight_layout=True)
39 | axs[0].set_title("Precision")
40 | axs[1].set_title("Recall")
41 | axs[2].set_title("F-measure")
42 | for method_name in INDEX.keys():
43 | print(method_name)
44 | color = sns.color_palette()[INDEX[method_name]]
45 | prec_list = []
46 | recall_list = []
47 | f_score_list = []
48 | for sample in range(1, 11):
49 | filename = "{}/sample{}.{}x.fasta".format(method_name, sample, cov)
50 | try:
51 | ncontigs = int(fasta_len(filename))
52 | except FileNotFoundError as e:
53 | continue
54 | if ncontigs == 0:
55 | continue
56 | subdata = data.loc[data["method"] == filename]
57 | # print(subdata)
58 | stats = [compute_stats(subdata, dist, ref_count, ncontigs) for dist in dist_bins]
59 | prec_list.append([x[0] for x in stats])
60 | recall_list.append([x[1] for x in stats])
61 | f_score_list.append([x[2] for x in stats])
62 | nsamples = len(prec_list)
63 | if nsamples == 0:
64 | continue
65 | precision = np.mean(np.array(prec_list), axis=0)
66 | prec_std = np.std(np.array(prec_list), axis=0)
67 | recall = np.mean(np.array(recall_list), axis=0)
68 | recall_std = np.std(np.array(recall_list), axis=0)
69 | f_score = np.mean(np.array(f_score_list), axis=0)
70 | f_score_std = np.std(np.array(f_score_list), axis=0)
71 | # now plot these averages with error bars
72 | axs[0].errorbar(dist_bins, precision, yerr=prec_std, capsize=3,
73 | label=method_name, color=color)
74 | axs[1].errorbar(dist_bins, recall, yerr=recall_std, capsize=3,
75 | label=method_name, color=color)
76 | axs[2].errorbar(dist_bins, f_score, yerr=f_score_std, capsize=3,
77 | label=method_name, color=color)
78 | for ax in axs:
79 | ax.set_xticks(dist_bins)
80 | ax.set_xlabel("max % edit distance")
81 | plt.legend(loc='upper center', bbox_to_anchor=(1.35, 0.75), shadow=True, ncol=1)
82 | plt.savefig('prec_recall_fscore.{}x.eps'.format(cov))
83 | plt.show()
84 | return
85 |
86 |
87 | def compute_stats(data, max_edit_perc, ref_count, ncontigs):
88 | true_positives = set()
89 | matched_ref = set()
90 | for index, record in data.iterrows():
91 | # print(record)
92 | edit_perc = record['edit_dist'] / record['aln_len'] * 100
93 | if edit_perc <= max_edit_perc:
94 | true_positives.add(record['contig_id'])
95 | matched_ref.add(record['truth_id'])
96 | recall = len(matched_ref) / ref_count
97 | precision = len(true_positives) / ncontigs if ncontigs > 0 else 0
98 | if precision + recall > 0:
99 | f_score = 2 * precision * recall / (precision + recall)
100 | else:
101 | f_score = 0
102 | return precision, recall, f_score
103 |
104 |
105 | def fasta_len(fname):
106 | with open(fname) as f:
107 | i = 0
108 | for line in f:
109 | if line[0] == '>':
110 | i += 1
111 | return i
112 |
113 |
114 | if __name__ == '__main__':
115 | sys.exit(main())
116 |
--------------------------------------------------------------------------------
/example/ref.fa:
--------------------------------------------------------------------------------
1 | >HXB2
2 | TGGAAGGGCTAATTCACTCCCAAAGAAGACAAGATATCCTTGATCTGTGGATCTACCACACACAAGGCTACTTCCCTGATTAGCAGAACTACACACCAGGGCCAGGGGTCAGATATCCACTGACCTTTGGATGGTGCTACAAGCTAGTACCAGTTGAGCCAGAGAAGGTAGAAGAAGCCAATAAAGGAGAGAACACCAGCTTGTTACACCCTGTGAGCCTGCATGGGATGGATGACCCGGAGAGAGAAGTGTTAGAGTGGAGGTTTGACAGCCGCCTAGCATTTCATCACGTGGCCCGAGAGCTGCATCCGGAGTACTTCAAGAACTGCTGATATCGAGCTTGCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGCGTGGCCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATCCTGCATATAAGCAGCTGCTTTTTGCCTGTACTGGGTCTCTCTGGTTAGACCAGATCTGAGCCTGGGAGCTCTCTGGCTAACTAGGGAACCCACTGCTTAAGCCTCAATAAAGCTTGCCTTGAGTGCTTCAAGTAGTGTGTGCCCGTCTGTTGTGTGACTCTGGTAACTAGAGATCCCTCAGACCCTTTTAGTCAGTGTGGAAAATCTCTAGCAGTGGCGCCCGAACAGGGACTTGAAAGCGAAAGGGAAACCAGAGGAGCTCTCTCGACGCAGGACTCGGCTTGCTGAAGCGCGCACGGCAAGAGGCGAGGGGCGGCGACTGGTGAGTACGCCAAAAATTTTGACTAGCGGAGGCTAGAAGGAGAGAGATGGGTGCGAGAGCGTCAGTATTAAGCGGGGGAGAATTAGATCGATGGGAAAAAATTCGGTTAAGGCCAGGGGGAAAGAAAAAATATAAATTAAAACATATAGTATGGGCAAGCAGGGAGCTAGAACGATTCGCAGTTAATCCTGGCCTGTTAGAAACATCAGAAGGCTGTAGACAAATACTGGGACAGCTACAACCATCCCTTCAGACAGGATCAGAAGAACTTAGATCATTATATAATACAGTAGCAACCCTCTATTGTGTGCATCAAAGGATAGAGATAAAAGACACCAAGGAAGCTTTAGACAAGATAGAGGAAGAGCAAAACAAAAGTAAGAAAAAAGCACAGCAAGCAGCAGCTGACACAGGACACAGCAATCAGGTCAGCCAAAATTACCCTATAGTGCAGAACATCCAGGGGCAAATGGTACATCAGGCCATATCACCTAGAACTTTAAATGCATGGGTAAAAGTAGTAGAAGAGAAGGCTTTCAGCCCAGAAGTGATACCCATGTTTTCAGCATTATCAGAAGGAGCCACCCCACAAGATTTAAACACCATGCTAAACACAGTGGGGGGACATCAAGCAGCCATGCAAATGTTAAAAGAGACCATCAATGAGGAAGCTGCAGAATGGGATAGAGTGCATCCAGTGCATGCAGGGCCTATTGCACCAGGCCAGATGAGAGAACCAAGGGGAAGTGACATAGCAGGAACTACTAGTACCCTTCAGGAACAAATAGGATGGATGACAAATAATCCACCTATCCCAGTAGGAGAAATTTATAAAAGATGGATAATCCTGGGATTAAATAAAATAGTAAGAATGTATAGCCCTACCAGCATTCTGGACATAAGACAAGGACCAAAAGAACCCTTTAGAGACTATGTAGACCGGTTCTATAAAACTCTAAGAGCCGAGCAAGCTTCACAGGAGGTAAAAAATTGGATGACAGAAACCTTGTTGGTCCAAAATGCGAACCCAGATTGTAAGACTATTTTAAAAGCATTGGGACCAGCGGCTACACTAGAAGAAATGATGACAGCATGTCAGGGAGTAGGAGGACCCGGCCATAAGGCAAGAGTTTTGGCTGAAGCAATGAGCCAAGTAACAAATTCAGCTACCATAATGATGCAGAGAGGCAATTTTAGGAACCAAAGAAAGATTGTTAAGTGTTTCAATTGTGGCAAAGAAGGGCACACAGCCAGAAATTGCAGGGCCCCTAGGAAAAAGGGCTGTTGGAAATGTGGAAAGGAAGGACACCAAATGAAAGATTGTACTGAGAGACAGGCTAATTTTTTAGGGAAGATCTGGCCTTCCTACAAGGGAAGGCCAGGGAATTTTCTTCAGAGCAGACCAGAGCCAACAGCCCCACCAGAAGAGAGCTTCAGGTCTGGGGTAGAGACAACAACTCCCCCTCAGAAGCAGGAGCCGATAGACAAGGAACTGTATCCTTTAACTTCCCTCAGATCACTCTTTGGCAACGACCCCTCGTCACAATAAAGATAGGGGGGCAACTAAAGGAAGCTCTATTAGATACAGGAGCAGATGATACAGTATTAGAAGAAATGAGTTTGCCAGGAAGATGGAAACCAAAAATGATAGGGGGAATTGGAGGTTTTATCAAAGTAAGACAGTATGATCAGATACTCATAGAAATCTGTGGACATAAAGCTATAGGTACAGTATTAGTAGGACCTACACCTGTCAACATAATTGGAAGAAATCTGTTGACTCAGATTGGTTGCACTTTAAATTTTCCCATTAGCCCTATTGAGACTGTACCAGTAAAATTAAAGCCAGGAATGGATGGCCCAAAAGTTAAACAATGGCCATTGACAGAAGAAAAAATAAAAGCATTAGTAGAAATTTGTACAGAGATGGAAAAGGAAGGGAAAATTTCAAAAATTGGGCCTGAAAATCCATACAATACTCCAGTATTTGCCATAAAGAAAAAAGACAGTACTAAATGGAGAAAATTAGTAGATTTCAGAGAACTTAATAAGAGAACTCAAGACTTCTGGGAAGTTCAATTAGGAATACCACATCCCGCAGGGTTAAAAAAGAAAAAATCAGTAACAGTACTGGATGTGGGTGATGCATATTTTTCAGTTCCCTTAGATGAAGACTTCAGGAAATATACTGCATTTACCATACCTAGTATAAACAATGAGACACCAGGGATTAGATATCAGTACAATGTGCTTCCACAGGGATGGAAAGGATCACCAGCAATATTCCAAAGTAGCATGACAAAAATCTTAGAGCCTTTTAGAAAACAAAATCCAGACATAGTTATCTATCAATACATGGATGATTTGTATGTAGGATCTGACTTAGAAATAGGGCAGCATAGAACAAAAATAGAGGAGCTGAGACAACATCTGTTGAGGTGGGGACTTACCACACCAGACAAAAAACATCAGAAAGAACCTCCATTCCTTTGGATGGGTTATGAACTCCATCCTGATAAATGGACAGTACAGCCTATAGTGCTGCCAGAAAAAGACAGCTGGACTGTCAATGACATACAGAAGTTAGTGGGGAAATTGAATTGGGCAAGTCAGATTTACCCAGGGATTAAAGTAAGGCAATTATGTAAACTCCTTAGAGGAACCAAAGCACTAACAGAAGTAATACCACTAACAGAAGAAGCAGAGCTAGAACTGGCAGAAAACAGAGAGATTCTAAAAGAACCAGTACATGGAGTGTATTATGACCCATCAAAAGACTTAATAGCAGAAATACAGAAGCAGGGGCAAGGCCAATGGACATATCAAATTTATCAAGAGCCATTTAAAAATCTGAAAACAGGAAAATATGCAAGAATGAGGGGTGCCCACACTAATGATGTAAAACAATTAACAGAGGCAGTGCAAAAAATAACCACAGAAAGCATAGTAATATGGGGAAAGACTCCTAAATTTAAACTGCCCATACAAAAGGAAACATGGGAAACATGGTGGACAGAGTATTGGCAAGCCACCTGGATTCCTGAGTGGGAGTTTGTTAATACCCCTCCTTTAGTGAAATTATGGTACCAGTTAGAGAAAGAACCCATAGTAGGAGCAGAAACCTTCTATGTAGATGGGGCAGCTAACAGGGAGACTAAATTAGGAAAAGCAGGATATGTTACTAATAGAGGAAGACAAAAAGTTGTCACCCTAACTGACACAACAAATCAGAAGACTGAGTTACAAGCAATTTATCTAGCTTTGCAGGATTCGGGATTAGAAGTAAACATAGTAACAGACTCACAATATGCATTAGGAATCATTCAAGCACAACCAGATCAAAGTGAATCAGAGTTAGTCAATCAAATAATAGAGCAGTTAATAAAAAAGGAAAAGGTCTATCTGGCATGGGTACCAGCACACAAAGGAATTGGAGGAAATGAACAAGTAGATAAATTAGTCAGTGCTGGAATCAGGAAAGTACTATTTTTAGATGGAATAGATAAGGCCCAAGATGAACATGAGAAATATCACAGTAATTGGAGAGCAATGGCTAGTGATTTTAACCTGCCACCTGTAGTAGCAAAAGAAATAGTAGCCAGCTGTGATAAATGTCAGCTAAAAGGAGAAGCCATGCATGGACAAGTAGACTGTAGTCCAGGAATATGGCAACTAGATTGTACACATTTAGAAGGAAAAGTTATCCTGGTAGCAGTTCATGTAGCCAGTGGATATATAGAAGCAGAAGTTATTCCAGCAGAAACAGGGCAGGAAACAGCATATTTTCTTTTAAAATTAGCAGGAAGATGGCCAGTAAAAACAATACATACAGACAATGGCAGCAATTTCACCAGTGCTACGGTTAAGGCCGCCTGTTGGTGGGCGGGAATCAAGCAGGAATTTGGAATTCCCTACAATCCCCAAAGTCAAGGAGTAGTAGAATCTATGAATAAAGAATTAAAGAAAATTATAGGACAGGTAAGAGATCAGGCTGAACATCTTAAGACAGCAGTACAAATGGCAGTATTCATCCACAATTTTAAAAGAAAAGGGGGGATTGGGGGGTACAGTGCAGGGGAAAGAATAGTAGACATAATAGCAACAGACATACAAACTAAAGAATTACAAAAACAAATTACAAAAATTCAAAATTTTCGGGTTTATTACAGGGACAGCAGAAATCCACTTTGGAAAGGACCAGCAAAGCTCCTCTGGAAAGGTGAAGGGGCAGTAGTAATACAAGATAATAGTGACATAAAAGTAGTGCCAAGAAGAAAAGCAAAGATCATTAGGGATTATGGAAAACAGATGGCAGGTGATGATTGTGTGGCAAGTAGACAGGATGAGGATTAGAACATGGAAAAGTTTAGTAAAACACCATATGTATGTTTCAGGGAAAGCTAGGGGATGGTTTTATAGACATCACTATGAAAGCCCTCATCCAAGAATAAGTTCAGAAGTACACATCCCACTAGGGGATGCTAGATTGGTAATAACAACATATTGGGGTCTGCATACAGGAGAAAGAGACTGGCATTTGGGTCAGGGAGTCTCCATAGAATGGAGGAAAAAGAGATATAGCACACAAGTAGACCCTGAACTAGCAGACCAACTAATTCATCTGTATTACTTTGACTGTTTTTCAGACTCTGCTATAAGAAAGGCCTTATTAGGACACATAGTTAGCCCTAGGTGTGAATATCAAGCAGGACATAACAAGGTAGGATCTCTACAATACTTGGCACTAGCAGCATTAATAACACCAAAAAAGATAAAGCCACCTTTGCCTAGTGTTACGAAACTGACAGAGGATAGATGGAACAAGCCCCAGAAGACCAAGGGCCACAGAGGGAGCCACACAATGAATGGACACTAGAGCTTTTAGAGGAGCTTAAGAATGAAGCTGTTAGACATTTTCCTAGGATTTGGCTCCATGGCTTAGGGCAACATATCTATGAAACTTATGGGGATACTTGGGCAGGAGTGGAAGCCATAATAAGAATTCTGCAACAACTGCTGTTTATCCATTTTCAGAATTGGGTGTCGACATAGCAGAATAGGCGTTACTCGACAGAGGAGAGCAAGAAATGGAGCCAGTAGATCCTAGACTAGAGCCCTGGAAGCATCCAGGAAGTCAGCCTAAAACTGCTTGTACCAATTGCTATTGTAAAAAGTGTTGCTTTCATTGCCAAGTTTGTTTCATAACAAAAGCCTTAGGCATCTCCTATGGCAGGAAGAAGCGGAGACAGCGACGAAGAGCTCATCAGAACAGTCAGACTCATCAAGCTTCTCTATCAAAGCAGTAAGTAGTACATGTAACGCAACCTATACCAATAGTAGCAATAGTAGCATTAGTAGTAGCAATAATAATAGCAATAGTTGTGTGGTCCATAGTAATCATAGAATATAGGAAAATATTAAGACAAAGAAAAATAGACAGGTTAATTGATAGACTAATAGAAAGAGCAGAAGACAGTGGCAATGAGAGTGAAGGAGAAATATCAGCACTTGTGGAGATGGGGGTGGAGATGGGGCACCATGCTCCTTGGGATGTTGATGATCTGTAGTGCTACAGAAAAATTGTGGGTCACAGTCTATTATGGGGTACCTGTGTGGAAGGAAGCAACCACCACTCTATTTTGTGCATCAGATGCTAAAGCATATGATACAGAGGTACATAATGTTTGGGCCACACATGCCTGTGTACCCACAGACCCCAACCCACAAGAAGTAGTATTGGTAAATGTGACAGAAAATTTTAACATGTGGAAAAATGACATGGTAGAACAGATGCATGAGGATATAATCAGTTTATGGGATCAAAGCCTAAAGCCATGTGTAAAATTAACCCCACTCTGTGTTAGTTTAAAGTGCACTGATTTGAAGAATGATACTAATACCAATAGTAGTAGCGGGAGAATGATAATGGAGAAAGGAGAGATAAAAAACTGCTCTTTCAATATCAGCACAAGCATAAGAGGTAAGGTGCAGAAAGAATATGCATTTTTTTATAAACTTGATATAATACCAATAGATAATGATACTACCAGCTATAAGTTGACAAGTTGTAACACCTCAGTCATTACACAGGCCTGTCCAAAGGTATCCTTTGAGCCAATTCCCATACATTATTGTGCCCCGGCTGGTTTTGCGATTCTAAAATGTAATAATAAGACGTTCAATGGAACAGGACCATGTACAAATGTCAGCACAGTACAATGTACACATGGAATTAGGCCAGTAGTATCAACTCAACTGCTGTTAAATGGCAGTCTAGCAGAAGAAGAGGTAGTAATTAGATCTGTCAATTTCACGGACAATGCTAAAACCATAATAGTACAGCTGAACACATCTGTAGAAATTAATTGTACAAGACCCAACAACAATACAAGAAAAAGAATCCGTATCCAGAGAGGACCAGGGAGAGCATTTGTTACAATAGGAAAAATAGGAAATATGAGACAAGCACATTGTAACATTAGTAGAGCAAAATGGAATAACACTTTAAAACAGATAGCTAGCAAATTAAGAGAACAATTTGGAAATAATAAAACAATAATCTTTAAGCAATCCTCAGGAGGGGACCCAGAAATTGTAACGCACAGTTTTAATTGTGGAGGGGAATTTTTCTACTGTAATTCAACACAACTGTTTAATAGTACTTGGTTTAATAGTACTTGGAGTACTGAAGGGTCAAATAACACTGAAGGAAGTGACACAATCACCCTCCCATGCAGAATAAAACAAATTATAAACATGTGGCAGAAAGTAGGAAAAGCAATGTATGCCCCTCCCATCAGTGGACAAATTAGATGTTCATCAAATATTACAGGGCTGCTATTAACAAGAGATGGTGGTAATAGCAACAATGAGTCCGAGATCTTCAGACCTGGAGGAGGAGATATGAGGGACAATTGGAGAAGTGAATTATATAAATATAAAGTAGTAAAAATTGAACCATTAGGAGTAGCACCCACCAAGGCAAAGAGAAGAGTGGTGCAGAGAGAAAAAAGAGCAGTGGGAATAGGAGCTTTGTTCCTTGGGTTCTTGGGAGCAGCAGGAAGCACTATGGGCGCAGCGTCAATGACGCTGACGGTACAGGCCAGACAATTATTGTCTGGTATAGTGCAGCAGCAGAACAATTTGCTGAGGGCTATTGAGGCGCAACAGCATCTGTTGCAACTCACAGTCTGGGGCATCAAGCAGCTCCAGGCAAGAATCCTGGCTGTGGAAAGATACCTAAAGGATCAACAGCTCCTGGGGATTTGGGGTTGCTCTGGAAAACTCATTTGCACCACTGCTGTGCCTTGGAATGCTAGTTGGAGTAATAAATCTCTGGAACAGATTTGGAATCACACGACCTGGATGGAGTGGGACAGAGAAATTAACAATTACACAAGCTTAATACACTCCTTAATTGAAGAATCGCAAAACCAGCAAGAAAAGAATGAACAAGAATTATTGGAATTAGATAAATGGGCAAGTTTGTGGAATTGGTTTAACATAACAAATTGGCTGTGGTATATAAAATTATTCATAATGATAGTAGGAGGCTTGGTAGGTTTAAGAATAGTTTTTGCTGTACTTTCTATAGTGAATAGAGTTAGGCAGGGATATTCACCATTATCGTTTCAGACCCACCTCCCAACCCCGAGGGGACCCGACAGGCCCGAAGGAATAGAAGAAGAAGGTGGAGAGAGAGACAGAGACAGATCCATTCGATTAGTGAACGGATCCTTGGCACTTATCTGGGACGATCTGCGGAGCCTGTGCCTCTTCAGCTACCACCGCTTGAGAGACTTACTCTTGATTGTAACGAGGATTGTGGAACTTCTGGGACGCAGGGGGTGGGAAGCCCTCAAATATTGGTGGAATCTCCTACAGTATTGGAGTCAGGAACTAAAGAATAGTGCTGTTAGCTTGCTCAATGCCACAGCCATAGCAGTAGCTGAGGGGACAGATAGGGTTATAGAAGTAGTACAAGGAGCTTGTAGAGCTATTCGCCACATACCTAGAAGAATAAGACAGGGCTTGGAAAGGATTTTGCTATAAGATGGGTGGCAAGTGGTCAAAAAGTAGTGTGATTGGATGGCCTACTGTAAGGGAAAGAATGAGACGAGCTGAGCCAGCAGCAGATAGGGTGGGAGCAGCATCTCGAGACCTGGAAAAACATGGAGCAATCACAAGTAGCAATACAGCAGCTACCAATGCTGCTTGTGCCTGGCTAGAAGCACAAGAGGAGGAGGAGGTGGGTTTTCCAGTCACACCTCAGGTACCTTTAAGACCAATGACTTACAAGGCAGCTGTAGATCTTAGCCACTTTTTAAAAGAAAAGGGGGGACTGGAAGGGCTAATTCACTCCCAAAGAAGACAAGATATCCTTGATCTGTGGATCTACCACACACAAGGCTACTTCCCTGATTAGCAGAACTACACACCAGGGCCAGGGGTCAGATATCCACTGACCTTTGGATGGTGCTACAAGCTAGTACCAGTTGAGCCAGATAAGGTAGAAGAGGCCAATAAAGGAGAGAACACCAGCTTGTTACACCCTGTGAGCCTGCATGGGATGGATGACCCGGAGAGAGAAGTGTTAGAGTGGAGGTTTGACAGCCGCCTAGCATTTCATCACGTGGCCCGAGAGCTGCATCCGGAGTACTTCAAGAACTGCTGATATCGAGCTTGCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGCGTGGCCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATCCTGCATATAAGCAGCTGCTTTTTGCCTGTACTGGGTCTCTCTGGTTAGACCAGATCTGAGCCTGGGAGCTCTCTGGCTAACTAGGGAACCCACTGCTTAAGCCTCAATAAAGCTTGCCTTGAGTGCTTCAAGTAGTGTGTGCCCGTCTGTTGTGTGACTCTGGTAACTAGAGATCCCTCAGACCCTTTTAGTCAGTGTGGAAAATCTCTAGCA
3 | >JRCSF
4 | AGGGCTAATTTACTCACAGAAAAGACAAGATATCCTTGATCTGTGGATCTACCACACACAAGGCTTCTTCCCTGATTGGCAGAACTACACAGCAGGACCAGGGGTCAGATTTCCACTGACCTTTGGATGGTGCTTCAAGCTAGTACCAGTTGATCCAGAGAAGGTAGAAGAGGCCAATGAAGGAGAGAACAACTGCTTGTTACACCCTATGAGCCAGCATGGAATGGACGACCCAGAGAAGGAAGTGTTAGTGTGGAAGTTTGACAGCAAGCTAGCATTGCATCACGTGGCCCGAGAGCTGCATCCGGAGTACTACAAGGACTGCTGACACCGAGCTTTCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGCGTGGCCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATGCTGCATATAAGCAGCTGCTTTTTGCCTGTACTGGGTCTCTCTGGTTAGACCAGATCTGAGCCTGGGAGCTCTCTGGCTAGCTAGGGAACCCACTGCTTAAGCCTCAATAAAGCTTGCCTTGAGTGCTTCAAGTAGTGTGTGCCCGTCTGTTGTGTGACTCTGGTAACTAGAGATCCCTCAGACCCTTTTAGTCAGTGTGGAAAATCTCTAGCAGTGGCGCCCGAACAGGGACCGGAAAGCGAAAGAGAAACCAGAGGAGATCTCTCGACGCAGGACTCGGCTTGCTGAAGCGCGCACAGCAAGAGGCGAGGGGCGGCGACTGGTGAGTACGCCGAAATTTTGACTAGCGGAGGCTAGAAGGAGAGAGATGGGTGCGAGAGCGTCAGTATTAAGCGGGGGAGAATTGGATAGGTGGGAAAAAATTCGGTTAAGGCCAGGAGGAAAGAAAAAATATAGATTAAAACATATAGTATGGGCAAGCAGGGAGCTAGAACGTTTCGCAGTCAATCCTGGCCTGTTAGAATCATCAGAAGGCTGTAGACAAATACTGGGACAACTACAACCATCCCTTAAGACAGGATCAGAAGAACTTACATCATTATATAATACAGTAGCAACCCTCTATTGTGTACATCAAAGGATAGAGATAAAAGACACCAAGGAAGCTTTAGAAAAGATAGAGGAAGAGCAAACCAAAAGTATGAAAAAGGCACAGCAAGCAGCAGCTGACACAGGAAACAGCAGCCAGGTCAGCCAAAATTACCCTATAGTGCAGAACCTGCAGGGGCAAATGGTACATCAGGCCATATCACCTAGAACTTTAAATGCATGGGTAAAAGTAATAGAAGAGAAGGCTTTCAGCCCCGAAGTAATACCCATGTTTTCAGCATTATCAGAAGGAGCCACCCCACAAGATTTAAACACCATGCTAAACACAGTGGGGGGACATCAAGCAGCTATGCAAATGCTAAAAGAAACCATCAATGAGGAAGCTGCAGAATGGGATAGATTGCATCCAGTGCATGCAGGGCCTATTGCACCAGGCCAGATGAGAGAACCAAGGGGAAGTGACATAGCAGGGACTACTAGTACCCTTCAGGAACAAATAGGATGGATGACAAATAATCCACCTATCCCAGTAGGAGAAATCTATAAAAGATGGATAATCCTGGGGTTAAATAAAATAGTAAGGATGTATAGCCCTGTCAGCATTCTGGACATAAGACAAGGACCAAAGGAACCCTTTAGAGACTATGTAGACCGGTTCTATAAAACCCTAAGAGCCGAGCAAGCTACACAGGAGGTAAAAAATTGGATGACAGAAACCTTGTTGGTCCAAAATGCGAACCCAGATTGTAAAACTATTTTAAAAGCATTGGGACCAGCAGCTACACTAGAAGAAATGATGACAGCATGTCAGGGAGTGGGAGGACCCGGCCATAAAGCAAGAGTTTTGGCTGAAGCAATGAGCCAAGTAACAAATCCAGCTACCATAATGATGCAGAGAGGCAACTTTAGGAACCAAAGAAAGAATGTTAAGTGTTTCAATTGTGGCAAAGAAGGGCACATAGCCAGAAATTGCAGGGCCCCTAGGAAAAAGGGCTGTTGGAAATGTGGAAAGGAAGGACACCAAATGAAAGAGTGTACTGAGAGACAGGCTAATTTTTTAGGGAAGATCTGGCCTTCCTACAAGGGAAGGCCAGGGAATTTCCTTCAGAGCAGACCAGAGCCAACAGCCCCACCAGAAGAGAGCTTCAGGTTTGGGGAAGAGACAGCAACTCCCTCTCAGAAGCAGGAGCAGAAGCAGGAGCCGATAGACAAGGAATTGTATCCTTTAACTTCCCTCAGATCACTCTTTGGCAACGACCCCTCGTCACAATAAAGATAGGGGGGCAACTAAAGGAAGCTCTATTAGATACAGGAGCAGATGATACAGTATTAGAAGACATGGATTTGCCAGGAAGATGGAAACCAAAAATGATAGGGGGAATTGGAGGTTTTATCAAAGTAAGACAGTATGATCAGATACCCATAGATATCTGTGGACATAAAGCTGTAGGTACAGTATTAGTAGGACCTACACCTGTCAACATAATTGGAAGAAATCTGTTGACTCAGATTGGTTGCACTTTAAATTTTCCCATTAGTCCTATTGAAACTGTACCAGTAAAATTAAAGCCAGGAATGGATGGCCCAAAAGTCAAACAATGGCCATTGACAGAAGAAAAAATAAAAGCATTAGTAGAAATTTGTACAGAAATGGAAAAGGAAGGAAAGATTTCAAAAATTGGGCCTGAAAATCCATACAATACTCCAGTATTTGCCATAAAGAAAAAAGACAGTACTAAATGGAGAAAATTAGTAGATTTCAGAGAACTTAATAGGAGAACTCAAGACTTCTGGGAAGTTCAATTAGGAATACCACATCCCGCAGGGTTAAAAAAGAAAAAATCAGTAACAGTACTGGATGTGGGTGATGCATATTTTTCAGTTCCCTTAGATAAAGACTTCAGGAAGTATACTGCATTTACCATACCTAGTATAAACAATGAGACACCAGGGATTAGATATCAGTACAATGTGCTTCCACAGGGATGGAAAGGATCACCAGCAATATTCCAAAGTAGCATGACAAAAATCTTAGAGCCTTTTAGAAAACAAAATCCAGACATAATTATCTATCAATACATGGATGATTTGTATGTAGGATCTGACTTAGAAATAGGGCAGCATAGAACAAAAATAGAGGAACTGAGACAACATCTGTTGAAGTGGGGATTTACCACACCAGACAAAAAACATCAGAAAGAACCTCCATTCCTTTGGATGGGTTATGAACTCCATCCTGATAAATGGACAGTACAGCCTATAGTGCTGCCAGAAAAAGACAGCTGGACTGTCAATGACATACAGAAGTTAGTGGGAAAATTGAATTGGGCAAGTCAAATTTATGCAGGGATTAAAGTAAAGCAATTATGTAAACTCCTTAGGGGAACCAAAGCACTTACAGAAGTAATACCACTAACAAAAGAAGCAGAGCTAGAACTGGCAGAAAACAGGGAGATTCTAAAAGAACCAGTACATGGAGTGTATTATGACCCATCAAAAGACTTAATAGTAGAAATACAGAAGCAGGGGCAAGGCCAATGGACATATCAAATTTTTCAAGAGCCATTTAAAAATCTGAAAACAGGAAAATATGCAAGAACGAGGGGTGCCCACACTAATGATGTAAAACAATTAACAGAGGCAGTGCAAAAAATAGCCAATGAAAGCATAGTAATATGGGGAAAGATTCCTAAATTTAAATTACCCATACAAAAAGAAACATGGGAAACATGGTGGACAGAGTATTGGCAAGCCACCTGGATTCCTGAGTGGGAGTTTGTCAATACCCCTCCCTTAGTGAAATTATGGTACCAGTTAGAAAAAGAACCCATAGTAGGAGCAGAAACTTTCTATGTAGATGGGGCAGCTAACAGGGAGACTAAATTAGGAAAAGCAGGATATGTTACTAGCAGAGGAAGACAAAAAGTTGTCTCCCTAACAGACACAACAAATCAGAAAACTGAGTTACAAGCAATTCACCTAGCTTTGCAGGATTCAGGATTAGAAGTAAACATAGTAACAGACTCACAATATGCATTAGGAATCATTCAAGCACAACCAGATAAAAGTGAATCAGAGTTAGTCAGTCAAATAATAGAACAGCTAATAAAAAAGGAAAAAGTCTACCTGGCATGGGTACCAGCACACAAAGGAATTGGAGGAAATGAACAGGTAGATAAATTAGTCAGTGCTGGAATCAGGAAAGTGCTATTTTTAGATGGAATAGATAAGGCCCAAGAAGATCATGAAAAATATCACAGTAATTGGAGAGCAATGGCTAGTGATTTTAACCTGCCACCTATAGTAGCAAAAGAAATAGTAGCCAGCTGTGATAAATGTCAGCTAAAAGGAGAAGCCATGCATGGACAAGTAGACTGTAGTCCAGGAATATGGCAACTAGATTGTACACATTTAGAAGGAAAAATTATCCTGGTAGCAGTTCATGTAGCCAGTGGATATATAGAAGCAGAAGTTATTCCAGCAGAAACAGGGCAGGAAACAGCATACTTTCTCTTAAAATTAGCAGGCAGATGGCCAGTAACAACAATACATACAGACAATGGCAGCAATTTCACCAGTACTACAGTTAAGGCCGCCTGTTGGTGGGCTGGGATCAAGCAGGAATTTGGCATTCCCTACAATCCCCAAAGTCAAGGAGTAGTAGAATCTATGAATAAAGAATTAAAGAAAATTATAGGACAGGTAAGAGATCAGGCTGAACATCTTAAGACAGCAGTACAAATGGCAGTATTCATCCACAATTTTAAAAGAAAAGGGGGGATTGGGGGGTACAGTGCAGGGGAAAGAATAATAGACATAATAGCAACAGACATACAAACTAAAGAATTACAAAAACAAATTACAAAAATTCAAAATTTTCGGGTTTATTACAGGGACAACAGAGATCCAATTTGGAAAGGACCAGCAAAGCTTCTCTGGAAAGGTGAAGGGGCAGTAGTAATACAAGATAATAGTGACATAAAAGTAGTGCCAAGAAGAAAAGTAAAAATCATTAGGGATTATGGAAAACAGATGGCAGGTGATGATTGTGTGGCAAGTAGACAGGATGAGGATTAGAACATGGAACAGTTTAGTAAAACACCATATGTATATTTCAGGGAAAGCTAAGGGATGGATTTATAAACATCACTATGAAAGCACTAATCCAAGAGTAAGTTCAGAAGTACAAATCCCACTAGGGGATGCTAGATTGGTAATAACAACATATTGGGGTCTGCATACAGGAGAAAGAGACTGGCATTTGGGTCAGGGAGTCTCCATGGAATGGAGGACAAGGAGATATAGCACACAAGTAGACCCTGACCTAGCAGACCAACTAATTCATCTGTATTACTTTGATTGTTTTTCAGAATCTGCTATAAGGAATGCCATATTAGGACATATAGTTAGTCCTAGATGTGAATATCAAGCAGGACATAGCAAGGTAGGATCTCTACAGTACTTGGCACTAACAGCATTAATAAAACCAAAAAAGATAAAGCCACCTTTGCCTAGTGTTAAGAAACTAACAGAGGATAGATGGAACAAGCCCCAGAAGACCAAGGGCCACAGAGGGAGCCATACAATGAATGGACACTAGAGCTTTTAGAGGAACTTAAGAATGAAGCTGTTAGACATTTTCCTAGGATCTGGCTCCATAGCTTAGGGCAATATATCTATGAAACTTATGGGGATACTTGGGCAGGAGTGGAAGCCATAATAAGAATACTGCAACAGCTGCTGTTTATTCATTTCAGAATTGGGTGTCGACATAGCAGAATAGGCATTACTCGACAGAGGAGAGCAAGAAATGGAGCCAGTAGATCCTAGCCTAGAGCCCTGGAAGCATCCAGGAAGTCAGCCTAAGACTGCTTGTACCAATTGCTATTGTAAAAAGTGTTGCCTTCATTGCCAAGTTTGTTTCACAACAAAAGGCTTAGGCATCTCCTATGGCAGGAAGAAGCGGAGACAGCGACGAAGACCTCCTCAAGACAGTCAGACTCATCAAGTTTCTCTACCAAAGCAGTAAGTAGTGCATGTAATGCAACCTTTACAAATATTAGCAATAGTAGCATTAGTAGTAGCAGGAATAATAGCAATAATTGTGTGGTCCATAGTACTCATAGAATATAGGAAAATATTAAGACAAAGAAAAATAGATAGGTTAATTGATAAAATAAGAGAGAGAGCAGAAGACAGTGGCAATGAGAGTGAAGGGGATCAGGAAGAATTATCAGCACTTGTGGAAAGGGGGCATCTTGCTCCTTGGGACATTAATGATCTGTAGTGCTGTAGAAAAGTTGTGGGTCACAGTCTATTATGGGGTACCTGTGTGGAAAGAAACAACCACCACTCTATTTTGTGCATCAGATGCTAAAGCATATGATACAGAGGTACATAATGTTTGGGCCACACATGCCTGTGTACCCACAGACCCCAACCCACAAGAAGTAGTATTGGAAAATGTAACAGAAGATTTTAACATGTGGAAAAATAACATGGTAGAACAGATGCAGGAGGATGTAATCAATTTATGGGATCAAAGCTTAAAGCCATGTGTAAAATTAACCCCACTCTGTGTTACTTTAAATTGCAAAGATGTGAATGCTACTAATACCACTAGTAGTAGTGAGGGAATGATGGAGAGAGGAGAAATAAAAAACTGCTCTTTCAATATCACCAAAAGCATAAGAGATAAGGTGCAGAAAGAATATGCTCTTTTTTATAAACTGGATGTAGTACCAATAGATAATAAGAATAATACCAAATATAGGTTAATAAGTTGTAACACCTCAGTCATTACACAAGCCTGTCCAAAGGTATCCTTTGAACCAATTCCCATACATTATTGTGCCCCGGCTGGTTTTGCGATTCTAAAGTGTAATAATAAGACATTCAATGGAAAAGGACAATGTAAAAATGTCAGCACAGTACAATGTACACATGGAATTAGGCCAGTAGTATCAACTCAACTGCTGCTAAATGGCAGTCTAGCAGAAGAAAAGGTTGTAATTAGATCTGACAATTTTACGGACAATGCTAAAACCATAATAGTACAGCTGAATGAATCTGTAAAAATTAATTGTACAAGGCCCAGCAACAATACAAGAAAAAGTATACATATAGGACCAGGGAGAGCATTTTATACAACAGGAGAAATAATAGGAGATATAAGACAAGCACATTGTAACATTAGTAGAGCACAATGGAATAACACTTTAAAACAGATAGTTGAAAAATTAAGAGAACAATTTAATAATAAAACAATAGTCTTTACTCACTCCTCAGGAGGGGATCCAGAAATTGTAATGCACAGTTTTAATTGTGGAGGGGAATTTTTCTACTGTAATTCAACACAACTGTTTAATAGTACTTGGAATGATACTGAAAAGTCAAGTGGCACTGAAGGAAATGACACCATCATACTCCCATGCAGAATAAAACAAATTATAAACATGTGGCAGGAAGTGGGAAAAGCAATGTATGCTCCTCCCATTAAAGGACAAATTAGATGTTCATCAAATATTACAGGGCTGCTATTAACAAGAGATGGTGGTAAAAATGAGAGTGAGATCGAGATCTTCAGACCTGGAGGAGGAGACATGAGGGACAATTGGAGAAGTGAATTATATAAATATAAAGTAGTAAAAATTGAACCATTAGGAGTAGCACCCACCAAGGCAAAGAGAAGAGTGGTGCAAAGAGAAAAAAGAGCAGTGGGAATAGGAGCTTTGTTCCTTGGGTTCTTGGGAGCAGCAGGAAGCACTATGGGCGCAGCGTCAATGACACTGACGGTACAGGCCAGACAATTATTGTCTGGTATAGTGCAACAGCAAAACAATTTGCTGAGGGCTATTGAGGCGCAACAGCATATGTTGCAACTCACAGTCTGGGGCATCAAGCAGCTCCAGGCAAGAGTCCTGGCTGTGGAAAGATACCTAAAGGATCAACAGCTCATGGGGATTTGGGGTTGCTCTGGAAAACTCATTTGCACCACTGCTGTGCCTTGGAATACTAGTTGGAGTAATAAATCTCTGGATAGTATTTGGAATAACATGACCTGGATGGAGTGGGAAAAAGAAATTGAGAATTACACAAACACAATATACACCCTAATTGAAGAATCGCAGATCCAACAAGAAAAGAATGAACAAGAATTATTGGAATTAGATAAATGGGCAAGTTTGTGGAATTGGTTTGACATAACAAAATGGCTGTGGTATATAAAAATATTCATAATGATAGTAGGAGGCTTGATAGGTTTAAGAATAGTTTTTTCTGTACTTTCTATAGTGAATAGAGTTAGGCAGGGATACTCACCCTTATCGTTTCAGACCCTCCTCCCAGCAACGAGGGGACCCGACAGGCCCGAAGGAATCGAAGAAGAAGGTGGAGAGAGAGACAGAGACAGATCCGGACAATTAGTGAACGGATTCTTAGCACTTATCTGGGTCGACCTGCGGAGCCTGTTCCTCTTCAGCTACCACCGCTTGAGAGACTTACTCTTGACTGTAACGAGGATTGTGGAACTTCTGGGACGCAGGGGGTGGGAAATCCTGAAATACTGGTGGAATCTCCTACAGTATTGGAGTCAGGAACTAAAGAATAGTGCTGTTAGCTTGCTTAATGCCACAGCTATAGCAGTAGCTGAGGGGACAGATAGGATTATAGAAGTAGTACAAAGAGTTTATAGGGCTATTCTCCACATACCTACAAGAATAAGACAGGGCTTGGAAAGGGCTTTGCTATAAGATGGGTGGCAAGTGGTCAAAACATAGTGTGCCTGGATGGTCTACTGTAAGGGAAAGAATGAGACGAGCTGAGCCAGCAACAGATAGGGTGAGACAAACTGAGCCAGCAGCAGTAGGGGTGGGAGCAGTATCTCGAGACCTGGAAAAACATGGAGCAATCACAAGTAGCAATACAGCAGCTACCAATGCTGATTGTGCCTGGCTAGAAGCATATGAGGATGAGGAAGTGGGTTTTCCAGTCAGACCTCAGGTACCTTTAAGACCAATGACTTACAAGGCAGCTATAGATCTTAGCCACTTTTTAAAAGAAAAGGGGGGACTGGAAGGGCTAATTTACTCACAGAAAAGACAAGATATCCTTGATCTGTGGATCTACCACACACAAGGCTACTTCCCTGATTGGCAGAACTACACAGCAGGACCAGGGGTCAGATTTCCACTGACCTTTGGATGGTGCTTCAAGCTAGTACCAGTTGATCCAGAGAAGGTAGAAGAGGCCAATGAAGGAGAGAACAACTGCTTGTTACACCCTATGAGCCAGCATGGAATGGACGACCCAGAGAAGGAAGTGTTAGTGTGGAAGTTTGACAGCAAGCTAGCATTGCATCACGTGGCCCGAGAGCTGCATCCGGAGTACTACAAGGACTGCTGACACCGAGCTTTCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGCGTGGCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATGCTGCATATAAGCAGCTGC
5 | >NL43
6 | TGGAAGGGCTAATTTACTCCCAAAAAAGACAAGAGATCCTTGATCTGTGGATCTACCACACACAAGGCTACTTCCCTGATTGGCAGAACTACACACCAGGGCCAGGGGTCAGATATCCACTGACCTTTGGATGGTGCTTCAAGCTAGTACCAGTTGAGCCAGAGCAAGTAGAAGAGGCCAATGAAGGAGAGAACAACAGCTTGTTACACCCTATGAGCCAGCATGGGATGGATGACCCTGAGGGAGAAGTATTAGTGTGGAAGTTTGACAGCCTCCTAGCATTTCATCACATGGCCCGAGAGCTGCATCCGGAGTACTACAAAGACTGCTGACATCGAGCTTTCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGTGTGGCCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATGCTACATATAAGCAGCTGCTTTTTGCCTGTACTGGGTCTCTCTGGTTAGACCAGATCTGAGCCTGGGAGCTCTCTGGCTAACTAGGGAACCCACTGCTTAAGCCTCAATAAAGCTTGCCTTGAGTGCTCAAAGTAGTGTGTGCCCGTCTGTTGTGTGACTCTGGTAACTAGAGATCCCTCAGACCCTTTTAGTCAGTGTGGAAAATCTCTAGCAGTGGCGCCCGAACAGGGACTTGAAAGCGAAAGTAAAGCCAGAGGAGATCTCTCGACGCAGGACTCGGCTTGCTGAAGCGCGCACGGCAAGAGGCGAGGGGCGGCGACTGGTGAGTACGCCAAAAATTTTGACTAGCGGAGGCTAGAAGGAGAGAGATGGGTGCGAGAGCGTCGGTATTAAGCGGGGGAGAATTAGATAAATGGGAAAAAATTCGGTTAAGGCCAGGGGGAAAGAAACAATATAAACTAAAACATATAGTATGGGCAAGCAGGGAGCTAGAACGATTCGCAGTTAATCCTGGCCTTTTAGAGACATCAGAAGGCTGTAGACAAATACTGGGACAGCTACAACCATCCCTTCAGACAGGATCAGAAGAACTTAGATCATTATATAATACAATAGCAGTCCTCTATTGTGTGCATCAAAGGATAGATGTAAAAGACACCAAGGAAGCCTTAGATAAGATAGAGGAAGAGCAAAACAAAAGTAAGAAAAAGGCACAGCAAGCAGCAGCTGACACAGGAAACAACAGCCAGGTCAGCCAAAATTACCCTATAGTGCAGAACCTCCAGGGGCAAATGGTACATCAGGCCATATCACCTAGAACTTTAAATGCATGGGTAAAAGTAGTAGAAGAGAAGGCTTTCAGCCCAGAAGTAATACCCATGTTTTCAGCATTATCAGAAGGAGCCACCCCACAAGATTTAAATACCATGCTAAACACAGTGGGGGGACATCAAGCAGCCATGCAAATGTTAAAAGAGACCATCAATGAGGAAGCTGCAGAATGGGATAGATTGCATCCAGTGCATGCAGGGCCTATTGCACCAGGCCAGATGAGAGAACCAAGGGGAAGTGACATAGCAGGAACTACTAGTACCCTTCAGGAACAAATAGGATGGATGACACATAATCCACCTATCCCAGTAGGAGAAATCTATAAAAGATGGATAATCCTGGGATTAAATAAAATAGTAAGAATGTATAGCCCTACCAGCATTCTGGACATAAGACAAGGACCAAAGGAACCCTTTAGAGACTATGTAGACCGATTCTATAAAACTCTAAGAGCCGAGCAAGCTTCACAAGAGGTAAAAAATTGGATGACAGAAACCTTGTTGGTCCAAAATGCGAACCCAGATTGTAAGACTATTTTAAAAGCATTGGGACCAGGAGCGACACTAGAAGAAATGATGACAGCATGTCAGGGAGTGGGGGGACCCGGCCATAAAGCAAGAGTTTTGGCTGAAGCAATGAGCCAAGTAACAAATCCAGCTACCATAATGATACAGAAAGGCAATTTTAGGAACCAAAGAAAGACTGTTAAGTGTTTCAATTGTGGCAAAGAAGGGCACATAGCCAAAAATTGCAGGGCCCCTAGGAAAAAGGGCTGTTGGAAATGTGGAAAGGAAGGACACCAAATGAAAGATTGTACTGAGAGACAGGCTAATTTTTTAGGGAAGATCTGGCCTTCCCACAAGGGAAGGCCAGGGAATTTTCTTCAGAGCAGACCAGAGCCAACAGCCCCACCAGAAGAGAGCTTCAGGTTTGGGGAAGAGACAACAACTCCCTCTCAGAAGCAGGAGCCGATAGACAAGGAACTGTATCCTTTAGCTTCCCTCAGATCACTCTTTGGCAGCGACCCCTCGTCACAATAAAGATAGGGGGGCAATTAAAGGAAGCTCTATTAGATACAGGAGCAGATGATACAGTATTAGAAGAAATGAATTTGCCAGGAAGATGGAAACCAAAAATGATAGGGGGAATTGGAGGTTTTATCAAAGTAAGACAGTATGATCAGATACTCATAGAAATCTGCGGACATAAAGCTATAGGTACAGTATTAGTAGGACCTACACCTGTCAACATAATTGGAAGAAATCTGTTGACTCAGATTGGCTGCACTTTAAATTTTCCCATTAGTCCTATTGAGACTGTACCAGTAAAATTAAAGCCAGGAATGGATGGCCCAAAAGTTAAACAATGGCCATTGACAGAAGAAAAAATAAAAGCATTAGTAGAAATTTGTACAGAAATGGAAAAGGAAGGAAAAATTTCAAAAATTGGGCCTGAAAATCCATACAATACTCCAGTATTTGCCATAAAGAAAAAAGACAGTACTAAATGGAGAAAATTAGTAGATTTCAGAGAACTTAATAAGAGAACTCAAGATTTCTGGGAAGTTCAATTAGGAATACCACATCCTGCAGGGTTAAAACAGAAAAAATCAGTAACAGTACTGGATGTGGGCGATGCATATTTTTCAGTTCCCTTAGATAAAGACTTCAGGAAGTATACTGCATTTACCATACCTAGTATAAACAATGAGACACCAGGGATTAGATATCAGTACAATGTGCTTCCACAGGGATGGAAAGGATCACCAGCAATATTCCAGTGTAGCATGACAAAAATCTTAGAGCCTTTTAGAAAACAAAATCCAGACATAGTTATCTATCAATACATGGATGATTTGTATGTAGGATCTGACTTAGAAATAGGGCAGCATAGAACAAAAATAGAGGAACTGAGACAACATCTGTTGAGGTGGGGATTTACCACACCAGACAAAAAACATCAGAAAGAACCTCCATTCCTTTGGATGGGTTATGAACTCCATCCTGATAAATGGACAGTACAGCCTATAGTGCTGCCAGAAAAGGACAGCTGGACTGTCAATGACATACAGAAATTAGTGGGAAAATTGAATTGGGCAAGTCAGATTTATGCAGGGATTAAAGTAAGGCAATTATGTAAACTTCTTAGGGGAACCAAAGCACTAACAGAAGTAGTACCACTAACAGAAGAAGCAGAGCTAGAACTGGCAGAAAACAGGGAGATTCTAAAAGAACCGGTACATGGAGTGTATTATGACCCATCAAAAGACTTAATAGCAGAAATACAGAAGCAGGGGCAAGGCCAATGGACATATCAAATTTATCAAGAGCCATTTAAAAATCTGAAAACAGGAAAGTATGCAAGAATGAAGGGTGCCCACACTAATGATGTGAAACAATTAACAGAGGCAGTACAAAAAATAGCCACAGAAAGCATAGTAATATGGGGAAAGACTCCTAAATTTAAATTACCCATACAAAAGGAAACATGGGAAGCATGGTGGACAGAGTATTGGCAAGCCACCTGGATTCCTGAGTGGGAGTTTGTCAATACCCCTCCCTTAGTGAAGTTATGGTACCAGTTAGAGAAAGAACCCATAATAGGAGCAGAAACTTTCTATGTAGATGGGGCAGCCAATAGGGAAACTAAATTAGGAAAAGCAGGATATGTAACTGACAGAGGAAGACAAAAAGTTGTCCCCCTAACGGACACAACAAATCAGAAGACTGAGTTACAAGCAATTCATCTAGCTTTGCAGGATTCGGGATTAGAAGTAAACATAGTGACAGACTCACAATATGCATTGGGAATCATTCAAGCACAACCAGATAAGAGTGAATCAGAGTTAGTCAGTCAAATAATAGAGCAGTTAATAAAAAAGGAAAAAGTCTACCTGGCATGGGTACCAGCACACAAAGGAATTGGAGGAAATGAACAAGTAGATAAATTGGTCAGTGCTGGAATCAGGAAAGTACTATTTTTAGATGGAATAGATAAGGCCCAAGAAGAACATGAGAAATATCACAGTAATTGGAGAGCAATGGCTAGTGATTTTAACCTACCACCTGTAGTAGCAAAAGAAATAGTAGCCAGCTGTGATAAATGTCAGCTAAAAGGGGAAGCCATGCATGGACAAGTAGACTGTAGCCCAGGAATATGGCAGCTAGATTGTACACATTTAGAAGGAAAAGTTATCTTGGTAGCAGTTCATGTAGCCAGTGGATATATAGAAGCAGAAGTAATTCCAGCAGAGACAGGGCAAGAAACAGCATACTTCCTCTTAAAATTAGCAGGAAGATGGCCAGTAAAAACAGTACATACAGACAATGGCAGCAATTTCACCAGTACTACAGTTAAGGCCGCCTGTTGGTGGGCGGGGATCAAGCAGGAATTTGGCATTCCCTACAATCCCCAAAGTCAAGGAGTAATAGAATCTATGAATAAAGAATTAAAGAAAATTATAGGACAGGTAAGAGATCAGGCTGAACATCTTAAGACAGCAGTACAAATGGCAGTATTCATCCACAATTTTAAAAGAAAAGGGGGGATTGGGGGGTACAGTGCAGGGGAAAGAATAGTAGACATAATAGCAACAGACATACAAACTAAAGAATTACAAAAACAAATTACAAAAATTCAAAATTTTCGGGTTTATTACAGGGACAGCAGAGATCCAGTTTGGAAAGGACCAGCAAAGCTCCTCTGGAAAGGTGAAGGGGCAGTAGTAATACAAGATAATAGTGACATAAAAGTAGTGCCAAGAAGAAAAGCAAAGATCATCAGGGATTATGGAAAACAGATGGCAGGTGATGATTGTGTGGCAAGTAGACAGGATGAGGATTAACACATGGAAAAGATTAGTAAAACACCATATGTATATTTCAAGGAAAGCTAAGGACTGGTTTTATAGACATCACTATGAAAGTACTAATCCAAAAATAAGTTCAGAAGTACACATCCCACTAGGGGATGCTAAATTAGTAATAACAACATATTGGGGTCTGCATACAGGAGAAAGAGACTGGCATTTGGGTCAGGGAGTCTCCATAGAATGGAGGAAAAAGAGATATAGCACACAAGTAGACCCTGACCTAGCAGACCAACTAATTCATCTGCACTATTTTGATTGTTTTTCAGAATCTGCTATAAGAAATACCATATTAGGACGTATAGTTAGTCCTAGGTGTGAATATCAAGCAGGACATAACAAGGTAGGATCTCTACAGTACTTGGCACTAGCAGCATTAATAAAACCAAAACAGATAAAGCCACCTTTGCCTAGTGTTAGGAAACTGACAGAGGACAGATGGAACAAGCCCCAGAAGACCAAGGGCCACAGAGGGAGCCATACAATGAATGGACACTAGAGCTTTTAGAGGAACTTAAGAGTGAAGCTGTTAGACATTTTCCTAGGATATGGCTCCATAACTTAGGACAACATATCTATGAAACTTACGGGGATACTTGGGCAGGAGTGGAAGCCATAATAAGAATTCTGCAACAACTGCTGTTTATCCATTTCAGAATTGGGTGTCGACATAGCAGAATAGGCGTTACTCGACAGAGGAGAGCAAGAAATGGAGCCAGTAGATCCTAGACTAGAGCCCTGGAAGCATCCAGGAAGTCAGCCTAAAACTGCTTGTACCAATTGCTATTGTAAAAAGTGTTGCTTTCATTGCCAAGTTTGTTTCATGACAAAAGCCTTAGGCATCTCCTATGGCAGGAAGAAGCGGAGACAGCGACGAAGAGCTCATCAGAACAGTCAGACTCATCAAGCTTCTCTATCAAAGCAGTAAGTAGTACATGTAATGCAACCTATAATAGTAGCAATAGTAGCATTAGTAGTAGCAATAATAATAGCAATAGTTGTGTGGTCCATAGTAATCATAGAATATAGGAAAATATTAAGACAAAGAAAAATAGACAGGTTAATTGATAGACTAATAGAAAGAGCAGAAGACAGTGGCAATGAGAGTGAAGGAGAAGTATCAGCACTTGTGGAGATGGGGGTGGAAATGGGGCACCATGCTCCTTGGGATATTGATGATCTGTAGTGCTACAGAAAAATTGTGGGTCACAGTCTATTATGGGGTACCTGTGTGGAAGGAAGCAACCACCACTCTATTTTGTGCATCAGATGCTAAAGCATATGATACAGAGGTACATAATGTTTGGGCCACACATGCCTGTGTACCCACAGACCCCAACCCACAAGAAGTAGTATTGGTAAATGTGACAGAAAATTTTAACATGTGGAAAAATGACATGGTAGAACAGATGCATGAGGATATAATCAGTTTATGGGATCAAAGCCTAAAGCCATGTGTAAAATTAACCCCACTCTGTGTTAGTTTAAAGTGCACTGATTTGAAGAATGATACTAATACCAATAGTAGTAGCGGGAGAATGATAATGGAGAAAGGAGAGATAAAAAACTGCTCTTTCAATATCAGCACAAGCATAAGAGATAAGGTGCAGAAAGAATATGCATTCTTTTATAAACTTGATATAGTACCAATAGATAATACCAGCTATAGGTTGATAAGTTGTAACACCTCAGTCATTACACAGGCCTGTCCAAAGGTATCCTTTGAGCCAATTCCCATACATTATTGTGCCCCGGCTGGTTTTGCGATTCTAAAATGTAATAATAAGACGTTCAATGGAACAGGACCATGTACAAATGTCAGCACAGTACAATGTACACATGGAATCAGGCCAGTAGTATCAACTCAACTGCTGTTAAATGGCAGTCTAGCAGAAGAAGATGTAGTAATTAGATCTGCCAATTTCACAGACAATGCTAAAACCATAATAGTACAGCTGAACACATCTGTAGAAATTAATTGTACAAGACCCAACAACAATACAAGAAAAAGTATCCGTATCCAGAGGGGACCAGGGAGAGCATTTGTTACAATAGGAAAAATAGGAAATATGAGACAAGCACATTGTAACATTAGTAGAGCAAAATGGAATGCCACTTTAAAACAGATAGCTAGCAAATTAAGAGAACAATTTGGAAATAATAAAACAATAATCTTTAAGCAATCCTCAGGAGGGGACCCAGAAATTGTAACGCACAGTTTTAATTGTGGAGGGGAATTTTTCTACTGTAATTCAACACAACTGTTTAATAGTACTTGGTTTAATAGTACTTGGAGTACTGAAGGGTCAAATAACACTGAAGGAAGTGACACAATCACACTCCCATGCAGAATAAAACAATTTATAAACATGTGGCAGGAAGTAGGAAAAGCAATGTATGCCCCTCCCATCAGTGGACAAATTAGATGTTCATCAAATATTACTGGGCTGCTATTAACAAGAGATGGTGGTAATAACAACAATGGGTCCGAGATCTTCAGACCTGGAGGAGGCGATATGAGGGACAATTGGAGAAGTGAATTATATAAATATAAAGTAGTAAAAATTGAACCATTAGGAGTAGCACCCACCAAGGCAAAGAGAAGAGTGGTGCAGAGAGAAAAAAGAGCAGTGGGAATAGGAGCTTTGTTCCTTGGGTTCTTGGGAGCAGCAGGAAGCACTATGGGCGCAGCGTCAATGACGCTGACGGTACAGGCCAGACAATTATTGTCTGATATAGTGCAGCAGCAGAACAATTTGCTGAGGGCTATTGAGGCGCAACAGCATCTGTTGCAACTCACAGTCTGGGGCATCAAACAGCTCCAGGCAAGAATCCTGGCTGTGGAAAGATACCTAAAGGATCAACAGCTCCTGGGGATTTGGGGTTGCTCTGGAAAACTCATTTGCACCACTGCTGTGCCTTGGAATGCTAGTTGGAGTAATAAATCTCTGGAACAGATTTGGAATAACATGACCTGGATGGAGTGGGACAGAGAAATTAACAATTACACAAGCTTAATACACTCCTTAATTGAAGAATCGCAAAACCAGCAAGAAAAGAATGAACAAGAATTATTGGAATTAGATAAATGGGCAAGTTTGTGGAATTGGTTTAACATAACAAATTGGCTGTGGTATATAAAATTATTCATAATGATAGTAGGAGGCTTGGTAGGTTTAAGAATAGTTTTTGCTGTACTTTCTATAGTGAATAGAGTTAGGCAGGGATATTCACCATTATCGTTTCAGACCCACCTCCCAATCCCGAGGGGACCCGACAGGCCCGAAGGAATAGAAGAAGAAGGTGGAGAGAGAGACAGAGACAGATCCATTCGATTAGTGAACGGATCCTTAGCACTTATCTGGGACGATCTGCGGAGCCTGTGCCTCTTCAGCTACCACCGCTTGAGAGACTTACTCTTGATTGTAACGAGGATTGTGGAACTTCTGGGACGCAGGGGGTGGGAAGCCCTCAAATATTGGTGGAATCTCCTACAGTATTGGAGTCAGGAACTAAAGAATAGTGCTGTTAACTTGCTCAATGCCACAGCCATAGCAGTAGCTGAGGGGACAGATAGGGTTATAGAAGTATTACAAGCAGCTTATAGAGCTATTCGCCACATACCTAGAAGAATAAGACAGGGCTTGGAAAGGATTTTGCTATAAGATGGGTGGCAAGTGGTCAAAAAGTAGTGTGATTGGATGGCCTGCTGTAAGGGAAAGAATGAGACGAGCTGAGCCAGCAGCAGATGGGGTGGGAGCAGTATCTCGAGACCTAGAAAAACATGGAGCAATCACAAGTAGCAATACAGCAGCTAACAATGCTGCTTGTGCCTGGCTAGAAGCACAAGAGGAGGAAGAGGTGGGTTTTCCAGTCACACCTCAGGTACCTTTAAGACCAATGACTTACAAGGCAGCTGTAGATCTTAGCCACTTTTTAAAAGAAAAGGGGGGACTGGAAGGGCTAATTCACTCCCAAAGAAGACAAGATATCCTTGATCTGTGGATCTACCACACACAAGGCTACTTCCCTGATTGGCAGAACTACACACCAGGGCCAGGGGTCAGATATCCACTGACCTTTGGATGGTGCTACAAGCTAGTACCAGTTGAGCCAGATAAGGTAGAAGAGGCCAATAAAGGAGAGAACACCAGCTTGTTACACCCTGTGAGCCTGCATGGAATGGATGACCCTGAGAGAGAAGTGTTAGAGTGGAGGTTTGACAGCCGCCTAGCATTTCATCACGTGGCCCGAGAGCTGCATCCGGAGTACTTCAAGAACTGCTGACATCGAGCTTGCTACAAGGGACTTTCCGCTGGGGACTTTCCAGGGAGGCGTGGCCTGGGCGGGACTGGGGAGTGGCGAGCCCTCAGATGCTGCATATAAGCAGCTGCTTTTTGCCTGTACTGGGTCTCTCTGGTTAGACCAGATCTGAGCCTGGGAGCTCTCTGGCTAACTAGGGAACCCACTGCTTAAGCCTCAATAAAGCTTGCCTTGAGTGCTCAAAGTAGTGTGTGCCCGTCTGTTGTGTGACTCTGGTAACTAGAGATCCCTCAGACCCTTTTAGTCAGTGTGGAAAATCTCTAGCA
7 |
--------------------------------------------------------------------------------
/reproduce.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | ######### Run strainline #########
5 |
6 | srcpath=/root/capsule/code/src
7 | threads=16
8 |
9 | # small example dataset
10 | echo "Running the example dataset..."
11 | input=/root/capsule/data/example/reads.fa
12 | $srcpath/strainline.sh -i $input -o out -p pb -k 20 -t $threads
13 |
14 |
15 | ## Note: Running the following codes on 'Code Ocean' may be time-consuming because of limited computational resources ##
16 | ## For all datasets, we provide the final output haplotyps in 'result/' ##
17 |
18 | if false
19 | then
20 | # simulated data, pacbio clr, 5-HIV
21 | input=/root/capsule/data/simulated/clr/5-HIV/reads.fa.gz
22 | $srcpath/strainline.sh -i $input -o out -p pb -k 50 --maxGD 0.02 --maxLD 0.01 --maxOH 50 -t $threads
23 |
24 | ## For other different sequencing coverage data (500x,1000x,2000x,5000x,10000x)
25 | # input=/root/capsule/data/simulated/clr/5-HIV/diff_coverage/*/reads.fa.gz
26 | # $srcpath/strainline.sh -i $input -o out -p pb -k 50 --maxGD 0.01 --maxLD 0.01 --maxOH 50 -t $threads
27 |
28 | # simulated data, pacbio clr, 6-polio
29 | input=/root/capsule/data/simulated/clr/6-polio/reads.fa.gz
30 | $srcpath/strainline.sh -i $input -o out -p pb -k 100 --minIdentity 0.995 -t $threads
31 |
32 | # simulated data, pacbio clr, 10-HCV
33 | input=/root/capsule/data/simulated/clr/10-HCV/reads.fa.gz
34 | $srcpath/strainline.sh -i $input -o out -p pb -k 100 --maxGD 0.02 --maxOH 50 -t $threads
35 |
36 | # simulated data, pacbio clr, 15-ZIKV
37 | input=/root/capsule/data/simulated/clr/15-ZIKV/reads.fa.gz
38 | $srcpath/strainline.sh -i $input -o out -p pb -k 500 --minIdentity 0.995 --maxGD 0.005 --minAbun 0.01 -t $threads
39 |
40 | # simulated data, pacbio clr, 5-SARSCov2
41 | input=/root/capsule/data/simulated/clr/5-SARSCov2/reads.fa.gz
42 | $srcpath/strainline.sh -i $input -o out -p pb -k 100 --maxLD 0.01 --minAbun 0.085 --iter 3 -t $threads
43 |
44 |
45 |
46 |
47 | # simulated data, ont, 5-HIV
48 | input=/root/capsule/data/simulated/ont/5-HIV/reads.fa.gz
49 | $srcpath/strainline.sh -i $input -o out -p ont -k 20 --maxGD 0.02 --maxLD 0.01 --maxOH 50 -t $threads
50 |
51 | # simulated data, ont , 6-polio
52 | input=/root/capsule/data/simulated/ont/6-polio/reads.fa.gz
53 | $srcpath/strainline.sh -i $input -o out -p ont -k 100 --maxOH 50 --maxLD 0.01 -t $threads
54 |
55 | # simulated data, ont , 10-HCV
56 | input=/root/capsule/data/simulated/ont/10-HCV/reads.fa.gz
57 | $srcpath/strainline.sh -i $input -o out -p ont -k 100 --maxGD 0.02 --maxLD 0.01 --maxOH 50 -t $threads
58 |
59 | # simulated data, ont , 15-ZIKV
60 | input=/root/capsule/data/simulated/ont/15-ZIKV/reads.fa.gz
61 | $srcpath/strainline.sh -i $input -o out -p ont -k 100 --minIdentity 0.995 --minAbun 0.01 -t $threads
62 |
63 | # simulated data, ont , 5-SARSCov2
64 | input=/root/capsule/data/simulated/ont/5-SARSCov2/reads.fa.gz
65 | $srcpath/strainline.sh -i $input -o out -p ont -k 100 --maxLD 0.01 --minAbun 0.085 -t $threads
66 |
67 |
68 |
69 | # real data, ont, 5-PVY
70 | input=/root/capsule/data/real/5-PVY/reads.fa.gz
71 | $srcpath/strainline.sh -i $input -o out -p ont -k 100 --maxGD 0.02 --maxLD 0.01 --minOvlpLen 400 --minSeedLen 2000 --minAbun 0.03 --maxOH 20 -t $threads
72 |
73 | # real data, ont, SARSCov2 [SRA:SRP250446]
74 | input=/root/capsule/data/real/SARSCov2/SRP250446/reads.fa.gz
75 | $srcpath/strainline.sh -i $input -o out -p ont -k 50 --rmMisassembly True --minAbun 0.05 --minIdentity 0.98 --maxLD 0.01 -t $threads
76 |
77 | fi
78 |
79 |
80 |
81 | ######### Run other tools #########
82 |
83 | ## Run canu --version, Canu snapshot (), installed on Nov4,2019 via conda ##
84 | ## use parameters recommended for metagenome assembly ##
85 | ## For PacBio CLR
86 | # canu -p out -d out genomeSize=GENOMESIZE minReadLength=500 minOverlapLength=200 corOutCoverage=10000 corMhapSensitivity=high corMinCoverage=0 redMemory=32 oeaMemory=32 batMemory=200 -pacbio-raw reads.fa
87 | ## For ONT
88 | # canu -p out -d out genomeSize=GENOMESIZE minReadLength=500 minOverlapLength=200 corOutCoverage=10000 corMhapSensitivity=high corMinCoverage=0 redMemory=32 oeaMemory=32 batMemory=200 -nanopore-raw reads.fa
89 |
90 | ## Run wtdbg2 Version: 0.0 (19830203) ##
91 | # wtdbg2 -x rs -g GENOMESIZE -t 8 -i $fq -fo out
92 | # wtpoa-cns -t 8 -i out.ctg.lay.gz -fo out.ctg.fa
93 |
94 | echo The output assemblies of simulated datasets are located here:
95 | ls /root/capsule/data/uploadedResults/simulated/*/*/haplotypes.*.fa
96 | echo
97 | echo the output assemblies of real datasets are located here:
98 | ls /root/capsule/data/uploadedResults/real/*/haplotypes.*.fa
99 | echo
100 | echo The output assemblies of simulated datasets[5-HIV, various sequencing coverages] are located here:
101 | ls /root/capsule/data/uploadedResults/simulated/*/5-HIV/*/haplotypes.*.fa
102 | echo
103 |
104 | ######### Evaluation #########
105 | ## For assembly evaluation, we used the following commands ##
106 | # quast-5.1.0rc1/metaquast.py -r ref.fa --min-contig 500 -o out --unique-mapping -t 16 contigs.fa
107 | # cat out/runs_per_reference/ref/report.tsv
108 |
--------------------------------------------------------------------------------
/src/bam2clip_fa.py:
--------------------------------------------------------------------------------
1 | '''
2 | Used to convert bam file into a hard/soft clipped fasta,
3 | mainly for breaking chimeric reads or removing artifact sequences
4 | in the both ends of reads.
5 | The soft clipped bases will be removed in both primary and supplementary alignments.
6 |
7 | Note: if the read is from - strand, the sequence in the bam is reversed and complementary,
8 | but the order of CIGAR string is consistent with the sequence in the bam.
9 |
10 | '''
11 |
12 | import sys
13 | import pysam
14 | import itertools
15 |
16 |
17 | def bam2fa(bam, fa, min_read_len):
18 | out = []
19 | with pysam.AlignmentFile(bam, 'rb') as fr:
20 | for line in fr:
21 | read_name, flag, _, _, _, cigar, _, _, _, seq = str(line).split()[:10]
22 | if flag=='4': #unmap reads
23 | continue
24 | # split cigar into list of numbers and characters all separately
25 | splitcigar = ["".join(x) for _, x in itertools.groupby(cigar, key=str.isdigit)]
26 | # print(splitcigar)
27 | if splitcigar[1] == 'S': # soft-clipped
28 | seq = seq[int(splitcigar[0]):]
29 | if splitcigar[-1] == 'S':
30 | seq = seq[:(-1 * int(splitcigar[-2]))]
31 | if len(seq) >= min_read_len:
32 | out.append('>' + read_name + '\n' + seq + '\n')
33 |
34 | with open(fa, 'w') as fw:
35 | fw.write(''.join(out))
36 | return
37 |
38 | if __name__ == '__main__':
39 | # bam = '/Users/xiaoluo/Documents/CWI/project/vg/test.bam'
40 | # fa = 'xx.fa'
41 | # min_read_len = 300
42 | #
43 | bam, fa, min_read_len = sys.argv[1:]
44 | bam2fa(bam, fa, int(min_read_len))
45 |
--------------------------------------------------------------------------------
/src/clustering.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | from multiprocessing import Pool
4 | from filter_ovlps import filter_ovlp
5 | from sort_reads import sort_reads_by_ovlps
6 |
7 |
8 | def get_read2seq(file, mode='fastq'):
9 | read2seq = {}
10 | read = ''
11 | seq = ''
12 | if mode == 'fastq':
13 | with open(file) as fr:
14 | for i, line in enumerate(fr):
15 | if i % 4 == 0:
16 | read = line.strip().strip('@')
17 | elif i % 4 == 1:
18 | seq = line.strip()
19 | read2seq[read] = seq
20 | else:
21 | continue
22 | elif mode == 'fasta':
23 | with open(file) as fr:
24 | for i, line in enumerate(fr):
25 | if i % 2 == 0:
26 | read = line.strip().strip('>')
27 | elif i % 2 == 1:
28 | seq = line.strip()
29 | read2seq[read] = seq
30 | else:
31 | continue
32 | else:
33 | print("Error: unknown mode, only fastq or fasta permitted.")
34 | sys.exit(1)
35 | return read2seq
36 |
37 |
38 | def write_fasta(k, reads, outdir, read2seq):
39 | fa = outdir + '/' + 'sread_cluster.' + str(k) + '.fa'
40 | with open(fa, 'w') as fw:
41 | for r in reads:
42 | fw.write(">" + r + "\n" + read2seq[r] + "\n")
43 | return fa
44 |
45 |
46 | def sort_reads_by_len(in_fa, outdir):
47 | id2seq = {}
48 | id = ''
49 |
50 | with open(in_fa) as fr:
51 | for line in fr:
52 | if line.startswith('>'):
53 | id = line.strip()
54 | else:
55 | seq = line.strip()
56 | id2seq[id] = [seq, len(seq)]
57 |
58 | out_fa = outdir + '/' + '.'.join(os.path.basename(in_fa).split('.')[:-1]) + '.sort_by_len.fa'
59 | fw = open(out_fa, 'w')
60 | i = 0
61 | for id, val in sorted(id2seq.items(), key=lambda d: d[1][1], reverse=True):
62 | i += 1
63 | fw.write(id + '\n' + val[0] + '\n')
64 | return out_fa
65 |
66 |
67 | def get_clusters(in_fa, outdir, topk, platform, threads, min_ovlp_len, min_identity, o, r, max_ovlps, min_sread_len,min_cluster_size):
68 | '''topk: top k seed read will be used
69 | '''
70 | id2fa = {} # each read to its corresponding fasta
71 | id = 0
72 | info = ''
73 | with open(in_fa) as fr:
74 | for line in fr:
75 | if line.startswith('>'):
76 | info += line
77 | else:
78 | info += line
79 | id2fa[id] = info
80 | info = ''
81 | id += 1
82 |
83 | read2seq = get_read2seq(in_fa, 'fasta')
84 | k = 0
85 | used_reads = {}
86 | cluster_list = []
87 | for id in range(len(id2fa)):
88 | if k >= topk:
89 | break
90 | print('processing the {} seed read...'.format(k + 1))
91 |
92 | header, seq = id2fa[id].strip().split('\n')
93 | if len(seq) < min_sread_len:
94 | break
95 | sread = header[1:] # seed read
96 | if sread in used_reads:
97 | continue
98 | with open(outdir + '/sread.fa', 'w') as fw:
99 | fw.write(header + '\n' + seq + '\n')
100 | # compute overlaps for seed read
101 | paf = outdir + '/sread.paf'
102 | filtered_paf = outdir + '/sread.filter.paf'
103 |
104 | # version 1
105 | os.system("minimap2 -cx ava-{} -t {} {} {}|cut -f 1-12 >{}".format(platform, threads, outdir + '/sread.fa', in_fa, paf))
106 |
107 | # version 2: do not use preset
108 | # os.system("minimap2 -c -k15 -w11 -t {} {} {}|cut -f 1-12 >{}".format(threads, outdir + '/sread.fa', in_fa, paf))
109 | # os.system("minimap2 -c -Hk23 -Xw7 -m100 -g10000 --max-chain-skip 25 -t {} {} {}|cut -f 1-12 >{}".format(threads, outdir + '/sread.fa', in_fa, paf))
110 | # os.system("minimap2 -cx asm5 -t {} {} {}|cut -f 1-12 >{}".format(threads, outdir + '/sread.fa', in_fa, paf)) # intra-species asm-to-asm alignment
111 | # os.system("minimap2 -X -c -k 21 -w 11 -s 60 -m 90 -n 2 -r 0 -A 4 -B 2 --end-bonus=100 -t {} {} {}|cut -f 1-12 >{}".format(threads, outdir + '/sread.fa', in_fa, paf)) # use parameters for short reads, from OGRE
112 |
113 | # if os.path.getsize(paf) <= 0:
114 | # continue
115 | filter_ovlp(paf, filtered_paf, min_ovlp_len, min_identity, o, r, max_ovlps, rm_extra_ovlps=True)
116 | print('read overlaps filtering finished.')
117 |
118 | reads = [] # read IDs in this cluster
119 |
120 | if os.path.getsize(filtered_paf) == 0:
121 | reads.append(sread)
122 | else:
123 | with open(filtered_paf, 'r') as fr:
124 | for line in fr:
125 | a = line.split()
126 | reads.extend([a[0], a[5]])
127 | reads = set(reads)
128 | if len(reads) < min_cluster_size: # iter2,only one contig is also fine
129 | # if len(reads)<5:
130 | continue
131 | sread_cluster_fa = write_fasta(k, reads, outdir, read2seq)
132 | for read in reads:
133 | used_reads[read] = 1
134 |
135 | # sort reads
136 | sorted_fa = sort_reads_by_ovlps(sread_cluster_fa, filtered_paf, outdir, by_length=1)
137 | cluster_list.append(sorted_fa)
138 | k += 1
139 | return cluster_list
140 |
141 |
142 | def get_consensus(param):
143 | # compute consensus
144 | i, cluster_fa, outdir = param
145 |
146 | #sort reads before run spoa, already sorted in get_clusters()
147 | consensus = os.popen('spoa -l 0 {}'.format(cluster_fa)).read()
148 | # consensus = os.popen('abpoa -m 1 {}'.format(cluster_fa)).read() #less computational cost,but result seems not good as spoa
149 |
150 | consensus = consensus.strip().split('\n')[-1]
151 | header = os.popen('cat {}|head -1'.format(cluster_fa)).read()
152 | out_fa = outdir + '/contig.' + str(i) + '.fa'
153 | with open(out_fa, 'w') as fw:
154 | fw.write(header + consensus + '\n')
155 | return out_fa
156 |
157 |
158 | def get_consensus_parallel(cluster_list, threads, outdir):
159 | pool = Pool(threads)
160 | params = [(i, cluster, outdir) for i, cluster in enumerate(cluster_list)]
161 | pool.map(get_consensus, params, chunksize=1) # ordered
162 | pool.close()
163 | pool.join()
164 | # with open(outdir + '/contigs.fa', 'w'd) as fw:
165 | # fw.write(''.join(out))
166 | return
167 |
168 |
169 | if __name__ == '__main__':
170 | # topk: top k seed reads
171 | in_fa, outdir, topk, platform, threads, min_ovlp_len, min_identity, o, r, max_ovlps, min_sread_len = sys.argv[1:]
172 | cluster_list = get_clusters(in_fa, outdir, int(topk), platform, int(threads), int(min_ovlp_len),
173 | float(min_identity), int(o), float(r), int(max_ovlps), int(min_sread_len),min_cluster_size=1)
174 | get_consensus_parallel(cluster_list, int(threads), outdir)
175 | os.system('rm -rf {}/sread*'.format(outdir))
176 |
--------------------------------------------------------------------------------
/src/compute_ANI.py:
--------------------------------------------------------------------------------
1 |
2 | import sys
3 | import os
4 |
5 | def compute_ANI_ij(fa,i,j,outdir):
6 | '''
7 | compute the ANI of the i <-> j th sequence in the fasta (one sequence per line)
8 | '''
9 | try:
10 | i_fa="{}/seq.{}.fa".format(outdir,i)
11 | j_fa="{}/seq.{}.fa".format(outdir,j)
12 | os.system("head -{} {}|tail -2 >{}".format(i*2,fa,i_fa))
13 |
14 | os.system("head -{} {}|tail -2 >{}".format(j*2,fa,j_fa))
15 | os.system("fastANI -q {} -r {} -o {}/ani.{}.{}.out -t 1 >/dev/null 2>&1".format(i_fa,j_fa,outdir,i,j))
16 | os.system("rm -f {} {}".format(i_fa,j_fa))
17 | except:
18 | raise Exception("Failed to extract sequences for ANI computation.")
19 |
20 |
21 | if __name__ == '__main__':
22 | fa,i,j,outdir=sys.argv[1:]
23 | i =int(i)
24 | j =int(j)
25 | os.system("mkdir -p {}".format(outdir))
26 | compute_ANI_ij(fa,i,j,outdir)
27 |
--------------------------------------------------------------------------------
/src/est_abundance.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | ##############################################
6 | ### Step4: low frequent haplotypes removal ###
7 | ##############################################
8 | old_hap_fa=$1
9 | corrected_reads_fa=$2 #corrected read fasta
10 | min_abun=$3 #0.02
11 |
12 | percent_identity=97
13 | threads=36
14 | export min_abundance=$min_abun
15 |
16 | mkdir -p filter_by_abun2
17 | cd filter_by_abun2 || exit
18 | #fa_read=../corrected.0.fa #corrected reads
19 |
20 | for i in {1..2};
21 | do
22 | if [[ $i == 1 ]];then
23 | cat $old_hap_fa | perl -ne 'BEGIN{$i=1;}if(/^>/){print ">contig_$i\n";$i+=1;}else{print;}' >haps.fa
24 | else
25 | cat haplotypes.final.fa | perl -ne 'BEGIN{$i=1;}if(/^>/){print ">contig_$i\n";$i+=1;}else{print;}' >haps.fa
26 | fi
27 | minimap2 -a --secondary=no -t $threads haps.fa $corrected_reads_fa | samtools view -F 3584 -b -t $threads | samtools sort - >haps.bam
28 |
29 | jgi_summarize_bam_contig_depths haps.bam --percentIdentity $percent_identity --outputDepth haps.depth
30 |
31 | perl -e 'open A,"haps.depth";;my$alldepth=0;while(){my@a=split;$alldepth+=$a[2];}close A; \
32 | open A,"haps.depth";;while(){my@a=split;my$d=$a[2]/$alldepth;print "$a[0]\t$a[1]\t$a[2]\t$d\n";}close A; ' |
33 | sort -k4nr >haps.depth.sort
34 |
35 | perl -e ' my%id2seq;$/=">";open A,"haps.fa";;while(){chomp;my@a=split;$id2seq{$a[0]}=$a[1];}close A;
36 | $/="\n"; open A,"haps.depth.sort";my$k=0;while(){chomp;my@a=split;next if $a[-1]<$ENV{"min_abundance"};
37 | my$abun=sprintf "%.3f",$a[-1];my$cov=sprintf "%.0f",$a[-2]; $k+=1;print ">hap$k $cov"."x freq=$abun\n$id2seq{$a[0]}\n";}close A; ' >haplotypes.final.fa
38 | done
39 |
40 | cp haplotypes.final.fa ../victor.fa
41 |
42 | echo 'All steps finished successfully.'
43 |
--------------------------------------------------------------------------------
/src/filter_ovlps.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 |
4 | __author__ = "Xiao Luo"
5 |
6 | usage = '''
7 | This program is used to filter long read overlaps(i.e.,duplicate or internal overlaps)
8 | which are generated by minimap2
9 | '''
10 |
11 |
12 | def paf_to_str(paf, min_len, min_identity, cigar=False):
13 | '''
14 | read paf file into a string, only keep 12 columns to reduce memory
15 | '''
16 | if os.path.getsize(paf) == 0:
17 | return ''
18 | ovlp_str = ''
19 | with open(paf, 'r') as fr:
20 | for line in fr:
21 | a = line.split()
22 | if int(a[10]) >= min_len and float(a[9]) / float(a[10]) >= min_identity:
23 | if cigar:
24 | ovlp_str += line # keep all infor, like CIGAR
25 | else:
26 | ovlp_str += '\t'.join(line.split()[:12]) + '\n'
27 | return ovlp_str.strip()
28 |
29 |
30 | def rm_dupovlp(ovlp_str):
31 | '''
32 | only keep the longest overlap if multiple overlaps exist for one pair reads
33 | and remove self-overlaps
34 | '''
35 | ovlp = {}
36 | self_counts = 0
37 | dup_counts = 0
38 | for line in ovlp_str.strip().split('\n'):
39 | a = line.strip().split()
40 | qname = a[0]
41 | tname = a[5]
42 | if qname == tname:
43 | self_counts += 1
44 | continue
45 | ovlp_len = int(a[10])
46 | key = ':'.join(sorted([qname, tname]))
47 | if key not in ovlp:
48 | ovlp[key] = line
49 | elif ovlp_len > int(ovlp[key].split()[10]):
50 | ovlp[key] = line
51 | dup_counts += 1
52 |
53 | ovlp_str2 = '\n'.join([ovlp[key] for key in ovlp.keys()])
54 | print("self-overlap counts:" + str(self_counts))
55 | print("duplicated overlap counts:" + str(dup_counts))
56 | ovlp = {}
57 | return ovlp_str2
58 |
59 |
60 | def keep_max_ovlps(ovlp_str, max_ovlps, rm_extra_ovlps=False):
61 | '''
62 | only keep the top max_ovlps(with decrease order of overlap length) overlaps for each read,
63 | in the final result there may be some reads that have more than max_ovlps in all, which is reasonable
64 | rm_extra_ovlps: is equal to delete edges which are out of max number overlaps in the overlap graph
65 | '''
66 | out = []
67 | rr2line = {}
68 | used_rr = {}
69 | if not rm_extra_ovlps:
70 | for line in ovlp_str.strip().split('\n'):
71 | a = line.strip().split()
72 | qname = a[0]
73 | tname = a[5]
74 | rr2line.setdefault(qname, {})[tname] = line
75 | rr2line.setdefault(tname, {})[qname] = line
76 | used_rr.setdefault(qname, {})[tname] = 0
77 | used_rr.setdefault(tname, {})[qname] = 0
78 | reads = list(rr2line.keys())
79 | for read in reads:
80 | if read not in rr2line: continue
81 | if len(rr2line[read]) <= max_ovlps:
82 | ovlp_reads = list(rr2line[read].keys())
83 | else:
84 | all_ovlp_reads = [t[0] for t in
85 | sorted(rr2line[read].items(), key=lambda d: int(d[1].split()[10]), reverse=True)]
86 | ovlp_reads = all_ovlp_reads[:max_ovlps]
87 |
88 | for ovlp_read in ovlp_reads:
89 | if not used_rr[read][ovlp_read]:
90 | out.append(rr2line[read][ovlp_read])
91 | used_rr[read][ovlp_read] = 1
92 | used_rr[ovlp_read][read] = 1
93 | # del rr2line[ovlp_read][read]
94 | # del rr2line[read]
95 | else: # TODO still a bug?
96 | for line in ovlp_str.strip().split('\n'):
97 | a = line.strip().split()
98 | qname = a[0]
99 | tname = a[5]
100 | rr2line.setdefault(qname, {})[tname] = line
101 | rr2line.setdefault(tname, {})[qname] = line
102 | reads = list(rr2line.keys())
103 | for read in reads:
104 | if read not in rr2line: continue
105 | if len(rr2line[read]) <= max_ovlps:
106 | ovlp_reads = list(rr2line[read].keys())
107 | else:
108 | all_ovlp_reads = [t[0] for t in
109 | sorted(rr2line[read].items(), key=lambda d: int(d[1].split()[10]), reverse=True)]
110 | ovlp_reads = all_ovlp_reads[:max_ovlps]
111 | for r in all_ovlp_reads[max_ovlps:]:
112 | if r in rr2line:
113 | del rr2line[r][read]
114 | # print('{} overlapped reads number:{}'.format(read,len(ovlp_reads)))
115 |
116 | for ovlp_read in ovlp_reads:
117 | out.append(rr2line[read][ovlp_read])
118 | del rr2line[ovlp_read][read]
119 | del rr2line[read]
120 |
121 | ovlp_str2 = '\n'.join(out)
122 |
123 | # delet large variables
124 | del rr2line, used_rr, out
125 |
126 | return ovlp_str2
127 |
128 |
129 | def rm_intermatch(ovlp_str, o=1000, r=0.8):
130 | '''
131 | filter internal match overlaps
132 | o: overhang length
133 | r: ratio
134 | '''
135 | ovlps = []
136 | inter = 0
137 | for line in ovlp_str.strip().split('\n'):
138 | a = line.strip().split()
139 | l1 = int(a[1])
140 | b1 = int(a[2])
141 | e1 = int(a[3])
142 | direction = a[4]
143 | l2 = int(a[6])
144 | if direction == '-':
145 | '''
146 | - overhang region: ***
147 | - b2,e2: both are the cordinates in the following sequence,
148 | no matter what the direction is.
149 |
150 | b1 e1 l1
151 | v ------------------------->
152 | |***|/////////|*****|
153 | w <----------------------------
154 | b2 e2 l2
155 | '''
156 | b2 = l2 - int(a[8]) # end in original seq
157 | e2 = l2 - int(a[7]) # start in original seq
158 | else:
159 | b2 = int(a[7])
160 | e2 = int(a[8])
161 |
162 | # from algorithm 5 in minimap paper
163 | overhang = min(b1, b2) + min(l1 - e1, l2 - e2)
164 | maplen = max(e1 - b1, e2 - b2)
165 |
166 | if overhang > min(o, maplen * r):
167 | # internal match
168 | inter += 1
169 | continue
170 | else:
171 | ovlps.append(line)
172 | ovlp_str2 = '\n'.join(ovlps)
173 | print("internal overlap counts:" + str(inter))
174 | del ovlps
175 | return ovlp_str2
176 |
177 |
178 | def ovlp_str2paf(ovlp_str, paf):
179 | with open(paf, 'w') as fw:
180 | fw.write(ovlp_str)
181 |
182 | def rm_extra_ovlps(in_paf,out_paf,max_ovlps, rm_extra_ovlps):
183 | if os.path.getsize(in_paf)==0:
184 | open(out_paf,'w').close()
185 | return out_paf
186 | ovlp_str = paf_to_str(in_paf, 0, 0)
187 | print('keeping the max number of overlaps...')
188 | ovlp_str = keep_max_ovlps(ovlp_str, max_ovlps, rm_extra_ovlps)
189 | ovlp_str2paf(ovlp_str, out_paf)
190 | return out_paf
191 |
192 | def filter_ovlp(in_paf, out_paf, min_ovlp_len=1000, min_identity=0.9, o=800, r=0.8, max_ovlps=None,
193 | rm_extra_ovlps=False, cigar=False):
194 | ovlp_str = paf_to_str(in_paf, min_ovlp_len, min_identity, cigar) # filter wrong overlaps
195 |
196 | if ovlp_str:
197 | print('removing internal overlaps...')
198 | ovlp_str = rm_intermatch(ovlp_str, o, r)
199 | if ovlp_str:
200 | print('removing duplicated overlaps...')
201 | ovlp_str = rm_dupovlp(ovlp_str)
202 |
203 | if max_ovlps and ovlp_str:
204 | print('keeping the max number of overlaps...')
205 | ovlp_str = keep_max_ovlps(ovlp_str, max_ovlps, rm_extra_ovlps)
206 |
207 | if not ovlp_str:
208 | print('No overlap any more. Stop iterating')
209 |
210 | print('writing the filtered overlaps into paf file...')
211 | ovlp_str2paf(ovlp_str, out_paf)
212 | return
213 |
214 |
215 | def main():
216 | # in_paf = "../data/local/xx.paf" # ovlpf or paf file
217 | # out_paf="../data/local/xx.filtered.paf"
218 | in_paf, out_paf, min_ovlp_len, min_identity, o = sys.argv[1:]
219 | filter_ovlp(in_paf, out_paf, int(min_ovlp_len), float(min_identity), int(o))
220 | return
221 |
222 |
223 | if __name__ == '__main__':
224 | sys.exit(main())
225 |
--------------------------------------------------------------------------------
/src/genome_divergence.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 |
4 | '''This program is used to compute the divergence between two genomes from two fasta files'''
5 |
6 |
7 | def fasta_len(fa):
8 | sum_len = 0
9 | with open(fa, 'r') as fr:
10 | for line in fr:
11 | if line.startswith('>'):
12 | continue
13 | else:
14 | sum_len += len(line.strip())
15 | return sum_len
16 |
17 |
18 | def cal_genome_divergence(fa1, fa2):
19 | paf_out = os.popen("minimap2 -cx asm20 -t 16 {} {} 2>/dev/null".format(fa1, fa2)).read().strip().split('\n')
20 | divergence = 1.0
21 | if not paf_out[0]:
22 | return divergence,divergence
23 | matched_len = 0 # identical bases
24 | ovlp_len = 0 # including mismatches and gaps
25 | for i, line in enumerate(paf_out):
26 | a = line.split('\t')
27 | matched_len += int(a[9])
28 | ovlp_len += int(a[10])
29 | fa1_len = fasta_len(fa1)
30 | fa2_len = fasta_len(fa2)
31 |
32 | fa1_uniq_ovlplen = os.popen("minimap2 -ax asm20 -t 16 {} {} 2>/dev/null|samtools sort - |samtools depth -|wc -l".
33 | format(fa1, fa2)).read().strip()
34 | fa2_uniq_ovlplen = os.popen("minimap2 -ax asm20 -t 16 {} {} 2>/dev/null|samtools sort - |samtools depth -|wc -l".
35 | format(fa2, fa1)).read().strip()
36 | fa1_uniq_ovlplen = int(fa1_uniq_ovlplen)
37 | fa2_uniq_ovlplen = int(fa2_uniq_ovlplen)
38 | global_divergence = round(1 - matched_len / (ovlp_len + fa1_len - fa1_uniq_ovlplen + fa2_len - fa2_uniq_ovlplen), 4)
39 |
40 | ovlp_divergence = round(1 - matched_len / ovlp_len, 4) # only consider the overlap regions
41 |
42 | return global_divergence, ovlp_divergence
43 |
44 |
45 | if __name__ == '__main__':
46 | fa1, fa2 = sys.argv[1:]
47 | # fa1='../data/1.fa'
48 | # fa2='../data/2.fa'
49 | global_divergence, ovlp_divergence = cal_genome_divergence(fa1, fa2)
50 | print('\n'+'-'*50)
51 | print('The global genome divergence is : {}%'.format(global_divergence * 100))
52 | print('The overlap regions divergence is: {}%'.format(ovlp_divergence * 100))
53 | print('-'*50)
54 |
55 |
--------------------------------------------------------------------------------
/src/reformat_fa.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 |
4 | def reformat_fasta(in_fa, out_fa):
5 | id2seq = {}
6 | id = ''
7 | seq = ''
8 | with open(in_fa) as fr:
9 | for line in fr:
10 | if line.startswith('>'):
11 | if id:
12 | id2seq[id] = [seq, len(seq)]
13 | seq = ''
14 | id = line.strip()
15 | else:
16 | seq += line.strip()
17 | id2seq[id] = [seq, len(seq)]
18 |
19 | fw = open(out_fa, 'w')
20 | i = 0
21 | for id, val in sorted(id2seq.items(), key=lambda d: d[1][1], reverse=True):
22 | i += 1
23 | fw.write('>r' + str(i) + '\n' + val[0] + '\n')
24 | return out_fa
25 |
26 |
27 | if __name__ == '__main__':
28 | in_fa, out_fa = sys.argv[1:]
29 | reformat_fasta(in_fa, out_fa)
30 |
--------------------------------------------------------------------------------
/src/rm_misassembly.clip.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | import itertools
4 | from multiprocessing import Pool
5 |
6 | def get_posi_by_depth(lst, min_cov, w=5):
7 | '''
8 | get the start and end positions of fragments if there are low coverage regions
9 | in the middle of sequence, the input should be better trimmed at both ends.
10 | '''
11 | min_cov = min_cov # * 0.8 # becuase of unstable coverage
12 | min_len = 500 # TODO, min length for output sequence
13 | k = int(len(lst) / w) + 1
14 | mean_cov = 0
15 | start = -1
16 | end = -1
17 | flag = False
18 | posi_list = []
19 | for i in range(k):
20 | mean_cov = sum([int(posi_cov.strip().split()[1]) for posi_cov in lst[i * w:(i + 1) * w]]) / w
21 | # print('mean_cov:{}'.format(mean_cov))
22 | if mean_cov < min_cov:
23 | if start != -1:
24 | if (end - start) >= min_len:
25 | posi_list.append((start, end, end - start))
26 | start = -1
27 | end = -1
28 | flag = False
29 | continue
30 | elif mean_cov >= min_cov and not flag:
31 | start = int(lst[i * w].strip().split()[0])
32 | end = int(lst[min(len(lst), (i + 1) * w) - 1].strip().split()[0])
33 | flag = True
34 | elif flag:
35 |
36 | end = int(lst[min(len(lst), (i + 1) * w) - 1].strip().split()[0])
37 | # print('end:{}'.format(end))
38 | if flag and ((end - start) >= min_len):
39 | posi_list.append((start, end, end - start)) # add the last one
40 | return posi_list
41 |
42 |
43 | def cov_based_misasm_removal_xx(param):
44 | i, reads_fa,outdir, min_cov, threads, trim_ends = param
45 | contig_fa='contig.{}.fa'.format(i)
46 | os.system("mkdir -p {}".format(outdir))
47 | out_fa = outdir + '/xx.{}.fa'.format(i)
48 |
49 | # compute coverage for each base, filter secondary and supplementary alignments at first
50 | bam = outdir + "/" + str(i) + ".bam"
51 | os.system("minimap2 -a" + " --secondary=no -t 1 " +" "+ contig_fa + " " + reads_fa + \
52 | " 2>/dev/null |samtools view -hS -F 2048 -|samtools sort -@ 1 - >" + bam)
53 | # print("minimap2 -a" + " --secondary=no -t " + str(threads) + contig_fa + " " + reads_fa + \
54 | # " 2>/dev/null |samtools view -hS -F 2048 -|samtools sort -@ 24 - >" + bam)
55 |
56 | # TODO need to consider the low coverage region in the middle of sequence
57 | # @@ check why many errors in the middle of some super reads:
58 | # some reads are assigned into a wrong haplotype group or reads in the middle are belong to
59 | # one haplotype and reads in both ends are belong to the other, which may cause this mistake, therefore,
60 | # one should split the super reads into different parts and only keep the short fragments
61 | # (OR only keep the longest fragment) that are satisfied with min coverage requirement.
62 | """
63 | positions = os.popen("samtools depth " + bam + "|awk '$3>=" + str(min_cov) + \
64 | "'|cut -f 2|sed -n '1p;$p'").read().strip()
65 | if positions:
66 | [start, end] = positions.split("\n") # 1 based for sam
67 | else:
68 | print("{}.{}: no sequence satisfies the requirement of min coverage".format(i, hap))
69 | open(out_fa, 'w').close() # new an empty file
70 | return
71 | """
72 |
73 | if os.path.getsize(bam) == 0:
74 | print("{}: no read can be aligned to the super read, skipping...".format(i),
75 | file=open("{}/log".format(outdir), 'a'))
76 | open(out_fa, 'w').close() # new an empty file
77 | return
78 | else:
79 | positions = os.popen("samtools depth " + bam + "|awk '{print NR, $0}'" + "|awk '$4>=" + str(min_cov) + \
80 | "'|cut -f 1 -d ' '|sed -n '1p;$p'").read().strip()
81 | if positions:
82 | [a, b] = [int(x) for x in positions.split("\n")] # line number
83 | posi_cov_list = os.popen("samtools depth " + bam + "|cut -f 2,3").read().strip().split('\n')
84 | posi_list = get_posi_by_depth(posi_cov_list[(a - 1):b], min_cov, w=5) # 1 based for sam
85 | print('posi_list:{}'.format(posi_list))
86 | else:
87 | print("contig.{}.fa: no sequence satisfies the requirement of min coverage".format(i),
88 | file=open("{}/log".format(outdir), 'a'))
89 | open(out_fa, 'w').close() # new an empty file
90 | return
91 |
92 | with open(contig_fa, "r") as fr:
93 | seq = fr.readline()
94 | seq = fr.readline().strip()
95 |
96 | sub_k = 1
97 | if trim_ends:
98 | for start, end, _ in posi_list:
99 | consensus = seq[(int(start) - 1):int(end)]
100 | if len(posi_list) == 1:
101 | head = ">c_{}\n".format(i)
102 | else:
103 | head = ">c_{}_sub{}\n".format(i, sub_k)
104 | with open(out_fa, 'a') as fw:
105 | fw.write(head + consensus + '\n')
106 | sub_k += 1
107 | else:
108 | # trim ends with low coverage and also break at the misassembled positions in the middle regions
109 | for start, end, _ in posi_list:
110 | if len(posi_list) == 1:
111 | consensus = seq[(int(start) - 1):int(end)]
112 | head = ">contig_{}\n".format(i)
113 | else:
114 | if sub_k == 1:
115 | consensus = seq[:int(end)]
116 | elif sub_k == len(posi_list):
117 | consensus = seq[(int(start) - 1):]
118 | else:
119 | consensus = seq[(int(start) - 1):int(end)]
120 | head = ">contig_{}_sub{}\n".format(i, sub_k)
121 | with open(outdir+'/contig.{}.sub{}.fa'.format(i,sub_k), 'w') as fw:
122 | fw.write(head + consensus + '\n')
123 | sub_k += 1
124 |
125 | return
126 |
127 |
128 | def cov_based_misasm_removal(param):
129 | i, reads_fa, all_bam, outdir, min_cov, threads, trim_ends = param
130 | # os.system("mkdir -p {}".format(outdir))
131 | out_fa = outdir + '/xx.{}.fa'.format(i)
132 |
133 |
134 | # compute coverage for each base, filter secondary and supplementary alignments at first
135 | bam = outdir + "/contig" + str(i) + ".bam"
136 | os.system("samtools view -b {} contig{} >{}".format(all_bam,str(i),bam))
137 | os.system("samtools index {}".format(bam))
138 |
139 | if os.path.getsize(bam) == 0:
140 | print("contig{}: bam is empty, skipping...".format(i),
141 | file=open("{}/log".format(outdir), 'a'))
142 | open(out_fa, 'w').close() # new an empty file
143 | return
144 | else:
145 | positions = os.popen("samtools depth " + bam + "|awk '{print NR, $0}'" + "|awk '$4>=" + str(min_cov) + \
146 | "'|cut -f 1 -d ' '|sed -n '1p;$p'").read().strip()
147 | if positions:
148 | [a, b] = [int(x) for x in positions.split("\n")] # line number
149 | posi_cov_list = os.popen("samtools depth " + bam + "|cut -f 2,3").read().strip().split('\n')
150 | posi_list = get_posi_by_depth(posi_cov_list[(a - 1):b], min_cov, w=5) # 1 based for sam
151 | print('# contig:{}, posi_list:{}'.format(i,posi_list))
152 | else:
153 | print("contig.{}.fa: no sequence satisfies the requirement of min coverage".format(i),
154 | file=open("{}/log".format(outdir), 'a'))
155 | open(out_fa, 'w').close() # new an empty file
156 | return
157 |
158 | contig="contig{}".format(i)
159 | seq = contig2seq[contig]
160 |
161 | sub_k = 1
162 | if trim_ends:
163 | for start, end, _ in posi_list:
164 | consensus = seq[(int(start) - 1):int(end)]
165 | if len(posi_list) == 1:
166 | head = ">c_{}\n".format(i)
167 | else:
168 | head = ">c_{}_sub{}\n".format(i, sub_k)
169 | with open(out_fa, 'a') as fw:
170 | fw.write(head + consensus + '\n')
171 | sub_k += 1
172 | else:
173 | # trim ends with low coverage and also break at the misassembled positions in the middle regions
174 | for start, end, _ in posi_list:
175 | if len(posi_list) == 1:
176 | consensus = seq[(int(start) - 1):int(end)]
177 | head = ">contig_{}\n".format(i)
178 | else:
179 | if sub_k == 1:
180 | consensus = seq[:int(end)]
181 | elif sub_k == len(posi_list):
182 | consensus = seq[(int(start) - 1):]
183 | else:
184 | consensus = seq[(int(start) - 1):int(end)]
185 | head = ">contig_{}_sub{}\n".format(i, sub_k)
186 | with open(outdir + '/contig.{}.sub{}.fa'.format(i, sub_k), 'w') as fw:
187 | fw.write(head + consensus + '\n')
188 | sub_k += 1
189 |
190 | return
191 |
192 |
193 | def clip_based_misasm_removal(read_fa, hap_fa, threads, outdir, min_clip_count):
194 | '''remove misassemblies based on clipped read alignments'''
195 | os.system("mkdir -p {}".format(outdir))
196 | sam = outdir + '/tmp.sam'
197 | min_clip_len = 5
198 |
199 | os.system(
200 | "minimap2 -a --secondary=no {} {} -t {}|samtools view -F 2048 - >{}".format(hap_fa, read_fa, threads, sam))
201 | hap2bpposi_tmp = {}
202 | hap2bpposi = {}
203 |
204 | with open(sam, 'r') as fr:
205 | for line in fr:
206 | a = line.split()
207 | hap, posi, cigar, seq = a[2], int(a[3]), a[5], a[9]
208 | read_len = len(seq)
209 | bp_posi = -1 # breakpoint position at target sequence
210 | # split cigar into list of numbers and characters all separately
211 | splitcigar = ["".join(x) for _, x in itertools.groupby(cigar, key=str.isdigit)] # 25S100M2S
212 | if splitcigar[1] == 'S': # soft-clipped, left
213 | if int(splitcigar[0]) < min_clip_len:
214 | if splitcigar[-1] == 'S' and int(splitcigar[-2]) >= min_clip_len:
215 | bp_posi = posi + read_len - int(splitcigar[-2]) # soft-clipped on both sides,such as 2S1000M50S
216 | else:
217 | continue
218 | else:
219 | bp_posi = posi
220 | elif splitcigar[-1] == 'S': # soft-clipped, right
221 | if int(splitcigar[-2]) < min_clip_len:
222 | continue
223 | else:
224 | bp_posi = posi + read_len - int(splitcigar[-2])
225 | else:
226 | continue
227 | if hap in hap2bpposi_tmp:
228 | hap2bpposi_tmp[hap].append(bp_posi)
229 | else:
230 | hap2bpposi_tmp[hap] = [bp_posi]
231 |
232 | for hap, posi_list in hap2bpposi_tmp.items():
233 | posi2count = {}
234 | for posi in posi_list:
235 | if posi in posi2count:
236 | posi2count[posi] += 1
237 | else:
238 | posi2count[posi] = 1
239 | for posi, count in posi2count.items():
240 | if count >= min_clip_count:
241 | print("## posi, count:{},{}".format(posi,count))
242 | if hap in hap2bpposi:
243 | hap2bpposi[hap].append(posi)
244 | else:
245 | hap2bpposi[hap] = [posi]
246 |
247 | hap2bpposi = {hap: sorted(posi_list) for hap, posi_list in hap2bpposi.items()}
248 | print('## haplotype to breakpoint position: {}'.format(hap2bpposi))
249 | hap=''
250 | out_info=[]
251 | i=0
252 | with open(hap_fa) as fr:
253 | for line in fr:
254 | sub_seqs=[]
255 | if line.startswith('>'):
256 | hap=line.strip()[1:]
257 | else:
258 | seq=line.strip()
259 | start=0
260 | if hap not in hap2bpposi:
261 | i+=1
262 | out_info.append('>hap_'+str(i)+'\n'+seq+'\n')
263 | continue
264 | for bp_posi in hap2bpposi[hap]:
265 | sub_seq = seq[start:(bp_posi-1)]
266 | sub_seqs.append(sub_seq)
267 | start=bp_posi-1
268 |
269 | sub_seqs.append(seq[start:]) #last sub sequence
270 | for s in sub_seqs:
271 | if len(s)<500: #filter short sequences
272 | continue
273 | i+=1
274 | out_info.append('>hap_' + str(i)+'\n'+s+'\n')
275 |
276 | with open(outdir+'/haplotypes.final.fasta','w') as fw:
277 | fw.write(''.join(out_info))
278 | return
279 |
280 |
281 |
282 |
283 | if __name__ == '__main__':
284 | read_fa, contig_fa, outdir, threads= sys.argv[1:]
285 | os.system("mkdir -p {}".format(outdir))
286 | clip_based_misasm_removal(read_fa,contig_fa , threads, outdir, min_clip_count=10)
287 |
--------------------------------------------------------------------------------
/src/rm_misassembly.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | import itertools
4 | from multiprocessing import Pool
5 |
6 | def get_posi_by_depth(lst, min_cov, w=5):
7 | '''
8 | get the start and end positions of fragments if there are low coverage regions
9 | in the middle of sequence, the input should be better trimmed at both ends.
10 | '''
11 | min_cov = min_cov # * 0.8 # becuase of unstable coverage
12 | min_len = 500 # TODO, min length for output sequence
13 | k = int(len(lst) / w) + 1
14 | mean_cov = 0
15 | start = -1
16 | end = -1
17 | flag = False
18 | posi_list = []
19 | for i in range(k):
20 | mean_cov = sum([int(posi_cov.strip().split()[1]) for posi_cov in lst[i * w:(i + 1) * w]]) / w
21 | # print('mean_cov:{}'.format(mean_cov))
22 | if mean_cov < min_cov:
23 | if start != -1:
24 | if (end - start) >= min_len:
25 | posi_list.append((start, end, end - start))
26 | start = -1
27 | end = -1
28 | flag = False
29 | continue
30 | elif mean_cov >= min_cov and not flag:
31 | start = int(lst[i * w].strip().split()[0])
32 | end = int(lst[min(len(lst), (i + 1) * w) - 1].strip().split()[0])
33 | flag = True
34 | elif flag:
35 |
36 | end = int(lst[min(len(lst), (i + 1) * w) - 1].strip().split()[0])
37 | # print('end:{}'.format(end))
38 | if flag and ((end - start) >= min_len):
39 | posi_list.append((start, end, end - start)) # add the last one
40 | return posi_list
41 |
42 |
43 | def cov_based_misasm_removal_xx(param):
44 | i, reads_fa,outdir, min_cov, threads, trim_ends = param
45 | contig_fa='contig.{}.fa'.format(i)
46 | os.system("mkdir -p {}".format(outdir))
47 | out_fa = outdir + '/xx.{}.fa'.format(i)
48 |
49 | # compute coverage for each base, filter secondary and supplementary alignments at first
50 | bam = outdir + "/" + str(i) + ".bam"
51 | os.system("minimap2 -a" + " --secondary=no -t 1 " +" "+ contig_fa + " " + reads_fa + \
52 | " 2>/dev/null |samtools view -hS -F 2048 -|samtools sort -@ 1 - >" + bam)
53 | # print("minimap2 -a" + " --secondary=no -t " + str(threads) + contig_fa + " " + reads_fa + \
54 | # " 2>/dev/null |samtools view -hS -F 2048 -|samtools sort -@ 24 - >" + bam)
55 |
56 | # TODO need to consider the low coverage region in the middle of sequence
57 | # @@ check why many errors in the middle of some super reads:
58 | # some reads are assigned into a wrong haplotype group or reads in the middle are belong to
59 | # one haplotype and reads in both ends are belong to the other, which may cause this mistake, therefore,
60 | # one should split the super reads into different parts and only keep the short fragments
61 | # (OR only keep the longest fragment) that are satisfied with min coverage requirement.
62 | """
63 | positions = os.popen("samtools depth " + bam + "|awk '$3>=" + str(min_cov) + \
64 | "'|cut -f 2|sed -n '1p;$p'").read().strip()
65 | if positions:
66 | [start, end] = positions.split("\n") # 1 based for sam
67 | else:
68 | print("{}.{}: no sequence satisfies the requirement of min coverage".format(i, hap))
69 | open(out_fa, 'w').close() # new an empty file
70 | return
71 | """
72 |
73 | if os.path.getsize(bam) == 0:
74 | print("{}: no read can be aligned to the super read, skipping...".format(i),
75 | file=open("{}/log".format(outdir), 'a'))
76 | open(out_fa, 'w').close() # new an empty file
77 | return
78 | else:
79 | positions = os.popen("samtools depth " + bam + "|awk '{print NR, $0}'" + "|awk '$4>=" + str(min_cov) + \
80 | "'|cut -f 1 -d ' '|sed -n '1p;$p'").read().strip()
81 | if positions:
82 | [a, b] = [int(x) for x in positions.split("\n")] # line number
83 | posi_cov_list = os.popen("samtools depth " + bam + "|cut -f 2,3").read().strip().split('\n')
84 | posi_list = get_posi_by_depth(posi_cov_list[(a - 1):b], min_cov, w=5) # 1 based for sam
85 | print('posi_list:{}'.format(posi_list))
86 | else:
87 | print("contig.{}.fa: no sequence satisfies the requirement of min coverage".format(i),
88 | file=open("{}/log".format(outdir), 'a'))
89 | open(out_fa, 'w').close() # new an empty file
90 | return
91 |
92 | with open(contig_fa, "r") as fr:
93 | seq = fr.readline()
94 | seq = fr.readline().strip()
95 |
96 | sub_k = 1
97 | if trim_ends:
98 | for start, end, _ in posi_list:
99 | consensus = seq[(int(start) - 1):int(end)]
100 | if len(posi_list) == 1:
101 | head = ">c_{}\n".format(i)
102 | else:
103 | head = ">c_{}_sub{}\n".format(i, sub_k)
104 | with open(out_fa, 'a') as fw:
105 | fw.write(head + consensus + '\n')
106 | sub_k += 1
107 | else:
108 | # trim ends with low coverage and also break at the misassembled positions in the middle regions
109 | for start, end, _ in posi_list:
110 | if len(posi_list) == 1:
111 | consensus = seq[(int(start) - 1):int(end)]
112 | head = ">contig_{}\n".format(i)
113 | else:
114 | if sub_k == 1:
115 | consensus = seq[:int(end)]
116 | elif sub_k == len(posi_list):
117 | consensus = seq[(int(start) - 1):]
118 | else:
119 | consensus = seq[(int(start) - 1):int(end)]
120 | head = ">contig_{}_sub{}\n".format(i, sub_k)
121 | with open(outdir+'/contig.{}.sub{}.fa'.format(i,sub_k), 'w') as fw:
122 | fw.write(head + consensus + '\n')
123 | sub_k += 1
124 |
125 | return
126 |
127 |
128 | def cov_based_misasm_removal(param):
129 | i, reads_fa, all_bam, outdir, min_cov, threads, trim_ends = param
130 | # os.system("mkdir -p {}".format(outdir))
131 | out_fa = outdir + '/xx.{}.fa'.format(i)
132 |
133 |
134 | # compute coverage for each base, filter secondary and supplementary alignments at first
135 | bam = outdir + "/contig" + str(i) + ".bam"
136 | os.system("samtools view -b {} contig{} >{}".format(all_bam,str(i),bam))
137 | os.system("samtools index {}".format(bam))
138 |
139 | if os.path.getsize(bam) == 0:
140 | print("contig{}: bam is empty, skipping...".format(i),
141 | file=open("{}/log".format(outdir), 'a'))
142 | open(out_fa, 'w').close() # new an empty file
143 | return
144 | else:
145 | positions = os.popen("samtools depth " + bam + "|awk '{print NR, $0}'" + "|awk '$4>=" + str(min_cov) + \
146 | "'|cut -f 1 -d ' '|sed -n '1p;$p'").read().strip()
147 | if positions:
148 | [a, b] = [int(x) for x in positions.split("\n")] # line number
149 | posi_cov_list = os.popen("samtools depth " + bam + "|cut -f 2,3").read().strip().split('\n')
150 | posi_list = get_posi_by_depth(posi_cov_list[(a - 1):b], min_cov, w=5) # 1 based for sam
151 | print('# contig:{}, posi_list:{}'.format(i,posi_list))
152 | else:
153 | print("contig.{}.fa: no sequence satisfies the requirement of min coverage".format(i),
154 | file=open("{}/log".format(outdir), 'a'))
155 | open(out_fa, 'w').close() # new an empty file
156 | return
157 |
158 | contig="contig{}".format(i)
159 | seq = contig2seq[contig]
160 |
161 | sub_k = 1
162 | if trim_ends:
163 | for start, end, _ in posi_list:
164 | consensus = seq[(int(start) - 1):int(end)]
165 | if len(posi_list) == 1:
166 | head = ">c_{}\n".format(i)
167 | else:
168 | head = ">c_{}_sub{}\n".format(i, sub_k)
169 | with open(out_fa, 'a') as fw:
170 | fw.write(head + consensus + '\n')
171 | sub_k += 1
172 | else:
173 | # trim ends with low coverage and also break at the misassembled positions in the middle regions
174 | for start, end, _ in posi_list:
175 | if len(posi_list) == 1:
176 | consensus = seq[(int(start) - 1):int(end)]
177 | head = ">contig_{}\n".format(i)
178 | else:
179 | if sub_k == 1:
180 | consensus = seq[:int(end)]
181 | elif sub_k == len(posi_list):
182 | consensus = seq[(int(start) - 1):]
183 | else:
184 | consensus = seq[(int(start) - 1):int(end)]
185 | head = ">contig_{}_sub{}\n".format(i, sub_k)
186 | with open(outdir + '/contig.{}.sub{}.fa'.format(i, sub_k), 'w') as fw:
187 | fw.write(head + consensus + '\n')
188 | sub_k += 1
189 |
190 | return
191 |
192 |
193 | def clip_based_misasm_removal(read_fa, hap_fa, threads, outdir, min_clip_count):
194 | '''remove misassemblies based on clipped read alignments'''
195 | os.system("mkdir -p {}".format(outdir))
196 | sam = outdir + '/tmp.sam'
197 | min_clip_len = 5
198 |
199 | os.system(
200 | "minimap2 -a --secondary=no {} {} -t {}|samtools view -F 2048 - >{}".format(hap_fa, read_fa, threads, sam))
201 | hap2bpposi_tmp = {}
202 | hap2bpposi = {}
203 |
204 | with open(sam, 'r') as fr:
205 | for line in fr:
206 | a = line.split()
207 | hap, posi, cigar, seq = a[2], int(a[3]), a[5], a[9]
208 | read_len = len(seq)
209 | bp_posi = -1 # breakpoint position at target sequence
210 | # split cigar into list of numbers and characters all separately
211 | splitcigar = ["".join(x) for _, x in itertools.groupby(cigar, key=str.isdigit)] # 25S100M2S
212 | if splitcigar[1] == 'S': # soft-clipped, left
213 | if int(splitcigar[0]) < min_clip_len:
214 | if splitcigar[-1] == 'S' and int(splitcigar[-2]) >= min_clip_len:
215 | bp_posi = posi + read_len - int(splitcigar[-2]) # soft-clipped on both sides,such as 2S1000M50S
216 | else:
217 | continue
218 | else:
219 | bp_posi = posi
220 | elif splitcigar[-1] == 'S': # soft-clipped, right
221 | if int(splitcigar[-2]) < min_clip_len:
222 | continue
223 | else:
224 | bp_posi = posi + read_len - int(splitcigar[-2])
225 | else:
226 | continue
227 | if hap in hap2bpposi_tmp:
228 | hap2bpposi_tmp[hap].append(bp_posi)
229 | else:
230 | hap2bpposi_tmp[hap] = [bp_posi]
231 |
232 | for hap, posi_list in hap2bpposi_tmp.items():
233 | posi2count = {}
234 | for posi in posi_list:
235 | if posi in posi2count:
236 | posi2count[posi] += 1
237 | else:
238 | posi2count[posi] = 1
239 | for posi, count in posi2count.items():
240 | if count >= min_clip_count:
241 | print("## posi, count:{},{}".format(posi,count))
242 | if hap in hap2bpposi:
243 | hap2bpposi[hap].append(posi)
244 | else:
245 | hap2bpposi[hap] = [posi]
246 |
247 | hap2bpposi = {hap: sorted(posi_list) for hap, posi_list in hap2bpposi.items()}
248 | print('## haplotype to breakpoint position: {}'.format(hap2bpposi))
249 | hap=''
250 | out_info=[]
251 | i=0
252 | with open(hap_fa) as fr:
253 | for line in fr:
254 | sub_seqs=[]
255 | if line.startswith('>'):
256 | hap=line.strip()[1:]
257 | else:
258 | seq=line.strip()
259 | start=0
260 | if hap not in hap2bpposi:
261 | i+=1
262 | out_info.append('>hap_'+str(i)+'\n'+seq+'\n')
263 | continue
264 | for bp_posi in hap2bpposi[hap]:
265 | sub_seq = seq[start:(bp_posi-1)]
266 | sub_seqs.append(sub_seq)
267 | start=bp_posi-1
268 |
269 | sub_seqs.append(seq[start:]) #last sub sequence
270 | for s in sub_seqs:
271 | if len(s)<500: #filter short sequences
272 | continue
273 | i+=1
274 | out_info.append('>hap_' + str(i)+'\n'+s+'\n')
275 |
276 | with open(outdir+'/haplotypes.final.fasta','w') as fw:
277 | fw.write(''.join(out_info))
278 | return
279 |
280 |
281 |
282 |
283 | if __name__ == '__main__':
284 | read_fa, contig_fa, outdir, threads, num_contigs= sys.argv[1:]
285 | min_cov=5
286 |
287 | contig2seq={}
288 | with open(contig_fa, 'r') as fr:
289 | for line in fr:
290 | if line.startswith('>'):
291 | contig = line.strip()[1:]
292 | else:
293 | contig2seq[contig] = line.strip()
294 |
295 | #map all corrected reads to all contigs
296 | os.system("mkdir -p {}".format(outdir))
297 | bam = outdir+'/reads2contigs.bam'
298 | os.system("minimap2 -a" + " --secondary=no -t " +threads +" "+ contig_fa + " " + read_fa + \
299 | " 2>/dev/null |samtools view -hS -F 2048 -|samtools sort -@ 8 - >" + bam)
300 | os.system("samtools index {}".format(bam))
301 |
302 |
303 | print('## reads alingment finished.')
304 | params=[]
305 | for i in range(int(num_contigs)):
306 | params.append((str(i), read_fa,bam, outdir, min_cov,1,False))
307 | # contig_fa = 'contig.{}.fa'.format(i)
308 | # cov_based_misasm_removal(str(i), read_fa, outdir, min_cov, threads=1)
309 | # clip_based_misasm_removal(read_fa,contig_fa , threads, outdir, min_clip_count=20)
310 | # clip_based_misasm_removal(read_fa, hap_fa, threads, outdir, min_clip_count=20)
311 | pool = Pool(int(threads))
312 | res = pool.map(cov_based_misasm_removal, params, chunksize=1)
313 |
314 | pool.close()
315 | pool.join()
--------------------------------------------------------------------------------
/src/rm_redundant_genomes.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | from itertools import combinations
4 | from multiprocessing import Pool
5 |
6 | '''This program is used to remove redundant genomes based on sequence divergence'''
7 |
8 |
9 | def fasta_len(fa):
10 | sum_len = 0
11 | with open(fa, 'r') as fr:
12 | for line in fr:
13 | if line.startswith('>'):
14 | continue
15 | else:
16 | sum_len += len(line.strip())
17 | return sum_len
18 |
19 |
20 | def cal_genome_divergence(param):
21 | ## Full genome/assembly alignment, intra-species asm-to-asm alignment
22 | fa1, fa2,max_local_divergence,maxCO = param
23 | paf_out = os.popen("minimap2 -cx asm20 -t 1 {} {} 2>/dev/null".format(fa1, fa2)).read().strip().split('\n')
24 | divergence = 1.0
25 | contained = 0 # if it is contained contig or not
26 |
27 | if not paf_out[0]:
28 | return (fa1, fa2, divergence, divergence,contained)
29 |
30 | matched_len = 0 # identical bases
31 | ovlp_len = 0 # including mismatches and gaps
32 | for i, line in enumerate(paf_out):
33 | a = line.split('\t')
34 | matched_len += int(a[9])
35 | ovlp_len += int(a[10])
36 | fa1_len = fasta_len(fa1)
37 | fa2_len = fasta_len(fa2)
38 |
39 | # number of bases which are covered in fa1 or fa2, which can be also obtained from paf file
40 | # this may be != fa1_len - ovlp_len (because of indels in overlap)
41 | # and != fa1_len - matched_len (because of mismatch bases not involved in matched_len)
42 | fa1_uniq_ovlplen = os.popen("minimap2 -ax asm20 -t 1 {} {} 2>/dev/null|samtools sort - |samtools depth -|wc -l".
43 | format(fa1, fa2)).read().strip()
44 | fa2_uniq_ovlplen = os.popen("minimap2 -ax asm20 -t 1 {} {} 2>/dev/null|samtools sort - |samtools depth -|wc -l".
45 | format(fa2, fa1)).read().strip()
46 | fa1_uniq_ovlplen = int(fa1_uniq_ovlplen)
47 | fa2_uniq_ovlplen = int(fa2_uniq_ovlplen)
48 | # global_divergence = 1 - matched / (similar+different)
49 | global_divergence = round(1 - matched_len / (ovlp_len + fa1_len - fa1_uniq_ovlplen + fa2_len - fa2_uniq_ovlplen), 4)
50 | local_divergence = round(1 - matched_len / ovlp_len, 4) # only consider the overlap regions
51 |
52 | # Discard contained contigs
53 | fa1_oh = fa1_len - ovlp_len # general overhang length of fa1
54 | fa2_oh = fa2_len - ovlp_len
55 | # min_oh = 5, replaced with maxCO, maximum overhang len for contained contigs
56 | # max_local_divergence = 0.001 #pacbio clr
57 | # max_local_divergence = 0.01 #for test, maybe for ont TODO
58 | if fa1_oh <= maxCO and local_divergence < max_local_divergence:
59 | contained = 1 # fa1 is contained contig
60 | elif fa2_oh <= maxCO and local_divergence < max_local_divergence:
61 | contained = 2
62 |
63 | return (fa1, fa2, global_divergence, local_divergence, contained)
64 |
65 |
66 | if __name__ == '__main__':
67 | fa_list_file, max_global_divergence, outdir, threads,max_local_divergence,maxCO = sys.argv[1:]
68 | max_global_divergence = float(max_global_divergence)
69 | max_local_divergence = float(max_local_divergence)
70 | maxCO = int(maxCO)
71 | fa_list = []
72 | with open(fa_list_file) as fr:
73 | for line in fr:
74 | fa_list.append(line.strip())
75 |
76 | final_fastas = {fa: 1 for fa in fa_list} # the final fasta files after removing redundant genomes
77 | # print(final_fastas)
78 | div_out = []
79 | params = [(fa1, fa2,max_local_divergence,maxCO) for fa1, fa2 in combinations(fa_list, 2)]
80 |
81 | pool = Pool(int(threads))
82 | res = pool.map(cal_genome_divergence, params, chunksize=1) # ordered
83 | pool.close()
84 | pool.join()
85 |
86 | for line in res:
87 | # print('line:{}'.format(line))
88 | fa1, fa2, global_divergence, local_divergence, contained = line
89 | div_out.append('\t'.join([fa1, fa2, str(global_divergence), str(local_divergence), str(contained)]))
90 | if contained == 1:
91 | if fa1 in final_fastas:
92 | del final_fastas[fa1]
93 | elif contained == 2:
94 | if fa2 in final_fastas:
95 | del final_fastas[fa2]
96 | elif global_divergence < max_global_divergence:
97 | if fasta_len(fa1) > fasta_len(fa2):
98 | if fa2 in final_fastas:
99 | del final_fastas[fa2]
100 | else:
101 | if fa1 in final_fastas:
102 | del final_fastas[fa1]
103 |
104 | with open(outdir + '/haplotypes_divergence.txt', 'w') as fw:
105 | fw.write('\n'.join(div_out) + '\n')
106 |
107 | i = 1
108 | with open(outdir + '/haplotypes.fa', 'w') as fw:
109 | for fa in final_fastas.keys():
110 | with open(fa) as fr:
111 | for line in fr:
112 | if line.startswith('>'):
113 | continue
114 | else:
115 | if line.strip():
116 | fw.write('>strain_{}\n'.format(i))
117 | fw.write(line)
118 | i += 1
119 |
--------------------------------------------------------------------------------
/src/sort_reads.py:
--------------------------------------------------------------------------------
1 | '''
2 | This script is used to sort long reads by read length and their overlaps,
3 | and unify the strand which all reads are from.
4 | '''
5 | import os
6 | import sys
7 | # import networkx as nx
8 |
9 | from filter_ovlps import filter_ovlp
10 |
11 |
12 | def sort_reads_by_len(in_fa, outdir, top_k):
13 | id2seq = {}
14 | id = ''
15 |
16 | with open(in_fa) as fr:
17 | for line in fr:
18 | if line.startswith('>'):
19 | id = line.strip()
20 | else:
21 | seq = line.strip()
22 | id2seq[id] = [seq, len(seq)]
23 |
24 | out_fa = outdir + '/' + '.'.join(os.path.basename(in_fa).split('.')[:-1]) + '.top' + str(top_k) + '.fa'
25 | fw = open(out_fa, 'w')
26 | i = 0
27 | for id, val in sorted(id2seq.items(), key=lambda d: d[1][1], reverse=True):
28 | i += 1
29 | if i <= top_k:
30 | fw.write(id + '\n' + val[0] + '\n')
31 | return out_fa
32 |
33 |
34 | def cal_overlap(fasta, outdir, platform, threads, filter=True, min_ovlp_len=500, min_identity=0.0, o=200, r=0.8):
35 | '''
36 | calculate the overlaps of long reads
37 | '''
38 | paf = outdir + '/' + '.'.join(os.path.basename(fasta).split('.')[:-1]) + '.paf'
39 | filtered_paf = outdir + '/' + '.'.join(os.path.basename(fasta).split('.')[:-1]) + '.filtered.paf'
40 | if platform == 'pb': # TODO: -c is necessary or not?
41 | # minimap = "minimap2 -x ava-pb -Hk19 -Xw5 -m100 -g10000 --max-chain-skip 25 " + \
42 | # "-t %s %s %s |cut -f 1-12 |fpa drop -i -m >%s" % (threads, fasta, fasta, paf)
43 |
44 | minimap = "minimap2 -x ava-pb -Hk19 -Xw5 -m100 -g10000 --max-chain-skip 25 -t {} \
45 | {} {} 2>/dev/null |cut -f 1-12 |awk '$11>={} && $10/$11 >={} ' |fpa drop -i -m >{}" \
46 | .format(threads, fasta, fasta, min_ovlp_len, min_identity, paf)
47 |
48 | elif platform == 'ont':
49 | # minimap = "minimap2 -x ava-ont -k15 -Xw5 -m100 -g10000 -r2000 --max-chain-skip 25 " + \
50 | # "-t %s %s %s |cut -f 1-12 |fpa drop -i -m >%s" % (threads, fasta, fasta, paf)
51 | minimap = "minimap2 -x ava-ont -k15 -Xw5 -m100 -g10000 -r2000 --max-chain-skip 25 -t {} \
52 | {} {} 2>/dev/null |cut -f 1-12 |awk '$11>={} && $10/$11 >={} ' |fpa drop -i -m >{}" \
53 | .format(threads, fasta, fasta, min_ovlp_len, min_identity, paf)
54 | else:
55 | raise Exception('wrong platform for reads type: pb/ont')
56 | os.system(minimap)
57 | if filter:
58 | filter_ovlp(paf, filtered_paf, min_ovlp_len, min_identity, o, r)
59 | return filtered_paf
60 | return paf
61 |
62 |
63 | def count_lost_reads(fa, paf):
64 | num_reads = int(os.popen('cat {}|grep ">"|wc -l'.format(fa)).read())
65 | reads_in_ovlps = {}
66 | with open(paf) as fr:
67 | for line in fr:
68 | a = line.split()
69 | reads_in_ovlps[a[0]] = 1
70 | reads_in_ovlps[a[5]] = 1
71 | print('\n\nraw reads: {}, {} reads in filtered overlaps\n'.format(num_reads, len(reads_in_ovlps)))
72 | return num_reads, len(reads_in_ovlps)
73 |
74 |
75 | def reverse_comp(seq):
76 | base2comp = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'N': 'N',
77 | 'a': 't', 't': 'a', 'g': 'c', 'c': 'g', 'n': 'n'}
78 | rev_seq = seq[::-1]
79 | rev_comp_seq = ''.join([base2comp[base] for base in rev_seq])
80 | return rev_comp_seq
81 |
82 |
83 | def paf2graph(paf):
84 | edges = []
85 | with open(paf) as fr:
86 | for line in fr:
87 | a = line.strip().split()
88 | edges.append((a[0], a[5]))
89 | G = nx.Graph()
90 | G.add_edges_from(edges)
91 | return G
92 |
93 |
94 | def sort_reads_by_ovlps(fa, paf, outdir, by_length):
95 | '''sort reads by length, keep the next read has overlap with the previous reads
96 | and unify the strand of all reads, assume '+'
97 | '''
98 | out_fa = outdir + '/' + '.'.join(os.path.basename(fa).split('.')[:-1]) + '.sorted.fa'
99 | if os.path.getsize(paf) == 0:
100 | os.system('cp {} {}'.format(fa,out_fa))
101 | return out_fa
102 |
103 | fw = open(out_fa, 'w')
104 | rr2strand = {} # {read_i} {read_j} = '+'
105 | with open(paf, 'r') as fr:
106 | for line in fr:
107 | a = line.split()
108 | rr2strand.setdefault(a[0], {})[a[5]] = a[4]
109 | rr2strand.setdefault(a[5], {})[a[0]] = a[4]
110 |
111 | i = 0
112 | read2strand = {}
113 | used_reads = {}
114 | read2seq = {}
115 | first_read = ''
116 | with open(fa) as fr:
117 | read = ''
118 | for line in fr:
119 | if line.startswith('>'):
120 | i += 1
121 | read = line.strip().split()[0][1:]
122 | if i == 1:
123 | first_read = read
124 | read2strand[first_read] = '+'
125 | else:
126 | seq = line.strip()
127 | read2seq[read] = [seq, len(seq)]
128 |
129 | # output the first read info
130 | fw.write('>' + first_read + '\n' + read2seq[first_read][0] + '\n')
131 |
132 | used_reads[first_read] = 1
133 | reverse = 0 # count number of reads which need to reverse_complement
134 | read_i = 1
135 | next_read = first_read
136 | neighbors = {}
137 | neighbors[next_read] = 1
138 | while True:
139 | read_i += 1
140 | if read_i % 1000 == 0:
141 | print('processing the {} read...'.format(read_i))
142 |
143 | for r in rr2strand[next_read].keys():
144 | if r not in used_reads:
145 | neighbors[r] = 1
146 | del neighbors[next_read]
147 | # sort neighbor reads by length
148 | if by_length:
149 | if len(neighbors) > 0:
150 | next_read = sorted(neighbors.keys(), key=lambda r: read2seq[r][1], reverse=True)[0]
151 | else:
152 | raise Exception('No overlap found for read because the overlap graph is not connected !')
153 | else:
154 | for read in neighbors.keys():
155 | next_read = read
156 | break
157 |
158 | # check strand of reads
159 | for used_read in used_reads.keys():
160 | if used_read in rr2strand[next_read]:
161 | ovlp_strand = rr2strand[next_read][used_read]
162 | if read2strand[used_read] == '+':
163 | if ovlp_strand == '+':
164 | read2strand[next_read] = '+'
165 | else:
166 | read2strand[next_read] = '-'
167 | elif read2strand[used_read] == '-':
168 | if ovlp_strand == '+':
169 | read2strand[next_read] = '-'
170 | else:
171 | read2strand[next_read] = '+'
172 | break
173 | # TODO: check strand conflicts ?
174 |
175 | if read2strand[next_read] == '+':
176 | fw.write('>' + next_read + '\n' + read2seq[next_read][0] + '\n')
177 | elif read2strand[next_read] == '-':
178 | reverse += 1
179 | fw.write('>' + next_read + '\n' + reverse_comp(read2seq[next_read][0]) + '\n')
180 | else:
181 | raise Exception('Wrong read strand found: {}'.format(read2strand[next_read]))
182 | used_reads[next_read] = 1
183 | if len(used_reads) == len(rr2strand): # all reads in overlap file are visited
184 | break
185 | fw.close()
186 | print('number of reverse_complement reads: {}'.format(reverse))
187 | return out_fa
188 |
189 |
190 | if __name__ == '__main__':
191 | # fa = 'data/hiv/reads.fa'
192 | # outdir = 'data/hiv'
193 | # top_k=100
194 | fa, outdir, top_k, by_length, platform = sys.argv[1:]
195 | top_fa = sort_reads_by_len(fa, outdir, int(top_k))
196 |
197 | #mean read length=2.4kb, min_ovlp_len=400 in the first version
198 | paf = cal_overlap(top_fa, outdir, platform, threads=40, filter=True, min_ovlp_len=1000,
199 | min_identity=0.1, o=400, r=0.8)
200 | count_lost_reads(top_fa, paf)
201 |
202 | # check if overlap graph is connected TODO: add a reference as the first read ?
203 | # G = paf2graph(paf)
204 | # if nx.is_connected(G):
205 | # print('The overlap graph is connected.')
206 | # else:
207 | # n = nx.algorithms.components.number_connected_components(G)
208 | # print('The overlap graph is not connected and has {} components,\n'
209 | # 'Refiltering overlaps with more relaxed threshold is recommended.\n\n'.format(n))
210 |
211 | # run anyway
212 | sort_reads_by_ovlps(top_fa, paf, outdir, int(by_length))
213 |
--------------------------------------------------------------------------------
/src/strainline.only_iter.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | #Prints a help message
6 | function print_help() {
7 | echo "Usage: $0 [options] -i reads.fasta -o out/ -p sequencingPlatform"
8 | echo ""
9 | echo "Full-length De Novo Viral Haplotype Reconstruction from Noisy Long Reads"
10 | echo ""
11 | echo "Author: Xiao Luo"
12 | echo "Date: Mar 2021"
13 | echo ""
14 | echo " Input:"
15 | echo " reads.fasta: fasta file of input long reads."
16 | echo " out/: directory where to output the results."
17 | echo " sequencingPlatform: long read sequencing platform: PacBio (-p pb) or Oxford Nanopore (-p ont)"
18 | echo ""
19 | echo " Options:"
20 | echo " --minTrimmedLen INT: Minimum trimmed read length. (default: 1000)"
21 | echo " --topk INT, -k INT: Choose top k seed reads. (default: 50)"
22 | echo " --minOvlpLen INT: Minimum read overlap length. (default: 1000)"
23 | echo " --minIdentity FLOAT: Minimum identity of overlaps. (default: 0.99)"
24 | echo " --minSeedLen INT: Minimum seed read length. (default: 3000)"
25 | echo " --maxOH INT: Maximum overhang length allowed for overlaps. (default: 30)"
26 | echo " --iter INT: Number of iterations for contig extension. (default: 2)"
27 | echo " --from INT: From this iteration for further contig extension. (default: 2)"
28 | echo " --maxGD FLOAT: Maximum global divergence allowed for merging haplotypes. (default: 0.01)"
29 | echo " --maxLD FLOAT: Maximum local divergence allowed for merging haplotypes. (default: 0.001)"
30 | echo " --maxCO INT: Maximum overhang length allowed for contig contains. (default: 5)"
31 | # echo " --perIdentity INT: Percent identity for haplotype abundacne computation. (default: 97)"
32 | echo " --minAbun FLOAT: Minimum abundance for filtering haplotypes (default: 0.02)"
33 | echo " --rmMisassembly BOOL: Break contigs at potential misassembled positions (default: False)"
34 | echo " --correctErr BOOL: Perform error correction for input reads (default: True)"
35 | echo " --threads INT, -t INT: Number of processes to run in parallel (default: 8)."
36 | echo " --help, -h: Print this help message."
37 | exit 1
38 | }
39 |
40 | #Set options to default values
41 | input_fa=""
42 | threads=8
43 | outdir="out/"
44 |
45 | min_trimmed_len=1000
46 |
47 | topk=50
48 | platform="pb"
49 | min_ovlp_len=1000
50 | min_identity=0.99
51 | o=30
52 | r=0.8
53 | #max_ovlps=10000 #TODO,reads are already corrected, so maybe use 1000?
54 | max_ovlps=1000
55 | min_sread_len=3000
56 |
57 | iter=2
58 | max_global_divergence=0.01
59 |
60 | #TODO: add if else
61 | max_local_divergence=0.001 #for CLR, 0.01 for ONT. #SARS-CoV-2 / (5-HIV different depth) results in paper use 0.01,
62 | maxCO=5
63 |
64 | percent_identity=97
65 | min_abun=0.02 #
66 | rm_misassembly="False"
67 | correct_err="True"
68 |
69 | #Print help if no argument specified
70 | if [[ "$1" == "" ]]; then
71 | print_help
72 | fi
73 |
74 | #Options handling
75 | while [[ "$1" != "" ]]; do
76 | case "$1" in
77 | "--help" | "-h")
78 | print_help
79 | ;;
80 | "-i")
81 | case "$2" in
82 | "")
83 | echo "Error: $1 expects an argument"
84 | exit 1
85 | ;;
86 | *)
87 | input_fa="$2"
88 | shift 2
89 | ;;
90 | esac
91 | ;;
92 | "-o")
93 | case "$2" in
94 | "")
95 | echo "Error: $1 expects an argument"
96 | exit 1
97 | ;;
98 | *)
99 | outdir="$2"
100 | shift 2
101 | ;;
102 | esac
103 | ;;
104 | "-p")
105 | case "$2" in
106 | "")
107 | echo "Error: $1 expects an argument"
108 | exit 1
109 | ;;
110 | *) if [[ "$2" == "pb" ]]; then
111 | platform="pb"
112 | shift 2
113 | elif [[ "$2" == "ont" ]]; then
114 | platform="ont"
115 | shift 2
116 | else
117 | echo "Error: $1 must be either pb or ont"
118 | exit 1
119 | fi ;;
120 | esac
121 | ;;
122 | "--minTrimmedLen")
123 | case "$2" in
124 | "")
125 | echo "Error: $1 expects an argument"
126 | exit 1
127 | ;;
128 | *)
129 | min_trimmed_len="$2"
130 | shift 2
131 | ;;
132 | esac
133 | ;;
134 | "--topk" | "-k")
135 | case "$2" in
136 | "")
137 | echo "Error: $1 expects an argument"
138 | exit 1
139 | ;;
140 | *)
141 | topk="$2"
142 | shift 2
143 | ;;
144 | esac
145 | ;;
146 | "--minOvlpLen")
147 | case "$2" in
148 | "")
149 | echo "Error: $1 expects an argument"
150 | exit 1
151 | ;;
152 | *)
153 | min_ovlp_len="$2"
154 | shift 2
155 | ;;
156 | esac
157 | ;;
158 | "--minIdentity")
159 | case "$2" in
160 | "")
161 | echo "Error: $1 expects an argument"
162 | exit 1
163 | ;;
164 | *)
165 | min_identity="$2"
166 | shift 2
167 | ;;
168 | esac
169 | ;;
170 | "--minSeedLen")
171 | case "$2" in
172 | "")
173 | echo "Error: $1 expects an argument"
174 | exit 1
175 | ;;
176 | *)
177 | min_sread_len="$2"
178 | shift 2
179 | ;;
180 | esac
181 | ;;
182 | "--maxOH")
183 | case "$2" in
184 | "")
185 | echo "Error: $1 expects an argument"
186 | exit 1
187 | ;;
188 | *)
189 | o="$2"
190 | shift 2
191 | ;;
192 | esac
193 | ;;
194 | "--iter")
195 | case "$2" in
196 | "")
197 | echo "Error: $1 expects an argument"
198 | exit 1
199 | ;;
200 | *)
201 | iter="$2"
202 | shift 2
203 | ;;
204 | esac
205 | ;;
206 | "--from")
207 | case "$2" in
208 | "")
209 | echo "Error: $1 expects an argument"
210 | exit 1
211 | ;;
212 | *)
213 | from="$2"
214 | shift 2
215 | ;;
216 | esac
217 | ;;
218 | "--maxGD")
219 | case "$2" in
220 | "")
221 | echo "Error: $1 expects an argument"
222 | exit 1
223 | ;;
224 | *)
225 | max_global_divergence="$2"
226 | shift 2
227 | ;;
228 | esac
229 | ;;
230 | "--maxLD")
231 | case "$2" in
232 | "")
233 | echo "Error: $1 expects an argument"
234 | exit 1
235 | ;;
236 | *)
237 | max_local_divergence="$2"
238 | shift 2
239 | ;;
240 | esac
241 | ;;
242 | "--maxCO")
243 | case "$2" in
244 | "")
245 | echo "Error: $1 expects an argument"
246 | exit 1
247 | ;;
248 | *)
249 | maxCO="$2"
250 | shift 2
251 | ;;
252 | esac
253 | ;;
254 | "--minAbun")
255 | case "$2" in
256 | "")
257 | echo "Error: $1 expects an argument"
258 | exit 1
259 | ;;
260 | *)
261 | min_abun="$2"
262 | shift 2
263 | ;;
264 | esac
265 | ;;
266 | "--rmMisassembly")
267 | case "$2" in
268 | "")
269 | echo "Error: $1 expects an argument"
270 | exit 1
271 | ;;
272 | *)
273 | rm_misassembly="$2"
274 | shift 2
275 | ;;
276 | esac
277 | ;;
278 | "--correctErr")
279 | case "$2" in
280 | "")
281 | echo "Error: $1 expects an argument"
282 | exit 1
283 | ;;
284 | *)
285 | correct_err="$2"
286 | shift 2
287 | ;;
288 | esac
289 | ;;
290 | "--threads" | "-t")
291 | case "$2" in
292 | "")
293 | echo "Error: $1 expects an argument"
294 | exit 1
295 | ;;
296 | *)
297 | threads="$2"
298 | shift 2
299 | ;;
300 | esac
301 | ;;
302 | #
303 | --)
304 | shift
305 | break
306 | ;;
307 | *)
308 | echo "Error: invalid option \"$1\""
309 | exit 1
310 | ;;
311 | esac
312 | done
313 |
314 | #Exit if no input or no output files have been specified
315 | if [[ $input_fa == "" ]]; then
316 | echo "Error: -i must be specified"
317 | exit 1
318 | fi
319 |
320 | basepath=$(dirname $0)
321 |
322 | ##############################################
323 | ######## Step1: read error correction ########
324 | ##############################################
325 | #if [ ! -d $outdir ]; then
326 | # mkdir $outdir
327 | #else
328 | # echo Directory \'$outdir\' 'already exists, please use a new one, exiting...'
329 | # exit
330 | #fi
331 | mkdir -p $outdir
332 |
333 | input_fa=$(readlink -f $input_fa)
334 | cd $outdir || exit
335 |
336 | ln -fs $input_fa reads.fasta
337 |
338 | if [[ $correct_err == "True" ]];then
339 | fasta2DAM reads.dam reads
340 | DBsplit -s256 -x$min_trimmed_len reads.dam # -x: Trimmed DB has reads >= this threshold.
341 | mkdir tmp || exit
342 | #HPC.daligner reads.dam -T$threads | bash #return core-dump error if using all cores
343 | HPC.daligner reads.dam -e0.85 -P./tmp -T$threads | bash
344 | # daccord -t$threads reads.las reads.dam >corrected.0.fa
345 | touch corrected.0.fa
346 | for las_file in reads.*las;
347 | do
348 | daccord -t$threads $las_file reads.dam >>corrected.0.fa
349 | done
350 |
351 | echo 'Step1: read error correction. Finished.'
352 | else
353 | echo 'Skip Step1, do not perform error correction.'
354 | fi
355 |
356 | ##############################################
357 | ########### Step2: read clustering ###########
358 | ##############################################
359 |
360 | for ((i = $from; i < $iter; i++)); do
361 | let j=$i+1
362 | mkdir -p iter$j
363 | #reformat fasta
364 | python $basepath/reformat_fa.py corrected.$i.fa corrected.$i.reformat.fa
365 | python $basepath/clustering.py corrected.$i.reformat.fa ./iter$j/ $topk $platform $threads $min_ovlp_len $min_identity $o $r $max_ovlps $min_sread_len
366 | cat ./iter$j/contig.*.fa | perl -ne 'if (/^>/){print ">r$.\n";}else{print;}' >corrected.$j.fa
367 | done
368 |
369 | python $basepath/reformat_fa.py corrected.$j.fa contigs.fa
370 |
371 | ##############################################
372 | #### Step3: redundant haplotypes removal #####
373 | ##############################################
374 |
375 | ls ./iter$j/contig.*.fa >contig_list.txt
376 |
377 | fa_list_file=contig_list.txt
378 |
379 | #generate 'haplotypes.fa'
380 | python $basepath/rm_redundant_genomes.py $fa_list_file $max_global_divergence . $threads $max_local_divergence $maxCO
381 |
382 |
383 | #optional ,remove misassembly
384 | if [[ $rm_misassembly == "True" ]]; then
385 | cat haplotypes.fa|perl -ne 'BEGIN{$head;$i=0;}if(/^>/){$head=">contig$i";}else{if (length($_) >1000){print "$head\n$_";$i+=1;} }' >tmp.fa
386 | num_contig=`cat tmp.fa |grep ">"|wc -l`
387 | fa_read=corrected.0.fa #corrected reads
388 | python $basepath/rm_misassembly.py $fa_read tmp.fa rmMisassemly $threads $num_contig
389 | cat rmMisassemly/contig.*.fa >haplotypes.rm_misassembly.redundant.fa
390 |
391 | #remove redundant contigs again because some non-redundant contigs may be caused by misassembly
392 | ls rmMisassemly/contig.*.fa >contig_list.txt2
393 | python $basepath/rm_redundant_genomes.py contig_list.txt2 $max_global_divergence . $threads $max_local_divergence $maxCO
394 | cp haplotypes.fa haplotypes.rm_misassembly.fa
395 | elif [[ $rm_misassembly == "False" ]]; then
396 | cp haplotypes.fa haplotypes.rm_misassembly.fa
397 | else
398 | echo "invalid value for --rmMisassembly, should be either True or False."
399 | exit 1
400 | fi
401 |
402 | ##############################################
403 | ### Step4: low frequent haplotypes removal ###
404 | ##############################################
405 | export min_abundance=$min_abun
406 |
407 | mkdir -p filter_by_abun
408 | cd filter_by_abun || exit
409 | fa_read=../corrected.0.fa #corrected reads
410 |
411 | for i in {1..2};
412 | do
413 | if [[ $i == 1 ]];then
414 | cat ../haplotypes.rm_misassembly.fa | perl -ne 'BEGIN{$i=1;}if(/^>/){print ">contig_$i\n";$i+=1;}else{print;}' >haps.fa
415 | else
416 | cat haplotypes.final.fa | perl -ne 'BEGIN{$i=1;}if(/^>/){print ">contig_$i\n";$i+=1;}else{print;}' >haps.fa
417 | fi
418 | minimap2 -a --secondary=no -t $threads haps.fa $fa_read | samtools view -F 3584 -b -t $threads | samtools sort - >haps.bam
419 |
420 | jgi_summarize_bam_contig_depths haps.bam --percentIdentity $percent_identity --outputDepth haps.depth
421 |
422 | perl -e 'open A,"haps.depth";;my$alldepth=0;while(){my@a=split;$alldepth+=$a[2];}close A; \
423 | open A,"haps.depth";;while(){my@a=split;my$d=$a[2]/$alldepth;print "$a[0]\t$a[1]\t$a[2]\t$d\n";}close A; ' |
424 | sort -k4nr >haps.depth.sort
425 |
426 | perl -e ' my%id2seq;$/=">";open A,"haps.fa";;while(){chomp;my@a=split;$id2seq{$a[0]}=$a[1];}close A;
427 | $/="\n"; open A,"haps.depth.sort";my$k=0;while(){chomp;my@a=split;next if $a[-1]<$ENV{"min_abundance"};
428 | my$abun=sprintf "%.3f",$a[-1];my$cov=sprintf "%.0f",$a[-2]; $k+=1;print ">hap$k $cov"."x freq=$abun\n$id2seq{$a[0]}\n";}close A; ' >haplotypes.final.fa
429 | done
430 | #TODO, after filtering, is it necessary to recompute the abundance of haplotypes ? yes, see for loop
431 |
432 |
433 | ## Done ##
434 | cd ..
435 | ln -fs ./filter_by_abun/haplotypes.final.fa .
436 | echo 'All steps finished successfully.'
437 | echo 'The final haplotypes and their relative abundances are saved here: '$outdir'/haplotypes.final.fa'
438 |
--------------------------------------------------------------------------------
/src/strainline.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -e
4 |
5 | #Prints a help message
6 | function print_help() {
7 | echo "Usage: $0 [options] -i reads.fasta -o out/ -p sequencingPlatform"
8 | echo ""
9 | echo "Full-length De Novo Viral Haplotype Reconstruction from Noisy Long Reads"
10 | echo ""
11 | echo "Author: Xiao Luo"
12 | echo "Date: Mar 2021"
13 | echo ""
14 | echo " Input:"
15 | echo " reads.fasta: fasta file of input long reads."
16 | echo " out/: directory where to output the results."
17 | echo " sequencingPlatform: long read sequencing platform: PacBio (-p pb) or Oxford Nanopore (-p ont)"
18 | echo ""
19 | echo " Options:"
20 | echo " --minTrimmedLen INT: Minimum trimmed read length. (default: 1000)"
21 | echo " --topk INT, -k INT: Choose top k seed reads. (default: 100)"
22 | echo " --minOvlpLen INT: Minimum read overlap length. (default: 1000)"
23 | echo " --minIdentity FLOAT: Minimum identity of overlaps. (default: 0.99)"
24 | echo " --minSeedLen INT: Minimum seed read length. (default: 3000)"
25 | echo " --maxOH INT: Maximum overhang length allowed for overlaps. (default: 30)"
26 | echo " --iter INT: Number of iterations for contig extension. (default: 2)"
27 | echo " --maxGD FLOAT: Maximum global divergence allowed for merging haplotypes. (default: 0.01)"
28 | echo " --maxLD FLOAT: Maximum local divergence allowed for merging haplotypes. (default: 0.001)"
29 | echo " --maxCO INT: Maximum overhang length allowed for contig contains. (default: 5)"
30 | # echo " --perIdentity INT: Percent identity for haplotype abundacne computation. (default: 97)"
31 | echo " --minAbun FLOAT: Minimum abundance for filtering haplotypes (default: 0.02)"
32 | echo " --rmMisassembly BOOL: Break contigs at potential misassembled positions (default: False)"
33 | echo " --correctErr BOOL: Perform error correction for input reads (default: True)"
34 | echo " --dsim FLOAT: Look for alignments with this percent similarity in Daligner. (default: 0.85)"
35 | echo " --threads INT, -t INT: Number of processes to run in parallel (default: 8)."
36 | echo " --help, -h: Print this help message."
37 | exit 1
38 | }
39 |
40 | #Set options to default values
41 | input_fa=""
42 | threads=8
43 | outdir="out/"
44 |
45 | min_trimmed_len=1000
46 |
47 | topk=100
48 | platform="pb"
49 | min_ovlp_len=1000
50 | min_identity=0.99
51 | o=30
52 | r=0.8
53 | max_ovlps=1000
54 | min_sread_len=3000
55 |
56 | iter=2
57 | max_global_divergence=0.01
58 | max_local_divergence=0.001
59 | maxCO=5
60 |
61 | percent_identity=97
62 | min_abun=0.02 #
63 | rm_misassembly="False"
64 | correct_err="True"
65 | dsim=0.85
66 |
67 | #Print help if no argument specified
68 | if [[ "$1" == "" ]]; then
69 | print_help
70 | fi
71 |
72 | #Options handling
73 | while [[ "$1" != "" ]]; do
74 | case "$1" in
75 | "--help" | "-h")
76 | print_help
77 | ;;
78 | "-i")
79 | case "$2" in
80 | "")
81 | echo "Error: $1 expects an argument"
82 | exit 1
83 | ;;
84 | *)
85 | input_fa="$2"
86 | shift 2
87 | ;;
88 | esac
89 | ;;
90 | "-o")
91 | case "$2" in
92 | "")
93 | echo "Error: $1 expects an argument"
94 | exit 1
95 | ;;
96 | *)
97 | outdir="$2"
98 | shift 2
99 | ;;
100 | esac
101 | ;;
102 | "-p")
103 | case "$2" in
104 | "")
105 | echo "Error: $1 expects an argument"
106 | exit 1
107 | ;;
108 | *) if [[ "$2" == "pb" ]]; then
109 | platform="pb"
110 | shift 2
111 | elif [[ "$2" == "ont" ]]; then
112 | platform="ont"
113 | shift 2
114 | else
115 | echo "Error: $1 must be either pb or ont"
116 | exit 1
117 | fi ;;
118 | esac
119 | ;;
120 | "--minTrimmedLen")
121 | case "$2" in
122 | "")
123 | echo "Error: $1 expects an argument"
124 | exit 1
125 | ;;
126 | *)
127 | min_trimmed_len="$2"
128 | shift 2
129 | ;;
130 | esac
131 | ;;
132 | "--topk" | "-k")
133 | case "$2" in
134 | "")
135 | echo "Error: $1 expects an argument"
136 | exit 1
137 | ;;
138 | *)
139 | topk="$2"
140 | shift 2
141 | ;;
142 | esac
143 | ;;
144 | "--minOvlpLen")
145 | case "$2" in
146 | "")
147 | echo "Error: $1 expects an argument"
148 | exit 1
149 | ;;
150 | *)
151 | min_ovlp_len="$2"
152 | shift 2
153 | ;;
154 | esac
155 | ;;
156 | "--minIdentity")
157 | case "$2" in
158 | "")
159 | echo "Error: $1 expects an argument"
160 | exit 1
161 | ;;
162 | *)
163 | min_identity="$2"
164 | shift 2
165 | ;;
166 | esac
167 | ;;
168 | "--minSeedLen")
169 | case "$2" in
170 | "")
171 | echo "Error: $1 expects an argument"
172 | exit 1
173 | ;;
174 | *)
175 | min_sread_len="$2"
176 | shift 2
177 | ;;
178 | esac
179 | ;;
180 | "--maxOH")
181 | case "$2" in
182 | "")
183 | echo "Error: $1 expects an argument"
184 | exit 1
185 | ;;
186 | *)
187 | o="$2"
188 | shift 2
189 | ;;
190 | esac
191 | ;;
192 | "--iter")
193 | case "$2" in
194 | "")
195 | echo "Error: $1 expects an argument"
196 | exit 1
197 | ;;
198 | *)
199 | iter="$2"
200 | shift 2
201 | ;;
202 | esac
203 | ;;
204 | "--maxGD")
205 | case "$2" in
206 | "")
207 | echo "Error: $1 expects an argument"
208 | exit 1
209 | ;;
210 | *)
211 | max_global_divergence="$2"
212 | shift 2
213 | ;;
214 | esac
215 | ;;
216 | "--maxLD")
217 | case "$2" in
218 | "")
219 | echo "Error: $1 expects an argument"
220 | exit 1
221 | ;;
222 | *)
223 | max_local_divergence="$2"
224 | shift 2
225 | ;;
226 | esac
227 | ;;
228 | "--maxCO")
229 | case "$2" in
230 | "")
231 | echo "Error: $1 expects an argument"
232 | exit 1
233 | ;;
234 | *)
235 | maxCO="$2"
236 | shift 2
237 | ;;
238 | esac
239 | ;;
240 | "--minAbun")
241 | case "$2" in
242 | "")
243 | echo "Error: $1 expects an argument"
244 | exit 1
245 | ;;
246 | *)
247 | min_abun="$2"
248 | shift 2
249 | ;;
250 | esac
251 | ;;
252 | "--rmMisassembly")
253 | case "$2" in
254 | "")
255 | echo "Error: $1 expects an argument"
256 | exit 1
257 | ;;
258 | *)
259 | rm_misassembly="$2"
260 | shift 2
261 | ;;
262 | esac
263 | ;;
264 | "--correctErr")
265 | case "$2" in
266 | "")
267 | echo "Error: $1 expects an argument"
268 | exit 1
269 | ;;
270 | *)
271 | correct_err="$2"
272 | shift 2
273 | ;;
274 | esac
275 | ;;
276 | "--dsim")
277 | case "$2" in
278 | "")
279 | echo "Error: $1 expects an argument"
280 | exit 1
281 | ;;
282 | *)
283 | dsim="$2"
284 | shift 2
285 | ;;
286 | esac
287 | ;;
288 | "--threads" | "-t")
289 | case "$2" in
290 | "")
291 | echo "Error: $1 expects an argument"
292 | exit 1
293 | ;;
294 | *)
295 | threads="$2"
296 | shift 2
297 | ;;
298 | esac
299 | ;;
300 | #
301 | --)
302 | shift
303 | break
304 | ;;
305 | *)
306 | echo "Error: invalid option \"$1\""
307 | exit 1
308 | ;;
309 | esac
310 | done
311 |
312 | #Exit if no input or no output files have been specified
313 | if [[ $input_fa == "" ]]; then
314 | echo "Error: -i must be specified"
315 | exit 1
316 | fi
317 |
318 | basepath="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
319 |
320 | ##############################################
321 | ######## Step1: read error correction ########
322 | ##############################################
323 | #if [ ! -d $outdir ]; then
324 | # mkdir $outdir
325 | #else
326 | # echo Directory \'$outdir\' 'already exists, please use a new one, exiting...'
327 | # exit
328 | #fi
329 | mkdir -p $outdir
330 |
331 | input_fa=$(readlink -f $input_fa)
332 | cd $outdir || exit
333 |
334 | # ln -fs $input_fa reads.fasta
335 |
336 | # convert input fasta into wrapped fasta (60 bases per line)
337 | # to avoid issue: 'Fasta line is too long'
338 | perl -e ' $/=">";open A,$ARGV[0] or die $!; ;
339 | while(){chomp;my@a=split/\n/;print ">$a[0]\n";my$seq=join("",@a[1..$#a]);
340 | my$len=length($seq);my $L=int $len/60;$L+=1 if $L*60<$len;
341 | for(my$i=0;$i<$L;$i++){print substr($seq,$i*60,60);print "\n";}
342 | }close A;' $input_fa >reads.fasta
343 |
344 | if [[ $correct_err == "True" ]];then
345 | fasta2DAM reads.dam reads
346 | DBsplit -s256 -x$min_trimmed_len reads.dam # -x: Trimmed DB has reads >= this threshold.
347 | # mkdir tmp || exit
348 | # #HPC.daligner reads.dam -T$threads | bash #return core-dump error if using all cores
349 | # HPC.daligner reads.dam -e$dsim -P./tmp -T$threads | bash #only conda installed version support '-P'
350 | HPC.daligner reads.dam -e$dsim -T$threads -l$min_ovlp_len | bash
351 | # HPC.daligner reads.dam -e0.85 -T$threads | bash
352 | # daccord -t$threads reads.las reads.dam >corrected.0.fa
353 | touch corrected.0.fa
354 | for las_file in reads.*las;
355 | do
356 | daccord -t$threads $las_file reads.dam >>corrected.0.fa
357 | done
358 |
359 | echo 'Step1: read error correction. Finished.'
360 | else
361 | echo 'Skip Step1, do not perform error correction.'
362 | fi
363 |
364 | ##############################################
365 | ########### Step2: read clustering ###########
366 | ##############################################
367 |
368 | for ((i = 0; i < $iter; i++)); do
369 | let j=$i+1
370 | mkdir -p iter$j
371 | #reformat fasta
372 | python $basepath/reformat_fa.py corrected.$i.fa corrected.$i.reformat.fa
373 | python $basepath/clustering.py corrected.$i.reformat.fa ./iter$j/ $topk $platform $threads $min_ovlp_len $min_identity $o $r $max_ovlps $min_sread_len
374 | cat ./iter$j/contig.*.fa | perl -ne 'if (/^>/){print ">r$.\n";}else{print;}' >corrected.$j.fa
375 | done
376 |
377 | python $basepath/reformat_fa.py corrected.$j.fa contigs.fa
378 |
379 | ##############################################
380 | #### Step3: redundant haplotypes removal #####
381 | ##############################################
382 |
383 | ls ./iter$j/contig.*.fa >contig_list.txt
384 |
385 | fa_list_file=contig_list.txt
386 |
387 | #generate 'haplotypes.fa'
388 | python $basepath/rm_redundant_genomes.py $fa_list_file $max_global_divergence . $threads $max_local_divergence $maxCO
389 |
390 |
391 | #optional ,remove misassembly
392 | if [[ $rm_misassembly == "True" ]]; then
393 | cat haplotypes.fa|perl -ne 'BEGIN{$head;$i=0;}if(/^>/){$head=">contig$i";}else{if (length($_) >1000){print "$head\n$_";$i+=1;} }' >tmp.fa
394 | num_contig=`cat tmp.fa |grep ">"|wc -l`
395 | fa_read=corrected.0.fa #corrected reads
396 | python $basepath/rm_misassembly.py $fa_read tmp.fa rmMisassemly $threads $num_contig
397 | cat rmMisassemly/contig.*.fa >haplotypes.rm_misassembly.redundant.fa
398 |
399 | #remove redundant contigs again because some non-redundant contigs may be caused by misassembly
400 | ls rmMisassemly/contig.*.fa >contig_list.txt2
401 | python $basepath/rm_redundant_genomes.py contig_list.txt2 $max_global_divergence . $threads $max_local_divergence $maxCO
402 | cp haplotypes.fa haplotypes.rm_misassembly.fa
403 | elif [[ $rm_misassembly == "False" ]]; then
404 | cp haplotypes.fa haplotypes.rm_misassembly.fa
405 | else
406 | echo "invalid value for --rmMisassembly, should be either True or False."
407 | exit 1
408 | fi
409 |
410 | ##############################################
411 | ### Step4: low frequent haplotypes removal ###
412 | ##############################################
413 | export min_abundance=$min_abun
414 |
415 | mkdir -p filter_by_abun
416 | cd filter_by_abun || exit
417 | fa_read=../corrected.0.fa #corrected reads
418 |
419 | for i in {1..2};
420 | do
421 | if [[ $i == 1 ]];then
422 | cat ../haplotypes.rm_misassembly.fa | perl -ne 'BEGIN{$i=1;}if(/^>/){print ">contig_$i\n";$i+=1;}else{print;}' >haps.fa
423 | else
424 | cat haplotypes.final.fa | perl -ne 'BEGIN{$i=1;}if(/^>/){print ">contig_$i\n";$i+=1;}else{print;}' >haps.fa
425 | fi
426 | minimap2 -a --secondary=no -t $threads haps.fa $fa_read | samtools view -F 3584 -b -t $threads | samtools sort - >haps.bam
427 |
428 | jgi_summarize_bam_contig_depths haps.bam --percentIdentity $percent_identity --outputDepth haps.depth
429 |
430 | perl -e 'open A,"haps.depth";;my$alldepth=0;while(){my@a=split;$alldepth+=$a[2];}close A; \
431 | open A,"haps.depth";;while(){my@a=split;my$d=$a[2]/$alldepth;print "$a[0]\t$a[1]\t$a[2]\t$d\n";}close A; ' |
432 | sort -k4nr >haps.depth.sort
433 |
434 | perl -e ' my%id2seq;$/=">";open A,"haps.fa";;while(){chomp;my@a=split;$id2seq{$a[0]}=$a[1];}close A;
435 | $/="\n"; open A,"haps.depth.sort";my$k=0;while(){chomp;my@a=split;next if $a[-1]<$ENV{"min_abundance"};
436 | my$abun=sprintf "%.3f",$a[-1];my$cov=sprintf "%.0f",$a[-2]; $k+=1;print ">hap$k $cov"."x freq=$abun\n$id2seq{$a[0]}\n";}close A; ' >haplotypes.final.fa
437 | done
438 | #TODO, after filtering, is it necessary to recompute the abundance of haplotypes ? yes, see for loop
439 |
440 |
441 | ## Done ##
442 | cd ..
443 | ln -fs ./filter_by_abun/haplotypes.final.fa .
444 | echo 'All steps finished successfully.'
445 | echo 'The final haplotypes and their relative abundances are saved here: '$outdir'/haplotypes.final.fa'
446 |
--------------------------------------------------------------------------------