├── .gitignore
├── LICENSE
├── README.md
├── analysis_scripts
├── analysis.sh
├── chop_up_assembly.py
├── error_summary.py
├── fix_read_names.py
├── get_median_identity.py
├── read_length_identity.py
├── rotate_reference.py
└── shred_assembly.py
├── basecalling_scripts
├── albacore_basecalling.sh
├── chiron_basecalling.sh
├── flappie_basecalling.sh
├── guppy_basecalling.sh
└── scrappie_basecalling.sh
├── images
├── logo-bottom.png
└── logo-top.png
└── sloika_training_scripts
├── filter_reads.py
├── per-isolate_commands.sh
├── subdivide_read_dir.py
├── training_commands.sh
└── trim_signal.py
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | .Rhistory
3 | plots/
4 | gh-md-toc
5 |
--------------------------------------------------------------------------------
/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)
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 |
2 | 
3 |
4 |
5 | # Performance of neural network basecalling tools for Oxford Nanopore sequencing
6 |
7 | __Ryan R. Wick1, Louise M. Judd1 and Kathryn E. Holt1,2__
8 |
9 | 1. Department of Infectious Diseases, Central Clinical School, Monash University, Melbourne, Victoria 3004, Australia
2. London School of Hygiene & Tropical Medicine, London WC1E 7HT, UK
10 |
11 |
12 | 
13 |
14 | [](https://doi.org/10.5281/zenodo.1188469)
15 |
16 |
17 | This repository contains the scripts used in the preparation of our manuscript on basecalling performance:
18 | [Wick RR, Judd LM, Holt KE. Performance of neural network basecalling tools for Oxford Nanopore sequencing. Genome Biology. 2019;20(1):129.](https://genomebiology.biomedcentral.com/articles/10.1186/s13059-019-1727-y)
19 |
20 | In August 2019, I put a small addendum to this paper on GitHub which looks at a more recent version of Guppy as well as some different polishing strategies:
21 | [github.com/rrwick/August-2019-consensus-accuracy-update](https://github.com/rrwick/August-2019-consensus-accuracy-update)
22 |
23 | Previous versions of this repository contained the analysis results here in the README, but the current results are now in that manuscript and this repo just holds the scripts associated with the analysis. These scripts assume you're running on Ubuntu 16.04. They make work on other OSs, but no guarantees!
24 |
25 | If you're still interested in the older results, here is a link to the earlier version of this repo: [Comparison of Oxford Nanopore basecalling tools](https://github.com/rrwick/Basecalling-comparison/tree/95bf07476f61cda79e6971f20f48c6ac83e634b3).
26 |
27 |
28 |
29 | ## Basecalling
30 |
31 | Before you analyse a read set, you must generate the read set! The [`basecalling_scripts`](basecalling_scripts) directory contains Bash scripts with the loops/commands I used to run the various basecallers. You'll need to edit the paths at the top of these scripts before running them.
32 |
33 |
34 |
35 | ## Custom training of basecallers
36 |
37 | The [`sloika_training_scripts`](sloika_training_scripts) directory contains the commands we used to train the custom-_Kp_ and custom-_Kp_-big-net models using [our fork of Sloika](https://github.com/rrwick/sloika).
38 |
39 | We used many different isolates in our training set, so the `per-isolate_commands.sh` script contains the commands which must be run separately for each of them.
40 |
41 | After the prepartory work is done, the model can be trained with the commands in `training_commands.sh`.
42 |
43 |
44 |
45 | ## Read set analysis
46 |
47 | The [`analysis_scripts`](analysis_scripts) directory contains the scripts for processing and generating accuracy measurements from read sets. Before the analysis, the reads must be given consistent names, as different basecallers have different conventions for the fastq headers. The `fix_read_names.py` script will convert a read fastq into a format suitable for the next step.
48 |
49 | [`analysis.sh`](scripts/analysis.sh) is the 'master script' that will run all analyses on a given read set: read-level accuracy, assembly, assembly-level accuracy, nanopolish and nanopolish-level accuracy. It will use the other scripts in its execution. You also might want to edit some of the variables at the start of the script to change things like the output directories and the number of CPU threads. You can also comment out parts of this script if you only want to run some of the analyses.
50 |
51 |
52 |
53 | ## License
54 |
55 | [GNU General Public License, version 3](https://www.gnu.org/licenses/gpl-3.0.html)
56 |
--------------------------------------------------------------------------------
/analysis_scripts/analysis.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | # https://github.com/rrwick/Basecalling-comparison
5 |
6 | # This program is free software: you can redistribute it and/or modify it under the terms of the
7 | # GNU General Public License as published by the Free Software Foundation, either version 3 of the
8 | # License, or (at your option) any later version. This program is distributed in the hope that it
9 | # will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
11 | # should have received a copy of the GNU General Public License along with this program. If not,
12 | # see .
13 |
14 | # This script:
15 | # * takes one argument: a fastq/fasta file of reads for analysis:
16 | # * read names should be in UUID format
17 | # * reads should be sorted by name
18 | # * expects the following in the directory in which it's run:
19 | # * a reference.fasta file
20 | # * expects the following tools in the PATH:
21 | # * minimap2 (https://github.com/lh3/minimap2)
22 | # * rebaler (https://github.com/rrwick/Rebaler)
23 | # * racon (https://github.com/isovic/racon)
24 | # * nanopolish and nanopolish_makerange.py (https://github.com/jts/nanopolish)
25 | # * MUMmer tools: nucmer, delta-filter, show-snps (https://sourceforge.net/projects/mummer)
26 |
27 |
28 | # Some high-level settings for the script:
29 | threads=20
30 | assembly_dir=assemblies # where finished assemblies will go
31 | nanopolish_dir=nanopolish # where Nanopolished assemblies will go
32 | results_dir=results # where the result tables will go
33 |
34 |
35 | # This variable holds the directory of the other scripts (assumed to be in the same directory as
36 | # this script):
37 | scripts_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
38 |
39 |
40 | # Get the read set name from the filename:
41 | set=$(basename $1 | sed 's/.fastq.gz//' | sed 's/.fasta.gz//' | sed 's/.fastq//' | sed 's/.fasta//')
42 | if [[ $1 = *"fastq"* ]]; then read_type=fastq
43 | elif [[ $1 = *"fasta"* ]]; then read_type=fasta
44 | else echo "Error: cannot determine read type"; exit 1
45 | fi
46 |
47 |
48 | # Various file paths that will be used along the way:
49 | read_data="$results_dir"/"$set"_reads.tsv
50 | read_alignment="$results_dir"/"$set"_reads.paf
51 | trimmed_reads="$assembly_dir"/"$set"_trimmed."$read_type"
52 | filtlong_reads="$assembly_dir"/"$set"_filtlong."$read_type"
53 | assembly_reads="$assembly_dir"/"$set"_assembly_reads.fastq
54 | final_assembly="$assembly_dir"/"$set"_assembly.fasta
55 | assembly_pieces="$results_dir"/"$set"_assembly_pieces.fasta
56 | assembly_data="$results_dir"/"$set"_assembly.tsv
57 | assembly_alignment="$results_dir"/"$set"_assembly.paf
58 | nanopolish_assembly="$nanopolish_dir"/"$set"_nanopolish.fasta
59 | sequencing_summary=03_basecalling_output/"$set"/sequencing_summary.txt
60 | bam_file="$1".sorted.bam
61 | nanopolish_pieces="$results_dir"/"$set"_nanopolish_pieces.fasta
62 | nanopolish_data="$results_dir"/"$set"_nanopolish.tsv
63 | nanopolish_alignment="$results_dir"/"$set"_nanopolish.paf
64 | nanopolish_2_assembly="$nanopolish_dir"/"$set"_nanopolish_2.fasta
65 | bam_file_2="$1"_2.sorted.bam
66 | nanopolish_2_pieces="$results_dir"/"$set"_nanopolish_2_pieces.fasta
67 | nanopolish_2_data="$results_dir"/"$set"_nanopolish_2.tsv
68 | nanopolish_2_alignment="$results_dir"/"$set"_nanopolish_2.paf
69 | nanopolish_3_assembly="$nanopolish_dir"/"$set"_nanopolish_3.fasta
70 | bam_file_3="$1"_3.sorted.bam
71 | nanopolish_3_pieces="$results_dir"/"$set"_nanopolish_3_pieces.fasta
72 | nanopolish_3_data="$results_dir"/"$set"_nanopolish_3.tsv
73 | nanopolish_3_alignment="$results_dir"/"$set"_nanopolish_3.paf
74 | nanopolish_4_assembly="$nanopolish_dir"/"$set"_nanopolish_4.fasta
75 | bam_file_4="$1"_4.sorted.bam
76 | nanopolish_4_pieces="$results_dir"/"$set"_nanopolish_4_pieces.fasta
77 | nanopolish_4_data="$results_dir"/"$set"_nanopolish_4.tsv
78 | nanopolish_4_alignment="$results_dir"/"$set"_nanopolish_4.paf
79 |
80 |
81 | # Used for nucmer:
82 | prefix="$set"_details
83 | ref_contig=chromosome
84 | assembly_contig=chromosome
85 |
86 |
87 |
88 |
89 | printf "\n\n\n"
90 | echo "ASSESS READS: "$set
91 | echo "--------------------------------------------------------------------------------"
92 | mkdir -p "$results_dir"
93 | minimap2 -x map-ont -t $threads -c reference.fasta $1 > $read_alignment
94 | pypy3 "$scripts_dir"/read_length_identity.py $1 $read_alignment > $read_data
95 | rm $read_alignment
96 |
97 |
98 |
99 |
100 | printf "\n\n\n\n"
101 | echo "ASSEMBLY: "$set
102 | echo "--------------------------------------------------------------------------------"
103 | mkdir -p "$assembly_dir"
104 | # Run Porechop
105 | # --no_split: to save time, chimeras shouldn't matter for Rebaler anyway
106 | # --check_reads 1000: to save time, it's all one barcode, so 1000 reads should be plenty
107 | porechop -i $1 -o $trimmed_reads --no_split --threads $threads --check_reads 1000
108 | if [ "$read_type" = "fasta" ]; then
109 | seqtk seq $trimmed_reads > "$assembly_dir"/temp.fasta # make one-line-per-seq fasta
110 | mv "$assembly_dir"/temp.fasta $trimmed_reads
111 | fi
112 | # Run multiple replicates of Racon on shuffled reads and a rotated reference.
113 | # Each assembly is then coursely shredded into 'reads' for the final Racon round.
114 | for i in {0..9}; do
115 | sample_reads="$assembly_dir"/"$set"_sample_"$i"."$read_type"
116 | sample_assembly="$assembly_dir"/"$set"_assembly_"$i".fasta
117 | sample_reference="$assembly_dir"/"$set"_reference_"$i".fasta
118 | if [ "$read_type" = "fastq" ]; then
119 | cat $trimmed_reads | paste - - - - | shuf | awk -F'\t' '{OFS="\n"; print $1,$2,$3,$4}' > $sample_reads
120 | elif [ "$read_type" = "fasta" ]; then
121 | cat $trimmed_reads | paste - - | shuf | awk -F'\t' '{OFS="\n"; print $1,$2}' > $sample_reads
122 | fi
123 | "$scripts_dir"/rotate_reference.py reference.fasta $i > $sample_reference
124 | rebaler -t $threads $sample_reference $sample_reads > $sample_assembly
125 | "$scripts_dir"/shred_assembly.py $sample_assembly $i 50000 >> $assembly_reads
126 | rm $sample_reads $sample_assembly $sample_reference
127 | done
128 | rm $trimmed_reads
129 | rebaler -t $threads reference.fasta $assembly_reads > $final_assembly
130 | rm $assembly_reads
131 |
132 |
133 |
134 |
135 | printf "\n\n\n\n"
136 | echo "ASSESS ASSEMBLY: "$set
137 | echo "--------------------------------------------------------------------------------"
138 | python3 "$scripts_dir"/chop_up_assembly.py $final_assembly 10000 > $assembly_pieces
139 | minimap2 -x asm5 -t $threads -c reference.fasta $assembly_pieces > $assembly_alignment
140 | pypy3 "$scripts_dir"/read_length_identity.py $assembly_pieces $assembly_alignment > $assembly_data
141 | rm $assembly_pieces $assembly_alignment
142 | if [ ! -f "$results_dir"/assembly_error_details ]; then
143 | printf "assembly\tdcm\thomo_del\thomo_ins\tother_del\tother_ins\tsub\n" > "$results_dir"/assembly_error_details
144 | fi
145 | printf $set"\t" >> "$results_dir"/assembly_error_details
146 | nucmer --prefix="$prefix" reference.fasta $final_assembly
147 | delta-filter -r -q "$prefix".delta > "$prefix".filter
148 | show-snps -ClrTH -x5 "$prefix".filter | python3 "$scripts_dir"/error_summary.py "$ref_contig" "$assembly_contig" >> "$results_dir"/assembly_error_details
149 | printf $set"\tassembly\t" >> "$results_dir"/substitution_counts
150 | show-snps -ClrTH "$prefix".filter | awk '$2 != "." && $3 != "."' | wc -l >> "$results_dir"/substitution_counts
151 | rm "$prefix".delta "$prefix".filter
152 |
153 |
154 |
155 |
156 | printf "\n\n\n\n"
157 | echo "NANOPOLISH: "$set
158 | echo "--------------------------------------------------------------------------------"
159 | mkdir -p $nanopolish_dir
160 | if [ -f $sequencing_summary ]; then
161 | echo "Running nanopolish index with sequencing_summary.txt file"
162 | nanopolish index -d fast5s -s $sequencing_summary $1
163 | else
164 | echo "Running nanopolish index without sequencing_summary.txt file"
165 | nanopolish index -d fast5s $1
166 | fi
167 | minimap2 -x map-ont -a -t $threads $final_assembly $1 | samtools sort > $bam_file
168 | samtools index $bam_file
169 | nanopolish_makerange.py $final_assembly | parallel --results "$nanopolish_dir"/"$set"_nanopolish.results -P $threads nanopolish variants --consensus -o "$nanopolish_dir"/"$set"_polished.{1}.vcf -w {1} -r $1 -b $bam_file -g $final_assembly -t 2 --min-candidate-frequency 0.1 --methylation-aware=dcm,dam --fix-homopolymers
170 | nanopolish vcf2fasta -g $final_assembly "$nanopolish_dir"/"$set"_polished.*.vcf > $nanopolish_assembly
171 | rm "$nanopolish_dir"/"$set"_polished.*.vcf "$nanopolish_dir"/"$set"_nanopolish.results*
172 | rm "$1".index "$1".index.fai "$1".index.gzi "$1".index.readdb $bam_file "$bam_file".bai
173 | rm "$final_assembly".fai
174 |
175 |
176 |
177 |
178 | printf "\n\n\n\n"
179 | echo "ASSESS NANOPOLISHED ASSEMBLY: "$set
180 | echo "--------------------------------------------------------------------------------"
181 | python3 "$scripts_dir"/chop_up_assembly.py $nanopolish_assembly 10000 > $nanopolish_pieces
182 | minimap2 -x asm5 -t $threads -c reference.fasta $nanopolish_pieces > $nanopolish_alignment
183 | pypy3 "$scripts_dir"/read_length_identity.py $nanopolish_pieces $nanopolish_alignment > $nanopolish_data
184 | rm $nanopolish_pieces $nanopolish_alignment
185 | if [ ! -f "$results_dir"/nanopolish_error_details ]; then
186 | printf "assembly\tdcm\thomo_del\thomo_ins\tother_del\tother_ins\tsub\n" > "$results_dir"/nanopolish_error_details
187 | fi
188 | printf $set"\t" >> "$results_dir"/nanopolish_error_details
189 | nucmer --prefix="$prefix" reference.fasta $nanopolish_assembly
190 | delta-filter -r -q "$prefix".delta > "$prefix".filter
191 | show-snps -ClrTH -x5 "$prefix".filter | python3 "$scripts_dir"/error_summary.py "$ref_contig" "$assembly_contig" >> "$results_dir"/nanopolish_error_details
192 | printf $set"\tnanopolish\t" >> "$results_dir"/substitution_counts
193 | show-snps -ClrTH "$prefix".filter | awk '$2 != "." && $3 != "."' | wc -l >> "$results_dir"/substitution_counts
194 | rm "$prefix".delta "$prefix".filter
195 |
196 |
197 |
198 |
199 | # What follows are subsequent runs of Nanopolish. If you want to do them, comment out this exit
200 | # statement so the script can continue.
201 | exit 0
202 |
203 |
204 |
205 |
206 | printf "\n\n\n\n"
207 | echo "NANOPOLISH (SECOND TIME): "$set
208 | echo "--------------------------------------------------------------------------------"
209 | if [ -f $sequencing_summary ]; then
210 | echo "Running nanopolish index with sequencing_summary.txt file"
211 | nanopolish index -d fast5s -s $sequencing_summary $1
212 | else
213 | echo "Running nanopolish index without sequencing_summary.txt file"
214 | nanopolish index -d fast5s $1
215 | fi
216 | minimap2 -x map-ont -a -t $threads $nanopolish_assembly $1 | samtools sort > $bam_file_2
217 | samtools index $bam_file_2
218 | nanopolish_makerange.py $nanopolish_assembly | parallel --results "$nanopolish_dir"/"$set"_2_nanopolish.results -P $threads nanopolish variants --consensus -o "$nanopolish_dir"/"$set"_2_polished.{1}.vcf -w {1} -r $1 -b $bam_file_2 -g $nanopolish_assembly -t 2 --min-candidate-frequency 0.1 --methylation-aware=dcm,dam --fix-homopolymers
219 | nanopolish vcf2fasta -g $nanopolish_assembly "$nanopolish_dir"/"$set"_2_polished.*.vcf > $nanopolish_2_assembly
220 | rm "$nanopolish_dir"/"$set"_2_polished.*.vcf "$nanopolish_dir"/"$set"_2_nanopolish.results*
221 | rm "$1".index "$1".index.fai "$1".index.gzi "$1".index.readdb $bam_file_2 "$bam_file_2".bai
222 | rm "$nanopolish_assembly".fai
223 |
224 |
225 |
226 | printf "\n\n\n\n"
227 | echo "ASSESS NANOPOLISHED (SECOND TIME) ASSEMBLY: "$set
228 | echo "--------------------------------------------------------------------------------"
229 | python3 "$scripts_dir"/chop_up_assembly.py $nanopolish_2_assembly 10000 > $nanopolish_2_pieces
230 | minimap2 -x asm5 -t $threads -c reference.fasta $nanopolish_2_pieces > $nanopolish_2_alignment
231 | pypy3 "$scripts_dir"/read_length_identity.py $nanopolish_2_pieces $nanopolish_2_alignment > $nanopolish_2_data
232 | rm $nanopolish_2_pieces $nanopolish_2_alignment
233 | if [ ! -f "$results_dir"/nanopolish_2_error_details ]; then
234 | printf "assembly\tdcm\thomo_del\thomo_ins\tother_del\tother_ins\tsub\n" > "$results_dir"/nanopolish_2_error_details
235 | fi
236 | printf $set"\t" >> "$results_dir"/nanopolish_2_error_details
237 | nucmer --prefix="$prefix"_2 reference.fasta $nanopolish_2_assembly
238 | delta-filter -r -q "$prefix"_2.delta > "$prefix"_2.filter
239 | show-snps -ClrTH -x5 "$prefix"_2.filter | python3 "$scripts_dir"/error_summary.py "$ref_contig" "$assembly_contig" >> "$results_dir"/nanopolish_2_error_details
240 | rm "$prefix"_2.delta "$prefix"_2.filter
241 |
242 |
243 |
244 |
245 | printf "\n\n\n\n"
246 | echo "NANOPOLISH (THIRD TIME): "$set
247 | echo "--------------------------------------------------------------------------------"
248 | if [ -f $sequencing_summary ]; then
249 | echo "Running nanopolish index with sequencing_summary.txt file"
250 | nanopolish index -d fast5s -s $sequencing_summary $1
251 | else
252 | echo "Running nanopolish index without sequencing_summary.txt file"
253 | nanopolish index -d fast5s $1
254 | fi
255 | minimap2 -x map-ont -a -t $threads $nanopolish_2_assembly $1 | samtools sort > $bam_file_3
256 | samtools index $bam_file_3
257 | nanopolish_makerange.py $nanopolish_2_assembly | parallel --results "$nanopolish_dir"/"$set"_3_nanopolish.results -P $threads nanopolish variants --consensus -o "$nanopolish_dir"/"$set"_3_polished.{1}.vcf -w {1} -r $1 -b $bam_file_3 -g $nanopolish_2_assembly -t 2 --min-candidate-frequency 0.1 --methylation-aware=dcm,dam --fix-homopolymers
258 | nanopolish vcf2fasta -g $nanopolish_2_assembly "$nanopolish_dir"/"$set"_3_polished.*.vcf > $nanopolish_3_assembly
259 | rm "$nanopolish_dir"/"$set"_3_polished.*.vcf "$nanopolish_dir"/"$set"_3_nanopolish.results*
260 | rm "$1".index "$1".index.fai "$1".index.gzi "$1".index.readdb $bam_file_3 "$bam_file_3".bai
261 | rm "$nanopolish_2_assembly".fai
262 |
263 |
264 |
265 | printf "\n\n\n\n"
266 | echo "ASSESS NANOPOLISHED (THIRD TIME) ASSEMBLY: "$set
267 | echo "--------------------------------------------------------------------------------"
268 | python3 "$scripts_dir"/chop_up_assembly.py $nanopolish_3_assembly 10000 > $nanopolish_3_pieces
269 | minimap2 -x asm5 -t $threads -c reference.fasta $nanopolish_3_pieces > $nanopolish_3_alignment
270 | pypy3 "$scripts_dir"/read_length_identity.py $nanopolish_3_pieces $nanopolish_3_alignment > $nanopolish_3_data
271 | rm $nanopolish_3_pieces $nanopolish_3_alignment
272 | if [ ! -f "$results_dir"/nanopolish_3_error_details ]; then
273 | printf "assembly\tdcm\thomo_del\thomo_ins\tother_del\tother_ins\tsub\n" > "$results_dir"/nanopolish_3_error_details
274 | fi
275 | printf $set"\t" >> "$results_dir"/nanopolish_3_error_details
276 | nucmer --prefix="$prefix"_3 reference.fasta $nanopolish_3_assembly
277 | delta-filter -r -q "$prefix"_3.delta > "$prefix"_3.filter
278 | show-snps -ClrTH -x5 "$prefix"_3.filter | python3 "$scripts_dir"/error_summary.py "$ref_contig" "$assembly_contig" >> "$results_dir"/nanopolish_3_error_details
279 | rm "$prefix"_3.delta "$prefix"_3.filter
280 |
281 |
282 |
283 |
284 | printf "\n\n\n\n"
285 | echo "NANOPOLISH (FOURTH TIME): "$set
286 | echo "--------------------------------------------------------------------------------"
287 | if [ -f $sequencing_summary ]; then
288 | echo "Running nanopolish index with sequencing_summary.txt file"
289 | nanopolish index -d fast5s -s $sequencing_summary $1
290 | else
291 | echo "Running nanopolish index without sequencing_summary.txt file"
292 | nanopolish index -d fast5s $1
293 | fi
294 | minimap2 -x map-ont -a -t $threads $nanopolish_3_assembly $1 | samtools sort > $bam_file_4
295 | samtools index $bam_file_4
296 | nanopolish_makerange.py $nanopolish_3_assembly | parallel --results "$nanopolish_dir"/"$set"_4_nanopolish.results -P $threads nanopolish variants --consensus -o "$nanopolish_dir"/"$set"_4_polished.{1}.vcf -w {1} -r $1 -b $bam_file_4 -g $nanopolish_3_assembly -t 2 --min-candidate-frequency 0.1 --methylation-aware=dcm,dam --fix-homopolymers
297 | nanopolish vcf2fasta -g $nanopolish_3_assembly "$nanopolish_dir"/"$set"_4_polished.*.vcf > $nanopolish_4_assembly
298 | rm "$nanopolish_dir"/"$set"_4_polished.*.vcf "$nanopolish_dir"/"$set"_4_nanopolish.results*
299 | rm "$1".index "$1".index.fai "$1".index.gzi "$1".index.readdb $bam_file_4 "$bam_file_4".bai
300 | rm "$nanopolish_3_assembly".fai
301 |
302 |
303 |
304 | printf "\n\n\n\n"
305 | echo "ASSESS NANOPOLISHED (FOURTH TIME) ASSEMBLY: "$set
306 | echo "--------------------------------------------------------------------------------"
307 | python3 "$scripts_dir"/chop_up_assembly.py $nanopolish_4_assembly 10000 > $nanopolish_4_pieces
308 | minimap2 -x asm5 -t $threads -c reference.fasta $nanopolish_4_pieces > $nanopolish_4_alignment
309 | pypy3 "$scripts_dir"/read_length_identity.py $nanopolish_4_pieces $nanopolish_4_alignment > $nanopolish_4_data
310 | rm $nanopolish_4_pieces $nanopolish_4_alignment
311 | if [ ! -f "$results_dir"/nanopolish_4_error_details ]; then
312 | printf "assembly\tdcm\thomo_del\thomo_ins\tother_del\tother_ins\tsub\n" > "$results_dir"/nanopolish_4_error_details
313 | fi
314 | printf $set"\t" >> "$results_dir"/nanopolish_4_error_details
315 | nucmer --prefix="$prefix"_4 reference.fasta $nanopolish_4_assembly
316 | delta-filter -r -q "$prefix"_4.delta > "$prefix"_4.filter
317 | show-snps -ClrTH -x5 "$prefix"_4.filter | python3 "$scripts_dir"/error_summary.py "$ref_contig" "$assembly_contig" >> "$results_dir"/nanopolish_4_error_details
318 | rm "$prefix"_4.delta "$prefix"_4.filter
319 |
--------------------------------------------------------------------------------
/analysis_scripts/chop_up_assembly.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This script takes an assembly as input and produces an output of 'reads': the assembly chopped into pieces.
15 | It is for assessing the distribution of identity over the assembly.
16 | """
17 |
18 | import sys
19 |
20 |
21 | def main():
22 | assembly_filename = sys.argv[1]
23 | piece_size = int(sys.argv[2])
24 | contigs = load_fasta(assembly_filename)
25 | read_num = 0
26 | for contig in contigs:
27 | seq = contig[1]
28 | for i in range(0, len(seq), piece_size):
29 | piece_seq = seq[i:i+piece_size]
30 | if len(piece_seq) == piece_size:
31 | read_num += 1
32 | print('>' + str(read_num))
33 | print(piece_seq)
34 |
35 |
36 | def load_fasta(fasta_filename):
37 | fasta_seqs = []
38 | with open(fasta_filename, 'rt') as fasta_file:
39 | name = ''
40 | sequence = ''
41 | for line in fasta_file:
42 | line = line.strip()
43 | if not line:
44 | continue
45 | if line[0] == '>': # Header line = start of new contig
46 | if name:
47 | fasta_seqs.append((name.split()[0], sequence, name))
48 | sequence = ''
49 | name = line[1:]
50 | else:
51 | sequence += line
52 | if name:
53 | fasta_seqs.append((name.split()[0], sequence, name))
54 | return fasta_seqs
55 |
56 |
57 | if __name__ == '__main__':
58 | main()
59 |
--------------------------------------------------------------------------------
/analysis_scripts/error_summary.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This script takes MUMmer SNPs as input (via stdin) and outputs a summary of the assembly's errors.
15 | Use it like this:
16 |
17 | prefix=ref_vs_assembly
18 | ref_fasta=ref.fasta
19 | assembly_fasta=assembly.fasta
20 | ref_contig=chromosome
21 | assembly_contig=tig00000001
22 |
23 | nucmer --prefix="$prefix" "$ref_fasta" "$assembly_fasta"
24 | delta-filter -r -q "$prefix".delta > "$prefix".filter
25 | rm "$prefix".delta
26 | show-snps -ClrTH -x5 "$prefix".filter | python3 error_summary.py "$ref_contig" "$assembly_contig"
27 | """
28 |
29 | import collections
30 | import math
31 | import sys
32 |
33 |
34 | homo_lengths_to_count = [3, 4, 5, 6, 7, 8]
35 |
36 |
37 | def main():
38 | r_contig = sys.argv[1]
39 | a_contig = sys.argv[2]
40 |
41 | r_length, alignment_length = None, None
42 | snp_count = 0
43 | homo_ins_count, non_homo_ins_count = 0, 0
44 | homo_del_count, non_homo_del_count = 0, 0
45 | homo_ins_counts = collections.defaultdict(int)
46 | homo_del_counts = collections.defaultdict(int)
47 | sub_count = 0
48 | dcm_count, no_motif_count = 0, 0
49 |
50 | error_type_counts = collections.defaultdict(int)
51 |
52 | for line in sys.stdin:
53 | parts = line.strip().split('\t')
54 | if parts[12] != r_contig or parts[13] != a_contig:
55 | continue
56 |
57 | if r_length is None:
58 | r_length = int(parts[7])
59 | alignment_length = r_length
60 | snp_count += 1
61 | r_base = parts[1]
62 | a_base = parts[2]
63 | ref_seq = parts[8]
64 |
65 | error_type = get_error_type(r_base, a_base, ref_seq)
66 | error_type_counts[error_type] += 1
67 |
68 | for error_type in ['dcm', 'homo del', 'homo ins', 'other del', 'other ins', 'sub']:
69 | rate = error_type_counts[error_type] / r_length
70 | end_char = '\n' if error_type == 'sub' else '\t'
71 | print('{:.7f}'.format(rate), end=end_char)
72 |
73 |
74 | def get_deletion_homopolymer_length(seq):
75 | seq_len = len(seq)
76 | middle_i = seq_len // 2
77 | base = seq[middle_i]
78 | start = middle_i
79 | while start > 0:
80 | if seq[start-1] == base:
81 | start -= 1
82 | else:
83 | break
84 | end = middle_i+1
85 | while end < seq_len:
86 | if seq[end] == base:
87 | end += 1
88 | else:
89 | break
90 | homopolymer = seq[start:end].replace('.', '')
91 | return len(homopolymer)
92 |
93 |
94 | def get_insertion_homopolymer_length(seq):
95 | seq_len = len(seq)
96 | middle_i = seq_len // 2
97 | base_1 = seq[middle_i-1]
98 | base_2 = seq[middle_i+1]
99 | if base_1 != base_2:
100 | return 1
101 | start = middle_i
102 | while start > 0:
103 | if seq[start-1] == base_1:
104 | start -= 1
105 | else:
106 | break
107 | end = middle_i+1
108 | while end < seq_len:
109 | if seq[end] == base_1:
110 | end += 1
111 | else:
112 | break
113 | homopolymer = seq[start:end].replace('.', '')
114 | return len(homopolymer)
115 |
116 |
117 | def error_in_dcm_motif(seq):
118 | seq = seq[1:-1]
119 | seq = seq.replace('.', '')
120 | return ('CCAGG' in seq) or ('CCTGG' in seq)
121 |
122 |
123 | def get_error_type(r_base, a_base, ref_seq):
124 | if error_in_dcm_motif(ref_seq):
125 | return 'dcm'
126 | if a_base == '.' and get_deletion_homopolymer_length(ref_seq) >= 3:
127 | return 'homo del'
128 | if r_base == '.' and get_insertion_homopolymer_length(ref_seq) >= 3:
129 | return 'homo ins'
130 | if a_base == '.': # deletion
131 | return 'other del'
132 | if r_base == '.': # insertion
133 | return 'other ins'
134 | return 'sub'
135 |
136 |
137 | if __name__ == '__main__':
138 | main()
139 |
--------------------------------------------------------------------------------
/analysis_scripts/fix_read_names.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This script adjusts read headers to be consistent between basecallers and compatible with
15 | Nanopolish. After running, each read header should be in this format:
16 | 5a8d447e-84e2-4f6f-922c-5ad7269f688c_Basecall_1D_template 5210_N125509_20170425_FN2002039725_MN19691_sequencing_run_klebs_033_restart_87298_ch152_read14914_strand
17 |
18 | It also sorts the reads alphabetically by their new headers and removes 0-length reads.
19 |
20 | Usage:
21 | fix_read_names.py input_reads.fastq.gz read_id_to_fast5 | gzip > output_reads.fastq.gz
22 |
23 | It can take either fasta or fastq input and will output in the same format.
24 |
25 | The read_id_to_fast5 file is a tab-delimited file with read IDs in the first column and fast5
26 | filenames in the second. For example:
27 | 00052d2b-be8b-4649-b6d5-9bdbd88a1ea5 5210_N128870_20170602_FN_MN20200_sequencing_run_sample_id_99953_ch225_read22973_strand.fast5
28 | 0005323f-791d-4bd1-bd5f-3f110cb72b08 5210_N128870_20170602_FN_MN20200_sequencing_run_sample_id_99953_ch341_read18592_strand.fast5
29 | 00077d28-f985-4800-898e-d4baede5d2aa 5210_N128870_20170602_FN_MN20200_sequencing_run_sample_id_99953_ch117_read27051_strand.fast5
30 | """
31 |
32 | import sys
33 | import os
34 | import gzip
35 | import re
36 |
37 |
38 | def main():
39 | input_reads_filename = sys.argv[1]
40 | read_id_to_fast5_filename = sys.argv[2]
41 |
42 | print('\nReading ' + read_id_to_fast5_filename, file=sys.stderr, flush=True)
43 | read_id_to_fast5, fast5_to_read_id = {}, {}
44 | with open(read_id_to_fast5_filename, 'rt') as read_id_to_fast5_file:
45 | for line in read_id_to_fast5_file:
46 | parts = line.strip().split('\t')
47 | if len(parts) == 2:
48 | read_id, fast5 = parts
49 | if fast5.endswith('.fast5'):
50 | fast5 = fast5[:-6]
51 | if read_id in read_id_to_fast5:
52 | sys.exit('Error: duplicate read ID in ' + read_id_to_fast5_filename + ': ' + read_id)
53 | if fast5 in fast5_to_read_id:
54 | sys.exit('Error: duplicate fast5 in ' + read_id_to_fast5_filename + ': ' + fast5)
55 | read_id_to_fast5[read_id] = fast5
56 | fast5_to_read_id[fast5] = read_id
57 |
58 | print('Loading reads from ' + input_reads_filename, file=sys.stderr, flush=True)
59 | reads, read_type = load_fasta_or_fastq(input_reads_filename)
60 |
61 | print('Fixing read names', file=sys.stderr, flush=True)
62 | output_reads = []
63 | for header, seq, qual in reads:
64 | read_id, fast5_name = None, None
65 | try:
66 | read_id = re.search(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', header).group(0)
67 | except AttributeError:
68 | read_id = None
69 | try:
70 | fast5_name = re.search(r'\w+_ch\d+_read\d+_\w+', header).group(0)
71 | except AttributeError:
72 | fast5_name = None
73 | if read_id is None and fast5_name is None:
74 | sys.exit('Error: could not parse read header\n' + header)
75 |
76 | if read_id is not None:
77 | new_header = read_id + ' ' + read_id_to_fast5[read_id]
78 | else:
79 | new_header = fast5_to_read_id[fast5_name] + ' ' + fast5_name
80 |
81 | output_reads.append((new_header, seq, qual))
82 |
83 | print('Sorting reads', file=sys.stderr, flush=True)
84 | output_reads = sorted(output_reads)
85 |
86 | print('Outputting reads', file=sys.stderr, flush=True)
87 | for header, seq, qual in output_reads:
88 | if len(seq) == 0:
89 | continue
90 | if read_type == 'FASTA':
91 | print('>' + header)
92 | print(seq)
93 | else: # read_type == 'FASTQ'
94 | print('@' + header)
95 | print(seq)
96 | print('+')
97 | print(qual)
98 | print('Done!\n', file=sys.stderr, flush=True)
99 |
100 |
101 | def get_compression_type(filename):
102 | magic_dict = {'gz': (b'\x1f', b'\x8b', b'\x08'),
103 | 'bz2': (b'\x42', b'\x5a', b'\x68'),
104 | 'zip': (b'\x50', b'\x4b', b'\x03', b'\x04')}
105 | max_len = max(len(x) for x in magic_dict)
106 |
107 | unknown_file = open(filename, 'rb')
108 | file_start = unknown_file.read(max_len)
109 | unknown_file.close()
110 | compression_type = 'plain'
111 | for filetype, magic_bytes in magic_dict.items():
112 | if file_start.startswith(magic_bytes):
113 | compression_type = filetype
114 | if compression_type == 'bz2':
115 | sys.exit('Error: cannot use bzip2 format - use gzip instead')
116 | if compression_type == 'zip':
117 | sys.exit('Error: cannot use zip format - use gzip instead')
118 | return compression_type
119 |
120 |
121 | def get_sequence_file_type(filename):
122 | if not os.path.isfile(filename):
123 | sys.exit('Error: could not find ' + filename)
124 | if get_compression_type(filename) == 'gz':
125 | open_func = gzip.open
126 | else: # plain text
127 | open_func = open
128 |
129 | with open_func(filename, 'rt') as seq_file:
130 | try:
131 | first_char = seq_file.read(1)
132 | except UnicodeDecodeError:
133 | first_char = ''
134 |
135 | if first_char == '>':
136 | return 'FASTA'
137 | elif first_char == '@':
138 | return 'FASTQ'
139 | else:
140 | raise ValueError('File is neither FASTA or FASTQ')
141 |
142 |
143 | def load_fasta_or_fastq(filename):
144 | try:
145 | file_type = get_sequence_file_type(filename)
146 | if file_type == 'FASTA':
147 | return load_fasta(filename), 'FASTA'
148 | else: # FASTQ
149 | return load_fastq(filename), 'FASTQ'
150 | except IndexError:
151 | sys.exit('\nError: ' + filename + ' could not be parsed - is it formatted correctly?')
152 |
153 |
154 | def load_fasta(fasta_filename):
155 | if get_compression_type(fasta_filename) == 'gz':
156 | open_func = gzip.open
157 | else: # plain text
158 | open_func = open
159 | fasta_seqs = []
160 | with open_func(fasta_filename, 'rt') as fasta_file:
161 | name = ''
162 | sequence = ''
163 | for line in fasta_file:
164 | line = line.strip()
165 | if not line:
166 | continue
167 | if line[0] == '>': # Header line = start of new contig
168 | if name:
169 | fasta_seqs.append((name, sequence, ''))
170 | sequence = ''
171 | name = line[1:]
172 | else:
173 | sequence += line
174 | if name:
175 | fasta_seqs.append((name, sequence, ''))
176 | return fasta_seqs
177 |
178 |
179 | def load_fastq(fastq_filename):
180 | if get_compression_type(fastq_filename) == 'gz':
181 | open_func = gzip.open
182 | else: # plain text
183 | open_func = open
184 | reads = []
185 |
186 | extra_empty_line = False
187 | with open_func(fastq_filename, 'rt') as fastq:
188 | for line in fastq:
189 | _ = next(fastq)
190 | _ = next(fastq)
191 | _ = next(fastq)
192 | fifth_line = next(fastq).strip()
193 | if len(fifth_line) == 0:
194 | extra_empty_line = True
195 | break
196 |
197 | with open_func(fastq_filename, 'rt') as fastq:
198 | for line in fastq:
199 | name = line.strip()[1:]
200 | sequence = next(fastq).strip()
201 | _ = next(fastq)
202 | qualities = next(fastq).strip()
203 | if extra_empty_line:
204 | _ = next(fastq)
205 | reads.append((name, sequence, qualities))
206 | return reads
207 |
208 |
209 | if __name__ == '__main__':
210 | main()
211 |
--------------------------------------------------------------------------------
/analysis_scripts/get_median_identity.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This script reads a tsv file (for either read or assembly data) and returns the median identity.
15 | It can optionally take a total number of sequences, which will make it add zeros to get to that
16 | number (useful for basecallers that didn't basecall all of the reads).
17 | """
18 |
19 | import statistics
20 | import sys
21 |
22 | identities = []
23 | with open(sys.argv[1], 'rt') as data_file:
24 | for line in data_file:
25 | parts = line.strip().split()
26 | if parts[0] == 'Name':
27 | continue
28 | identities.append(float(parts[2]))
29 |
30 | try:
31 | total_count = int(sys.argv[2])
32 | while len(identities) < total_count:
33 | identities.append(0.0)
34 | except IndexError:
35 | pass
36 |
37 | print(statistics.median(identities))
38 |
--------------------------------------------------------------------------------
/analysis_scripts/read_length_identity.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This script produces a table with information for each read.
15 |
16 | Inputs:
17 | * Read file
18 | * minimap2 PAF
19 |
20 | Output:
21 | * tsv file with these columns: length, identity, relative length
22 |
23 | If less than half of a read aligns, it is deemed unaligned and given an identity of 0. If more than
24 | half aligns, only the aligned parts are used to determined the read identity.
25 |
26 | Relative length is included to see if the reads are systematically too short or too long.
27 | """
28 |
29 |
30 | import collections
31 | import gzip
32 | import os
33 | import statistics
34 | import sys
35 |
36 |
37 | def main():
38 | read_filename = sys.argv[1]
39 | paf_filename = sys.argv[2]
40 |
41 | read_lengths = get_read_lengths(read_filename)
42 | read_names = sorted(read_lengths.keys())
43 | read_alignments = load_alignments(paf_filename, read_lengths)
44 |
45 | print('\t'.join(['Name', 'Length', 'Identity', 'Relative length']))
46 | for read_num, read_name in enumerate(read_names):
47 | read_length = read_lengths[read_name]
48 | alignments = read_alignments[read_name]
49 | identity_by_base = [0.0] * read_length
50 | total_read_length, total_ref_length = 0, 0
51 |
52 | for read_start, read_end, ref_start, ref_end, identity in alignments:
53 | for i in range(read_start, read_end):
54 | if identity > identity_by_base[i]:
55 | identity_by_base[i] = identity
56 | total_read_length += read_end - read_start
57 | total_ref_length += ref_end - ref_start
58 |
59 | # If less than half the read aligned, then we call it an unaligned read.
60 | if identity_by_base.count(0.0) > read_length / 2.0:
61 | whole_read_identity = 0.0
62 |
63 | # Otherwise, the read's identity is the average of the aligned parts.
64 | else:
65 | whole_read_identity = statistics.mean([x for x in identity_by_base if x > 0.0])
66 |
67 | if whole_read_identity > 0.0:
68 | relative_length = '%.5f' % (100.0 * total_read_length / total_ref_length)
69 | else:
70 | relative_length = ''
71 |
72 | print('{}\t{}\t{:.5f}\t{}'.format(read_name, read_length, whole_read_identity, relative_length))
73 | print_progress(read_num, len(read_names))
74 | print('\n', file=sys.stderr)
75 |
76 |
77 | def print_progress(done_count, total_count):
78 | print('\r{:,} / {:,} reads complete'.format(done_count+1, total_count),
79 | end='', flush=True, file=sys.stderr)
80 |
81 |
82 | def load_alignments(paf_filename, read_lengths):
83 | print('Loading alignments...', end='', flush=True, file=sys.stderr)
84 | read_alignments = collections.defaultdict(list)
85 | with open(paf_filename, 'rt') as paf:
86 | for line in paf:
87 | paf_parts = line.strip().split('\t')
88 | if len(paf_parts) < 11:
89 | continue
90 | read_name = paf_parts[0]
91 | read_length = int(paf_parts[1])
92 | assert read_length == read_lengths[read_name]
93 | read_start = int(paf_parts[2])
94 | read_end = int(paf_parts[3])
95 | ref_start = int(paf_parts[7])
96 | ref_end = int(paf_parts[8])
97 | identity = 100.0 * int(paf_parts[9]) / int(paf_parts[10])
98 | read_alignments[read_name].append((read_start, read_end, ref_start, ref_end, identity))
99 | print(' done', file=sys.stderr)
100 | return read_alignments
101 |
102 |
103 | def get_compression_type(filename):
104 | """
105 | Attempts to guess the compression (if any) on a file using the first few bytes.
106 | http://stackoverflow.com/questions/13044562
107 | """
108 | magic_dict = {'gz': (b'\x1f', b'\x8b', b'\x08'),
109 | 'bz2': (b'\x42', b'\x5a', b'\x68'),
110 | 'zip': (b'\x50', b'\x4b', b'\x03', b'\x04')}
111 | max_len = max(len(x) for x in magic_dict)
112 |
113 | unknown_file = open(filename, 'rb')
114 | file_start = unknown_file.read(max_len)
115 | unknown_file.close()
116 | compression_type = 'plain'
117 | for filetype, magic_bytes in magic_dict.items():
118 | if file_start.startswith(magic_bytes):
119 | compression_type = filetype
120 | if compression_type == 'bz2':
121 | sys.exit('Error: cannot use bzip2 format - use gzip instead')
122 | if compression_type == 'zip':
123 | sys.exit('Error: cannot use zip format - use gzip instead')
124 | return compression_type
125 |
126 |
127 | def get_sequence_file_type(filename):
128 | if not os.path.isfile(filename):
129 | sys.exit('Error: could not find ' + filename)
130 | if get_compression_type(filename) == 'gz':
131 | open_func = gzip.open
132 | else: # plain text
133 | open_func = open
134 | with open_func(filename, 'rt') as seq_file:
135 | try:
136 | first_char = seq_file.read(1)
137 | except UnicodeDecodeError:
138 | first_char = ''
139 | if first_char == '>':
140 | return 'FASTA'
141 | elif first_char == '@':
142 | return 'FASTQ'
143 | else:
144 | raise ValueError('File is neither FASTA or FASTQ')
145 |
146 |
147 | def get_read_lengths(filename):
148 | print('Loading read lengths...', end='', flush=True, file=sys.stderr)
149 | try:
150 | file_type = get_sequence_file_type(filename)
151 | if file_type == 'FASTA':
152 | return get_fasta_lengths(filename)
153 | else: # FASTQ
154 | return get_fastq_lengths(filename)
155 | except IndexError:
156 | sys.exit('\nError: ' + filename + ' could not be parsed - is it formatted correctly?')
157 |
158 |
159 | def get_fasta_lengths(fasta_filename):
160 | if get_compression_type(fasta_filename) == 'gz':
161 | open_func = gzip.open
162 | else: # plain text
163 | open_func = open
164 | read_lengths = {}
165 | with open_func(fasta_filename, 'rt') as fasta_file:
166 | name = ''
167 | sequence = []
168 | for line in fasta_file:
169 | line = line.strip()
170 | if not line:
171 | continue
172 | if line[0] == '>': # Header line = start of new contig
173 | if name:
174 | read_lengths[name.split()[0]] = len(''.join(sequence))
175 | sequence = []
176 | name = line[1:]
177 | else:
178 | sequence.append(line)
179 | if name:
180 | read_lengths[name.split()[0]] = len(''.join(sequence))
181 | print(' done', file=sys.stderr)
182 | return read_lengths
183 |
184 |
185 | def get_fastq_lengths(fastq_filename):
186 | if get_compression_type(fastq_filename) == 'gz':
187 | open_func = gzip.open
188 | else: # plain text
189 | open_func = open
190 | read_lengths = {}
191 | with open_func(fastq_filename, 'rt') as fastq:
192 | for line in fastq:
193 | name = line.strip()[1:].split()[0]
194 | sequence = next(fastq).strip()
195 | next(fastq)
196 | next(fastq)
197 | read_lengths[name] = len(sequence)
198 | print(' done', file=sys.stderr)
199 | return read_lengths
200 |
201 |
202 | if __name__ == '__main__':
203 | main()
204 |
--------------------------------------------------------------------------------
/analysis_scripts/rotate_reference.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This script takes a one-contig circular assembly as input and produces a rotated version of the
15 | assembly (with a new starting point).
16 | """
17 |
18 |
19 | import random
20 | import sys
21 |
22 |
23 | def main():
24 | ref = load_fasta(sys.argv[1])
25 | random.seed(int(sys.argv[2]))
26 | assert len(ref) == 1
27 | ref_seq = ref[0][1]
28 | assert len(ref_seq) > 1000000
29 | if random.random() < 0.5:
30 | ref_seq = reverse_complement(ref_seq)
31 | new_start_pos = random.randint(0, len(ref_seq) - 1)
32 | ref_seq = ref_seq[new_start_pos:] + ref_seq[:new_start_pos]
33 | print('>reference circular=true')
34 | print(ref_seq)
35 |
36 |
37 | def load_fasta(fasta_filename):
38 | fasta_seqs = []
39 | with open(fasta_filename, 'rt') as fasta_file:
40 | name = ''
41 | sequence = []
42 | for line in fasta_file:
43 | line = line.strip()
44 | if not line:
45 | continue
46 | if line[0] == '>': # Header line = start of new contig
47 | if name:
48 | fasta_seqs.append((name.split()[0], ''.join(sequence), name))
49 | sequence = []
50 | name = line[1:]
51 | else:
52 | sequence.append(line)
53 | if name:
54 | fasta_seqs.append((name.split()[0], ''.join(sequence), name))
55 | return fasta_seqs
56 |
57 |
58 | REV_COMP_DICT = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G',
59 | 'a': 't', 't': 'a', 'g': 'c', 'c': 'g',
60 | 'R': 'Y', 'Y': 'R', 'S': 'S', 'W': 'W',
61 | 'K': 'M', 'M': 'K', 'B': 'V', 'V': 'B',
62 | 'D': 'H', 'H': 'D', 'N': 'N',
63 | 'r': 'y', 'y': 'r', 's': 's', 'w': 'w',
64 | 'k': 'm', 'm': 'k', 'b': 'v', 'v': 'b',
65 | 'd': 'h', 'h': 'd', 'n': 'n',
66 | '.': '.', '-': '-', '?': '?'}
67 |
68 |
69 | def complement_base(base):
70 | try:
71 | return REV_COMP_DICT[base]
72 | except KeyError:
73 | return 'N'
74 |
75 |
76 | def reverse_complement(seq):
77 | return ''.join([complement_base(x) for x in seq][::-1])
78 |
79 |
80 | if __name__ == '__main__':
81 | main()
82 |
--------------------------------------------------------------------------------
/analysis_scripts/shred_assembly.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This script takes an assembly as input and produces an output of 'reads': the assembly chopped into
15 | overlapping pieces. It is used in assembly polishing to turn individual Racon-polished assemblies
16 | into 'reads' which can then be used as input for a final Racon polish.
17 | """
18 |
19 | import random
20 | import sys
21 | import uuid
22 |
23 |
24 | def main():
25 | assembly = load_fasta(sys.argv[1])
26 | random.seed(int(sys.argv[2]))
27 | read_length = int(sys.argv[3])
28 | assert len(assembly) == 1
29 | assembly_seq = assembly[0][1]
30 | assert len(assembly_seq) > 1000000
31 |
32 | # Add a bit of overlap so reads can span the junction.
33 | assembly_seq = assembly_seq + assembly_seq[:read_length]
34 |
35 | read_start = 0
36 | read_end = read_length
37 | while read_end <= len(assembly_seq):
38 | read_seq = assembly_seq[read_start:read_end]
39 | if random.random() < 0.5:
40 | read_seq = reverse_complement(read_seq)
41 | read_qual = ''.join([chr(random.randint(65, 75)) for _ in range(read_length)])
42 | print('@' + str(uuid.uuid4()))
43 | print(read_seq)
44 | print('+')
45 | print(read_qual)
46 | read_start += read_length // 3
47 | read_end += read_length // 3
48 |
49 |
50 | def load_fasta(fasta_filename):
51 | fasta_seqs = []
52 | with open(fasta_filename, 'rt') as fasta_file:
53 | name = ''
54 | sequence = []
55 | for line in fasta_file:
56 | line = line.strip()
57 | if not line:
58 | continue
59 | if line[0] == '>': # Header line = start of new contig
60 | if name:
61 | fasta_seqs.append((name.split()[0], ''.join(sequence), name))
62 | sequence = []
63 | name = line[1:]
64 | else:
65 | sequence.append(line)
66 | if name:
67 | fasta_seqs.append((name.split()[0], ''.join(sequence), name))
68 | return fasta_seqs
69 |
70 |
71 | REV_COMP_DICT = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G',
72 | 'a': 't', 't': 'a', 'g': 'c', 'c': 'g',
73 | 'R': 'Y', 'Y': 'R', 'S': 'S', 'W': 'W',
74 | 'K': 'M', 'M': 'K', 'B': 'V', 'V': 'B',
75 | 'D': 'H', 'H': 'D', 'N': 'N',
76 | 'r': 'y', 'y': 'r', 's': 's', 'w': 'w',
77 | 'k': 'm', 'm': 'k', 'b': 'v', 'v': 'b',
78 | 'd': 'h', 'h': 'd', 'n': 'n',
79 | '.': '.', '-': '-', '?': '?'}
80 |
81 |
82 | def complement_base(base):
83 | try:
84 | return REV_COMP_DICT[base]
85 | except KeyError:
86 | return 'N'
87 |
88 |
89 | def reverse_complement(seq):
90 | return ''.join([complement_base(x) for x in seq][::-1])
91 |
92 |
93 | if __name__ == '__main__':
94 | main()
95 |
--------------------------------------------------------------------------------
/basecalling_scripts/albacore_basecalling.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | # https://github.com/rrwick/Basecalling-comparison
5 |
6 | # This program is free software: you can redistribute it and/or modify it under the terms of the
7 | # GNU General Public License as published by the Free Software Foundation, either version 3 of the
8 | # License, or (at your option) any later version. This program is distributed in the hope that it
9 | # will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
11 | # should have received a copy of the GNU General Public License along with this program. If not,
12 | # see .
13 |
14 | # This script will execute each version of Albacore on the reads.
15 |
16 |
17 | # Edit the following paths before running, as appropriate for your environment:
18 | fast5_dir=/path/to/fast5s # all fast5s must be directly in this directory (i.e. not nested in subdirectories)
19 | output_prefix=/path/to/basecalling_output # Albacore output directories and consolidated fastqs will go in this directory
20 | albacore_installers=/path/to/albacore_installers # must contain the whl/deb files for the Albacore versions - this script installs each version before running it
21 | fast5_to_fastq=/path/to/fastq_to_fastq.py # path to fastq_to_fastq.py script (from https://github.com/rrwick/Fast5-to-Fastq) - required for older versions of Albacore
22 |
23 |
24 | cd $output_prefix
25 |
26 | # The most recent versions of Albacore:
27 | for v in 2.1.0 2.1.1 2.1.1 2.1.2 2.1.3 2.1.5 2.1.6 2.1.7 2.1.9 2.1.10 2.2.1 2.2.2 2.2.4 2.2.6 2.2.7 2.3.0 2.3.1 2.3.2 2.3.3 2.3.4; do
28 | pip3 install "$albacore_installers"/ont_albacore-"$v"-cp35-cp35m-manylinux1_x86_64.whl
29 | out_dir="$output_prefix"/albacore_v"$v"
30 | /usr/bin/time -v -o albacore_v"$v".time read_fast5_basecaller.py -f FLO-MIN106 -k SQK-LSK108 -i $fast5_dir -t 12 -s $out_dir -o fastq --disable_filtering --disable_pings
31 | cat "$out_dir"/workspace/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > albacore_v"$v".fastq
32 | done
33 |
34 | # These versions don't have --disable_pings:
35 | for v in 2.0.0 2.0.1 2.0.2; do
36 | pip3 install "$albacore_installers"/ont_albacore-"$v"-cp35-cp35m-manylinux1_x86_64.whl
37 | out_dir="$output_prefix"/albacore_v"$v"
38 | /usr/bin/time -v -o albacore_v"$v".time read_fast5_basecaller.py -f FLO-MIN106 -k SQK-LSK108 -i $fast5_dir -t 12 -s $out_dir -o fastq --disable_filtering
39 | cat "$out_dir"/workspace/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > albacore_v"$v".fastq
40 | done
41 |
42 | # These versions don't have --disable_filtering:
43 | for v in 1.2.0 1.2.1 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.3.1; do
44 | pip3 install "$albacore_installers"/ont_albacore-"$v"-cp35-cp35m-manylinux1_x86_64.whl
45 | out_dir="$output_prefix"/albacore_v"$v"
46 | /usr/bin/time -v -o albacore_v"$v".time read_fast5_basecaller.py -f FLO-MIN106 -k SQK-LSK108 -i $fast5_dir -t 12 -s $out_dir -o fastq
47 | cat "$out_dir"/workspace/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > albacore_v"$v".fastq
48 | done
49 |
50 | # These versions mess up the fastq files (extra line break) which requires fixing:
51 | for v in 1.1.0 1.1.1 1.1.2; do
52 | pip3 install "$albacore_installers"/ont_albacore-"$v"-cp35-cp35m-manylinux1_x86_64.whl
53 | out_dir="$output_prefix"/albacore_v"$v"
54 | /usr/bin/time -v -o albacore_v"$v".time read_fast5_basecaller.py -f FLO-MIN106 -k SQK-LSK108 -i $fast5_dir -t 12 -s $out_dir -o fastq
55 | cat "$out_dir"/workspace/*.fastq | paste - - - - - | sort -k1,1 -t " " | tr "\t" "\n" > albacore_v"$v".fastq
56 | done
57 |
58 | # These versions can't output to fastq:
59 | for v in 1.0.1 1.0.2 1.0.3 1.0.4; do
60 | pip3 install "$albacore_installers"/ont_albacore-"$v"-cp35-cp35m-manylinux1_x86_64.whl
61 | out_dir="$output_prefix"/albacore_v"$v"
62 | /usr/bin/time -v -o albacore_v"$v".time read_fast5_basecaller.py -f FLO-MIN106 -k SQK-LSK108 -i $fast5_dir -t 12 -s $out_dir
63 | ~/Fast5-to-Fastq/fast5_to_fastq.py "$out_dir"/workspace | paste - - - - | sed 's/_Basecall_1D_template/ Basecall_1D_template/' | sort -k1,1 -t " " | tr "\t" "\n" > albacore_v"$v".fastq
64 | done
65 |
66 | # These versions don't have flowcell and kit options (need to specify config):
67 | for v in 0.8.2 0.8.4 0.9.1; do
68 | pip3 install "$albacore_installers"/ont_albacore-"$v"-cp35-cp35m-manylinux1_x86_64.whl
69 | out_dir="$output_prefix"/albacore_v"$v"
70 | /usr/bin/time -v -o albacore_v"$v".time read_fast5_basecaller.py -c FLO-MIN106_LSK108_linear.cfg -i $fast5_dir -t 12 -s $out_dir
71 | "$fast5_to_fastq" "$out_dir"/workspace | paste - - - - | sed 's/_Basecall_1D_template/ Basecall_1D_template/' | sort -k1,1 -t " " | tr "\t" "\n" > albacore_v"$v".fastq
72 | done
73 |
74 | # 0.7.5 is the only version without a Python wheel:
75 | v=0.7.5
76 | apt install "$albacore_installers"/python3-ont-albacore_"$v"-1-xenial_amd64.deb
77 | out_dir="$output_prefix"/albacore_v"$v"
78 | /usr/bin/time -v -o albacore_v"$v".time read_fast5_basecaller.py -c FLO-MIN106_LSK108_linear.cfg -i $fast5_dir -t 12 -s $out_dir
79 | "$fast5_to_fastq" "$out_dir"/workspace | paste - - - - | sed 's/_Basecall_1D_template/ Basecall_1D_template/' | sort -k1,1 -t " " | tr "\t" "\n" > albacore_v"$v".fastq
80 |
--------------------------------------------------------------------------------
/basecalling_scripts/chiron_basecalling.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | # https://github.com/rrwick/Basecalling-comparison
5 |
6 | # This program is free software: you can redistribute it and/or modify it under the terms of the
7 | # GNU General Public License as published by the Free Software Foundation, either version 3 of the
8 | # License, or (at your option) any later version. This program is distributed in the hope that it
9 | # will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
11 | # should have received a copy of the GNU General Public License along with this program. If not,
12 | # see .
13 |
14 | # This script will execute each version of Chiron on the reads. Chiron takes a long time to run,
15 | # so I ran it on smaller batches of files so I could start/stop the basecalling as needed.
16 |
17 |
18 | # Edit the following paths before running, as appropriate for your environment:
19 | fast5_dir=/path/to/fast5s_100_read_dirs # should contain numbered subdirectories (000 to 151), each containing fast5 files
20 | output_prefix=/path/to/basecalling_output # Chiron output fastqs will go in this directory
21 | chiron_dirs=/path/to/Chiron # should contain a subdirectory for each version of Chiron, e.g. Chiron-v0.4.2
22 |
23 | # TensorFlow/CUDA requirements might change between Chiron versions:
24 | cuda_bin_path=/path/to/cuda-8.0/bin
25 | cuda_lib_path=/path/to/cuda-8.0/lib64
26 |
27 |
28 | cd $output_prefix
29 |
30 | # Versions 0.4, 0.4.1 and 0.4.2 all seem to produce the same reads, so I'm only running v0.4.2.
31 | v=0.4.2
32 | for d in {000..151}; do
33 | out_dir="$output_prefix"/chiron_v"$v"_"$d"
34 | out_file=chiron_v"$v"_"$d".fastq
35 | time_file=chiron_v"$v"_"$d".time
36 | if [ ! -f $out_file ]; then
37 | rm -rf $out_dir
38 | rm -f $time_file
39 | /usr/bin/time -v -o $time_file python "$chiron_dirs"/Chiron-"$v"/chiron/entry.py call -i "$fast5_dir"/"$d" -o $out_dir || break
40 | cat "$out_dir"/result/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > $out_file
41 | fi
42 | done
43 | cat chiron_v"$v"_*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > chiron_v"$v".fastq
44 | cat chiron_v"$v"_*.time > chiron_v"$v".time
45 |
46 | # Older versions need TensorFlow 1.0.1, which needs CUDA 8.0.
47 | export PATH="$cuda_bin_path":"$PATH"
48 | export LD_LIBRARY_PATH="$cuda_lib_path":"$LD_LIBRARY_PATH"
49 |
50 | for v in 0.3 0.2; do
51 | for d in "{000..151}"; do
52 | out_dir="$output_prefix"/chiron_v"$v"_"$d"
53 | out_file=chiron_v"$v"_"$d".fastq
54 | time_file=chiron_v"$v"_"$d".time
55 | if [ ! -f $out_file ]; then
56 | rm -rf $out_dir
57 | rm -f $time_file
58 | /usr/bin/time -v -o $time_file python "$chiron_dirs"/Chiron-"$v"/chiron/entry.py call -i "$fast5_dir"/"$d" -o $out_dir || break
59 | cat "$out_dir"/result/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > $out_file
60 | fi
61 | done
62 | cat chiron_v"$v"_*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > chiron_v"$v".fastq
63 | cat chiron_v"$v"_*.time > chiron_v"$v".time
64 | done
65 |
--------------------------------------------------------------------------------
/basecalling_scripts/flappie_basecalling.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | # https://github.com/rrwick/Basecalling-comparison
5 |
6 | # This program is free software: you can redistribute it and/or modify it under the terms of the
7 | # GNU General Public License as published by the Free Software Foundation, either version 3 of the
8 | # License, or (at your option) any later version. This program is distributed in the hope that it
9 | # will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
11 | # should have received a copy of the GNU General Public License along with this program. If not,
12 | # see .
13 |
14 | # This script will execute each version of Flappie on the reads.
15 |
16 |
17 | # Edit the following paths before running, as appropriate for your environment:
18 | fast5_dir=/path/to/fast5s # all fast5s must be directly in this directory (i.e. not nested in subdirectories)
19 | output_prefix=/path/to/basecalling_output # Flappie output fastqs will go in this directory
20 | binaries=/path/to/binaries # should contain Flappie binaries named with the version number, e.g. flappie-v1.1
21 |
22 |
23 | cd $output_prefix
24 | export OPENBLAS_NUM_THREADS=1
25 |
26 | for v in 1.0 1.1; do
27 | out_dir="$output_prefix"/flappie_v"$v"
28 | flappie="$binaries"/flappie-"$v"
29 |
30 | # I can't use time for Flappie because I run it in separate processes with the parallel
31 | # command, so I just run date before and after to get the total time.
32 | date
33 | find $fast5_dir -name \*.fast5 | parallel -P 12 -X $flappie --model r941_native > flappie_v"$v".fastq
34 | date
35 | done
36 |
--------------------------------------------------------------------------------
/basecalling_scripts/guppy_basecalling.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | # https://github.com/rrwick/Basecalling-comparison
5 |
6 | # This program is free software: you can redistribute it and/or modify it under the terms of the
7 | # GNU General Public License as published by the Free Software Foundation, either version 3 of the
8 | # License, or (at your option) any later version. This program is distributed in the hope that it
9 | # will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
11 | # should have received a copy of the GNU General Public License along with this program. If not,
12 | # see .
13 |
14 | # This script will execute each version of Guppy on the reads. In order to also use the
15 | # custom-trained models, the model files(holtlab_kp_r9.4_r9.4.1_nov_2018.jsn and
16 | # holtlab_kp_big_r9.4_r9.4.1_nov_2018.jsn) must be put into Guppy's data directory.
17 |
18 |
19 | # Edit the following paths before running, as appropriate for your environment:
20 | fast5_dir=/path/to/fast5s # all fast5s must be directly in this directory (i.e. not nested in subdirectories)
21 | output_prefix=/path/to/basecalling_output # Guppy output directories and consolidated fastqs will go in this directory
22 | guppy_installers=/path/to/guppy_installers # must contain the deb files for the Guppy versions - this script installs each version before running it
23 |
24 |
25 | cd $output_prefix
26 |
27 | # For the most recent versions of Guppy, I'm using both the default and flip-flop models:
28 | for v in 2.1.3 2.2.3; do
29 | apt install "$guppy_installers"/ont-guppy_"$v"-1~xenial_amd64.deb
30 | out_dir="$output_prefix"/guppy_v"$v"
31 | /usr/bin/time -v -o guppy_v"$v".time guppy_basecaller --config dna_r9.4.1_450bps.cfg --device auto -i $fast5_dir -t 12 -s $out_dir
32 | cat "$out_dir"/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > guppy_v"$v".fastq
33 | out_dir="$output_prefix"/guppy_v"$v"_flipflop
34 | /usr/bin/time -v -o guppy_v"$v"_flipflop.time guppy_basecaller --config dna_r9.4.1_450bps_flipflop.cfg --device auto -i $fast5_dir -t 12 -s $out_dir
35 | cat "$out_dir"/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > guppy_v"$v"_flipflop.fastq
36 | done
37 |
38 | # For only the most recent version of Guppy, I also tried our custom-trained models:
39 | v=2.2.3
40 | out_dir="$output_prefix"/guppy_v"$v"_custom_kp_model
41 | /usr/bin/time -v -o guppy_v"$v"_custom_kp_model.time guppy_basecaller --model_file holtlab_kp_r9.4_r9.4.1_nov_2018.jsn --config dna_r9.4.1_450bps.cfg --device auto -i $fast5_dir -t 12 -s $out_dir
42 | cat "$out_dir"/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > guppy_v"$v"_custom_kp_model.fastq
43 | out_dir="$output_prefix"/guppy_v"$v"_custom_kp_big_net_model
44 | /usr/bin/time -v -o guppy_v"$v"_custom_kp_big_net_model.time guppy_basecaller --model_file holtlab_kp_big_r9.4_r9.4.1_nov_2018.jsn --config dna_r9.4.1_450bps.cfg -i $fast5_dir -t 12 -s $out_dir
45 | cat "$out_dir"/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > guppy_v"$v"_custom_kp_big_net_model.fastq
46 |
47 |
48 | for v in 1.5.1 1.6.0 1.8.1 1.8.3 1.8.5; do
49 | apt install "$guppy_installers"/ont-guppy_"$v"-1~xenial_amd64.deb
50 | out_dir="$output_prefix"/guppy_v"$v"
51 | /usr/bin/time -v -o guppy_v"$v".time guppy_basecaller --config dna_r9.4_450bps.cfg --device auto -i $fast5_dir -t 12 -s $out_dir
52 | cat "$out_dir"/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > guppy_v"$v".fastq
53 | done
54 |
55 | # I couldn't make v1.4.3 run on the GPU so I used the CPU instead:
56 | v=1.4.3
57 | apt install "$guppy_installers"/ont-guppy_"$v"-1~xenial_amd64.deb
58 | out_dir="$output_prefix"/guppy_v"$v"
59 | /usr/bin/time -v -o guppy_v"$v".time guppy_basecaller --config dna_r9.4_450bps.cfg -i $fast5_dir -t 12 -s $out_dir
60 | cat "$out_dir"/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > guppy_v"$v".fastq
61 |
62 | v=0.5.4
63 | apt install "$guppy_installers"/ont-guppy_"$v"-1~xenial_amd64.deb
64 | out_dir="$output_prefix"/guppy_v"$v"
65 | /usr/bin/time -v -o guppy_v"$v".time guppy_basecaller --config dna_r9.4_450bps.cfg --device cuda:00000000:65:00.0 -i $fast5_dir -t 12 -s $out_dir
66 | cat "$out_dir"/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > guppy_v"$v".fastq
67 |
68 | # I couldn't make v0.3.0 run on the GPU so I used the CPU instead:
69 | v=0.3.0
70 | apt install "$guppy_installers"/ont-guppy_"$v"-1~xenial_amd64.deb
71 | out_dir="$output_prefix"/guppy_v"$v"
72 | /usr/bin/time -v -o guppy_v"$v".time guppy --config dna_r9.4_450bps.cfg --device cpu -i $fast5_dir -s $out_dir
73 | cat "$out_dir"/*.fastq | paste - - - - | sort -k1,1 -t " " | tr "\t" "\n" > guppy_v"$v".fastq
74 |
--------------------------------------------------------------------------------
/basecalling_scripts/scrappie_basecalling.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | # https://github.com/rrwick/Basecalling-comparison
5 |
6 | # This program is free software: you can redistribute it and/or modify it under the terms of the
7 | # GNU General Public License as published by the Free Software Foundation, either version 3 of the
8 | # License, or (at your option) any later version. This program is distributed in the hope that it
9 | # will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
11 | # should have received a copy of the GNU General Public License along with this program. If not,
12 | # see .
13 |
14 | # This script will execute each version of Scrappie on the reads.
15 |
16 |
17 | # Edit the following paths before running, as appropriate for your environment:
18 | fast5_dir=/path/to/fast5s # all fast5s must be directly in this directory (i.e. not nested in subdirectories)
19 | output_prefix=/path/to/basecalling_output # Scrappie output fastas will go in this directory
20 | binaries=/path/to/binaries # should contain Scrappie binaries named with the version number, e.g. scrappie-v1.4.1
21 |
22 |
23 | cd $output_prefix
24 | export OMP_NUM_THREADS=$(nproc)
25 | export OPENBLAS_NUM_THREADS=1
26 |
27 | # For recent versions of Scrappie, I ran both raw and event basecalling:
28 | for v in 1.4.1 1.4.0 1.3.2 1.3.1 1.3.0 1.2.0 1.1.1 1.1.0; do
29 | out_dir="$output_prefix"/scrappie_v"$v"
30 | scrappie="$binaries"/scrappie-v"$v"
31 | /usr/bin/time -v -o scrappie_raw_v"$v".time $scrappie raw $fast5_dir > scrappie_raw_v"$v".fasta
32 | /usr/bin/time -v -o scrappie_events_v"$v".time $scrappie events $fast5_dir > scrappie_events_v"$v".fasta
33 | done
34 |
35 | # These versions can't call events on their own - they rely on events already
36 | # being present, e.g. from Albacore. I therefore skipped scrappie events
37 | # (because it's not a stand-alone basecaller) and just ran scrappie raw.
38 | for v in 1.0.0 0.3.2 0.3.1 0.3.0; do
39 | out_dir="$output_prefix"/scrappie_v"$v"
40 | scrappie="$binaries"/scrappie-v"$v"
41 | /usr/bin/time -v -o scrappie_raw_v"$v".time $scrappie raw $fast5_dir > scrappie_raw_v"$v".fasta
42 | done
43 |
44 |
45 | # Versions earlier than 0.3.0 can only do event-based basecalling, so I'm skipping all of them.
46 |
--------------------------------------------------------------------------------
/images/logo-bottom.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rrwick/Basecalling-comparison/40c4802b3e78d262f0d6f07851e4e648bff39670/images/logo-bottom.png
--------------------------------------------------------------------------------
/images/logo-top.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rrwick/Basecalling-comparison/40c4802b3e78d262f0d6f07851e4e648bff39670/images/logo-top.png
--------------------------------------------------------------------------------
/sloika_training_scripts/filter_reads.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This script filters fast5 reads based on their alignment to reference contigs.
15 | The reads which pass filtering should be suitable for Sloika training.
16 | """
17 |
18 | import argparse
19 | import glob
20 | import os
21 | import re
22 | import shutil
23 | import sys
24 |
25 |
26 | def get_arguments():
27 | parser = argparse.ArgumentParser(description='Trim fast5 files at the signal level')
28 |
29 | parser.add_argument('--min_basecalled_length', type=int, required=False, default=5000,
30 | help='Reads will fail if basecalled to shorter than this amount')
31 | parser.add_argument('--max_unaligned_bases', type=int, required=False, default=100,
32 | help='Reads will fail if they have more than this many bases unaligned')
33 | parser.add_argument('--max_window_indels', type=float, required=False, default=0.8,
34 | help='Reads will fail if they have any CIGAR window with more than this '
35 | 'fraction of indels')
36 | parser.add_argument('--window_size', type=int, required=False, default=25,
37 | help='Window size for CIGAR indel check')
38 |
39 | parser.add_argument('in_fast5_dir', type=str,
40 | help='Directory containing trimmed fast5 files')
41 | parser.add_argument('seq_summary', type=str,
42 | help='Albacore/Guppy\'s sequencing_summary.txt file for the basecalling '
43 | 'of the trimmed fast5 files')
44 | parser.add_argument('reference', type=str,
45 | help='Reference FASTA (used to generate alignment)')
46 | parser.add_argument('paf_alignment', type=str,
47 | help='Minimap2 alignment of basecalled reads to reference contigs')
48 | parser.add_argument('out_fast5_dir', type=str,
49 | help='Output directory of passing fast5 files')
50 | parser.add_argument('out_ref', type=str,
51 | help='Output file per-read reference sequences')
52 |
53 | args = parser.parse_args()
54 | return args
55 |
56 |
57 | def main():
58 | args = get_arguments()
59 | filename_to_read_id = read_seq_summary(args.seq_summary)
60 | read_id_to_alignment_info = read_paf(args.paf_alignment)
61 | make_output_dir(args.out_fast5_dir)
62 | references = load_fasta(args.reference)
63 |
64 | with open(args.out_ref, 'w') as out_ref:
65 | for fast5_file in glob.iglob(args.in_fast5_dir + '/**/*.fast5', recursive=True):
66 | print()
67 | print(fast5_file)
68 | filename = fast5_file.rpartition('/')[2]
69 | read_id = filename_to_read_id[filename]
70 | print(' ID: {}'.format(read_id))
71 |
72 | try:
73 | read_length, read_start, read_end, cigar, _, strand, contig_name, contig_start, contig_end = read_id_to_alignment_info[read_id]
74 | except KeyError:
75 | print(' FAIL due to no alignment')
76 | continue
77 |
78 | print(' Length: {:,} bp'.format(read_length))
79 | if read_length < args.min_basecalled_length:
80 | print(' FAIL due to short length')
81 | continue
82 |
83 | unaligned_bases = read_start + (read_length - read_end)
84 | print(' Unaligned: {:,} bp'.format(unaligned_bases))
85 | if unaligned_bases > args.max_unaligned_bases:
86 | print(' FAIL due to too much unaligned')
87 | continue
88 |
89 | expanded_cigar = get_expanded_cigar(cigar)
90 | worst_window_indel_fraction = 0.0
91 | for i in range(len(expanded_cigar) - args.window_size):
92 | cigar_window = expanded_cigar[i:i+args.window_size]
93 | window_indel_fraction = (cigar_window.count('I') + cigar_window.count('D')) / args.window_size
94 | worst_window_indel_fraction = max(worst_window_indel_fraction, window_indel_fraction)
95 | print(' Worst window indels: {:.4f}'.format(worst_window_indel_fraction))
96 | if worst_window_indel_fraction > args.max_window_indels:
97 | print(' FAIL due to bad window indels')
98 | continue
99 |
100 | print(' PASS')
101 | new_file = '{}/{}'.format(args.out_fast5_dir, filename)
102 | print(' making a copy here: {}'.format(new_file))
103 | if os.path.exists(new_file):
104 | print()
105 | sys.exit('Error: {} already exists'.format(new_file))
106 | shutil.copyfile(fast5_file, new_file)
107 |
108 | print(' getting reference sequence from {} ({}-{}, {} strand)'.format(contig_name, contig_start, contig_end, strand))
109 | ref_header = '>' + os.path.basename(os.path.splitext(fast5_file)[0])
110 | ref_seq = references[contig_name][contig_start:contig_end]
111 | if strand == '-':
112 | ref_seq = reverse_complement(ref_seq)
113 |
114 | out_ref.write(ref_header)
115 | out_ref.write('\n')
116 | out_ref.write(ref_seq)
117 | out_ref.write('\n')
118 |
119 |
120 | def read_seq_summary(seq_summary_filename):
121 | filename_to_read_id = {}
122 | with open(seq_summary_filename, 'r') as seq_summary:
123 | for line in seq_summary:
124 | parts = line.split('\t')
125 | if parts[0] == 'filename': # header line
126 | continue
127 | filename, read_id = parts[0], parts[1]
128 | filename_to_read_id[filename] = read_id
129 | return filename_to_read_id
130 |
131 |
132 | def read_paf(paf_filename):
133 | read_id_to_alignment_info = {}
134 | with open(paf_filename, 'r') as paf_file:
135 | for line in paf_file:
136 | parts = line.split('\t')
137 | read_id = parts[0]
138 | read_length = int(parts[1])
139 | read_start = int(parts[2])
140 | read_end = int(parts[3])
141 | strand = parts[4]
142 | contig_name = parts[5]
143 | contig_start = int(parts[7])
144 | contig_end = int(parts[8])
145 | cigar, alignment_score = None, None
146 | for part in parts:
147 | if part.startswith('cg:Z:'):
148 | cigar = part[5:]
149 | if part.startswith('AS:i:'):
150 | alignment_score = int(part[5:])
151 | assert cigar is not None and alignment_score is not None
152 | alignment_info = read_length, read_start, read_end, cigar, alignment_score, strand, contig_name, contig_start, contig_end
153 |
154 | # If there are multiple alignments for a read, we keep the one with the best score.
155 | if read_id in read_id_to_alignment_info:
156 | _, _, _, _, existing_score, _, _, _, _ = read_id_to_alignment_info[read_id]
157 | if alignment_score > existing_score:
158 | read_id_to_alignment_info[read_id] = alignment_info
159 | else:
160 | read_id_to_alignment_info[read_id] = alignment_info
161 | return read_id_to_alignment_info
162 |
163 |
164 | def get_expanded_cigar(cigar):
165 | expanded_cigar = []
166 | cigar_parts = re.findall(r'\d+\w', cigar)
167 | for cigar_part in cigar_parts:
168 | num = int(cigar_part[:-1])
169 | letter = cigar_part[-1]
170 | if letter == 'M' or letter == 'I' or letter == 'D':
171 | expanded_cigar.append(letter * num)
172 | return ''.join(expanded_cigar)
173 |
174 |
175 | def make_output_dir(out_dir):
176 | if os.path.exists(out_dir):
177 | sys.exit('Error: output directory already exists')
178 | os.makedirs(out_dir)
179 |
180 |
181 | def load_fasta(fasta_filename):
182 | fasta_seqs = {}
183 | with open(fasta_filename, 'rt') as fasta_file:
184 | name = ''
185 | sequence = []
186 | for line in fasta_file:
187 | line = line.strip()
188 | if not line:
189 | continue
190 | if line[0] == '>': # Header line = start of new contig
191 | if name:
192 | fasta_seqs[name.split()[0]] = ''.join(sequence)
193 | sequence = []
194 | name = line[1:]
195 | else:
196 | sequence.append(line)
197 | if name:
198 | fasta_seqs[name.split()[0]] = ''.join(sequence)
199 | return fasta_seqs
200 |
201 |
202 | REV_COMP_DICT = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G',
203 | 'a': 't', 't': 'a', 'g': 'c', 'c': 'g',
204 | 'R': 'Y', 'Y': 'R', 'S': 'S', 'W': 'W',
205 | 'K': 'M', 'M': 'K', 'B': 'V', 'V': 'B',
206 | 'D': 'H', 'H': 'D', 'N': 'N',
207 | 'r': 'y', 'y': 'r', 's': 's', 'w': 'w',
208 | 'k': 'm', 'm': 'k', 'b': 'v', 'v': 'b',
209 | 'd': 'h', 'h': 'd', 'n': 'n',
210 | '.': '.', '-': '-', '?': '?'}
211 |
212 |
213 | def complement_base(base):
214 | try:
215 | return REV_COMP_DICT[base]
216 | except KeyError:
217 | return 'N'
218 |
219 |
220 | def reverse_complement(seq):
221 | return ''.join([complement_base(x) for x in seq][::-1])
222 |
223 |
224 | if __name__ == '__main__':
225 | main()
226 |
--------------------------------------------------------------------------------
/sloika_training_scripts/per-isolate_commands.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | # https://github.com/rrwick/Basecalling-comparison
5 |
6 | # This program is free software: you can redistribute it and/or modify it under the terms of the
7 | # GNU General Public License as published by the Free Software Foundation, either version 3 of the
8 | # License, or (at your option) any later version. This program is distributed in the hope that it
9 | # will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
11 | # should have received a copy of the GNU General Public License along with this program. If not,
12 | # see .
13 |
14 | # These commands assume you are running in a directory with a subdirectory titled
15 | # 01_original_fast5s, which contains the isolate's fast5s. It will make a few more directories as
16 | # it runs.
17 |
18 |
19 | # Edit the following paths before running, as appropriate for your environment:
20 | script_dir=/path/to/python_script_dir # directory with other Python scripts (trim_signal.py, filter_reads.py and subdivide_read_dir.py)
21 | r1=/path/to/reads_1.fastq.gz # Illumina reads (pair 1)
22 | r2=/path/to/reads_2.fastq.gz # Illumina reads (pair 2)
23 | sloika_dir=/path/to/sloika_dir # directory of Sloika clone (https://github.com/rrwick/sloika)
24 |
25 |
26 | # Make reference FASTA:
27 | skesa --fastq "$r1","$r2" --cores 16 --memory 128 > ref_contigs.fasta
28 |
29 | # Signal-level trimming of fast5s:
30 | python3 "$script_dir"/trim_signal.py --trim_amount 2000 --min_size 50000 01_original_fast5s 02_trimmed_fast5s
31 |
32 | # Basecalling and alignment - prep for QC:
33 | read_fast5_basecaller.py -f FLO-MIN106 -k SQK-LSK108 -i 02_trimmed_fast5s -t 12 -s 03_basecalling -o fastq --disable_filtering --disable_pings
34 | cat 03_basecalling/workspace/*.fastq > temp.fastq
35 | minimap2 -c -x map-ont -t 20 ref_contigs.fasta temp.fastq > alignments.paf
36 | rm temp.fastq
37 |
38 | # Alignment-based QC and per-read references:
39 | python3 "$script_dir"/filter_reads.py --min_basecalled_length 5000 --max_unaligned_bases 30 --max_window_indels 0.8 --window_size 25 02_trimmed_fast5s 03_basecalling/sequencing_summary.txt ref_contigs.fasta alignments.paf 04_filtered_fast5s read_references.fasta
40 |
41 | # Run the first round of Sloika chunky in parallel on smallish groups of reads. This means that
42 | # troublesome reads which hang and/or use lots of RAM only mess up their batch, not the whole
43 | # group.
44 | python3 "$script_dir"/subdivide_read_dir.py 04_filtered_fast5s 50
45 | cd 04_filtered_fast5s
46 | for d in *; do
47 | if (( d < 240 )); then # limit to 240 batches (12k reads)
48 | sbatch --job-name=Sloika_chunkify_"$d" --account=js66 --ntasks=4 --nodes=1-1 --time=1:00:00 --mem=40000 --wrap "module load python/3.5.2-gcc5; source ~/programs/sloika/build/env/bin/activate; export THEANO_FLAGS=device=cpu,floatX=float32,mode=FAST_RUN,blas.ldflags='-lblas',scan.allow_gc=False; /usr/bin/time -v ~/programs/sloika/bin/chunkify.py raw_remap --overwrite --jobs 4 --chunk_len 4000 --downsample_factor 5 --output_strand_list ../unfiltered_strands.txt "$d" remapped_unfiltered_"$d".hdf5 ~/programs/sloika/models/pretrained.pkl ../read_references.fasta"
49 | sleep 0.1
50 | fi
51 | done
52 | rm remapped_unfiltered_*.hdf5
53 | cd ..
54 |
55 | # Optionally, visualise the distributions of scores and proportions of stays:
56 | tail -n+2 unfiltered_strands.txt | awk '{print $3;}' | histogram.py --min 0 --max 1.6 --buckets 40
57 | tail -n+2 unfiltered_strands.txt | awk '{print $4 / ($7 - $6 + $4);}' | histogram.py --min 0 --max 1 --buckets 40
58 |
59 | # QC pass using the chunkify strand info:
60 | low_score=$(tail -n+2 unfiltered_strands.txt | awk '{print $3;}' | sort -n | awk '{all[NR] = $0} END{print all[int(NR*0.15 - 0.5)]}')
61 | high_score=$(tail -n+2 unfiltered_strands.txt | awk '{print $3;}' | sort -n | awk '{all[NR] = $0} END{print all[int(NR*0.95 - 0.5)]}')
62 | min_cov=$(tail -n+2 unfiltered_strands.txt | awk '{print ($7 - $6) / $5;}' | sort -n | awk '{all[NR] = $0} END{print all[int(NR*0.1 - 0.5)]}')
63 | min_cov=$(( min_cov > 0.975 ? min_cov : 0.975 ))
64 | max_stay=$(tail -n+2 unfiltered_strands.txt | awk '{print $4 / ($7 - $6 + $4);}' | sort -n | awk '{all[NR] = $0} END{print all[int(NR*0.75 - 0.5)]}')
65 | (head -n 1 unfiltered_strands.txt ; cat unfiltered_strands.txt | awk -v a="$low_score" -v b="$high_score" -v c="$min_cov" -v d="$max_stay" '$3 > a && $3 < b && ($7 - $6) > c * $5 && $4 / ($7 - $6 + $4) < d && $6 > 0') > filtered_strand_list.txt
66 |
67 | # Split reads into a training set (most of them) and a validation set (a small fraction):
68 | mkdir 05_training_fast5s
69 | for f in $(tail -n+2 filtered_strand_list.txt | cut -f1); do
70 | cp 04_filtered_fast5s/*/"$f" 05_training_fast5s
71 | done
72 | mkdir 06_validation_fast5s
73 | for f in $(ls 05_training_fast5s | shuf | head -n 20); do
74 | mv 05_training_fast5s/"$f" 06_validation_fast5s
75 | done
76 | python3 "$script_dir"/subdivide_read_dir.py 05_training_fast5s 1000
77 |
78 | # The second round of Sloika chunkify:
79 | isolate_name=$(basename "$PWD")
80 | cd 05_training_fast5s
81 | for d in *; do
82 | sbatch --job-name=Chunkify_"$isolate_name"_"$d" --account=js66 --ntasks=12 --nodes=1-1 --time=24:00:00 --mem=120000 --wrap "module load python/3.5.2-gcc5; source ~/programs/sloika/build/env/bin/activate; export THEANO_FLAGS=device=cpu,floatX=float32,mode=FAST_RUN,blas.ldflags='-lblas',scan.allow_gc=False; /usr/bin/time -v ~/programs/sloika/bin/chunkify.py raw_remap --jobs 12 --chunk_len 4000 --downsample_factor 5 --output_strand_list strands_"$d".txt "$d" remapped_"$d".hdf5 ~/programs/sloika/models/pretrained.pkl ../read_references.fasta"
83 | sleep 0.1
84 | done
85 |
--------------------------------------------------------------------------------
/sloika_training_scripts/subdivide_read_dir.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This script moves fast5 files into subdirectories with a particular number of files per directory.
15 | """
16 |
17 | import glob
18 | import math
19 | import os
20 | import shutil
21 | import sys
22 |
23 | input_dir = sys.argv[1]
24 | target_reads_per_dir = int(sys.argv[2])
25 |
26 | fast5_files = glob.glob(input_dir + '/*.fast5')
27 | file_count = len(fast5_files)
28 | print('Found {} fast5 files in {}'.format(file_count, input_dir))
29 |
30 | dir_count = int(round(file_count / target_reads_per_dir))
31 | if dir_count == 0:
32 | dir_count = 1
33 | files_per_dir = int(math.ceil(file_count / dir_count))
34 |
35 | dir_num = 0
36 | while file_count > 0:
37 | dir_name = input_dir + '/{:04d}'.format(dir_num)
38 | os.makedirs(dir_name)
39 |
40 | if file_count >= files_per_dir:
41 | move_files = files_per_dir
42 | else:
43 | move_files = file_count
44 | print('Moving {} files to {}'.format(move_files, dir_name))
45 | for f in fast5_files[:move_files]:
46 | shutil.move(f, dir_name)
47 |
48 | fast5_files = fast5_files[move_files:]
49 | file_count -= move_files
50 | dir_num += 1
51 |
--------------------------------------------------------------------------------
/sloika_training_scripts/training_commands.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | # https://github.com/rrwick/Basecalling-comparison
5 |
6 | # This program is free software: you can redistribute it and/or modify it under the terms of the
7 | # GNU General Public License as published by the Free Software Foundation, either version 3 of the
8 | # License, or (at your option) any later version. This program is distributed in the hope that it
9 | # will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
11 | # should have received a copy of the GNU General Public License along with this program. If not,
12 | # see .
13 |
14 |
15 | # Edit the following paths before running, as appropriate for your environment:
16 | out_dir=training_output
17 | training_input_dir=/path/to/training_data # this directory must contain the hdf5 files made by Sloika chunkify
18 | sloika_dir=/path/to/sloika_dir # directory of Sloika clone (https://github.com/rrwick/sloika)
19 | model=/path/to/sloika/models/raw_0.98_rgrgr.py # model file - change this to change the neural network architecture
20 |
21 |
22 | # Do the actual training:
23 | "$sloika_dir"/bin/train_network.py raw --min_prob 1e-5 --reload_after_batches 500 --save_every 500 --niteration 100000 "$model" "$out_dir" "$training_input_dir"/*.hdf5
24 |
25 | # Convert the trained models into both CPU and GPU appropriate forms:
26 | for f in "$out_dir"/model_*.pkl; do
27 | "$sloika_dir"/misc/model_convert.py --target cpu $f "$f".cpu
28 | "$sloika_dir"/misc/model_convert.py --target gpu $f "$f".gpu
29 | done
30 |
--------------------------------------------------------------------------------
/sloika_training_scripts/trim_signal.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Copyright 2019 Ryan Wick (rrwick@gmail.com)
4 | https://github.com/rrwick/Basecalling-comparison
5 |
6 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
7 | General Public License as published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version. This program is distributed in the hope that it
9 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
11 | have received a copy of the GNU General Public License along with this program. If not, see
12 | .
13 |
14 | This is a tool for trimming fast5s at the signal level.
15 |
16 | It does two steps for each read:
17 | 1) Trim off what looks like open-pore signal from the start and end of reads.
18 | 2) Trim off a fixed amount of signal from the start and end of reads.
19 |
20 | The final result should be reads with no adapter sequence, making them more suitable for Sloika.
21 | """
22 |
23 | import argparse
24 | import glob
25 | import h5py
26 | import numpy as np
27 | import os
28 | import shutil
29 | import sys
30 |
31 |
32 | def get_arguments():
33 | parser = argparse.ArgumentParser(description='Trim fast5 files at the signal level')
34 |
35 | parser.add_argument('--trim_amount', type=int, required=False, default=2000,
36 | help='Signal values to be trimmed from the start/end of the signal')
37 | parser.add_argument('--min_size', type=int, required=False, default=50000,
38 | help='Don\'t keep reads with a trimmed signal smaller than this')
39 |
40 | parser.add_argument('in_dir', type=str,
41 | help='Directory containing fast5 files to trim')
42 | parser.add_argument('out_dir', type=str,
43 | help='Output directory of trimmed fast5 files (will be made)')
44 |
45 | args = parser.parse_args()
46 | return args
47 |
48 |
49 | def main():
50 | args = get_arguments()
51 | make_output_dir(args.out_dir)
52 |
53 | for original_file in glob.iglob(args.in_dir + '/**/*.fast5', recursive=True):
54 | print(original_file)
55 |
56 | # Make a copy of the file which we will modify.
57 | new_file = '{}/{}'.format(args.out_dir, original_file.rpartition('/')[2])
58 | print(' making a copy here: {}'.format(new_file))
59 | if os.path.exists(new_file):
60 | print()
61 | sys.exit('Error: {} already exists'.format(new_file))
62 | shutil.copyfile(original_file, new_file)
63 |
64 | # Find the signal.
65 | hdf5_file = h5py.File(new_file, 'r+')
66 | signal_location = get_signal_location(hdf5_file)
67 | read_location = signal_location.replace('/Signal', '')
68 | signal = hdf5_file[signal_location].value
69 | orignal_length = len(signal)
70 | print(' original signal length = {:,}'.format(orignal_length))
71 |
72 | # Trim off open-pore signal
73 | try:
74 | start_trim = find_signal_start_pos(signal)
75 | print(' open-pore signal at start: {}'.format(start_trim))
76 | end_trim = find_signal_start_pos(signal[::-1])
77 | print(' open-pore signal at end: {}'.format(end_trim))
78 | except CannotTrim:
79 | print(' cannot trim - skipping')
80 | hdf5_file.close()
81 | os.remove(new_file)
82 | continue
83 |
84 | if start_trim + end_trim >= orignal_length:
85 | print(' too short - skipping')
86 | hdf5_file.close()
87 | os.remove(new_file)
88 | continue
89 | signal = signal[start_trim:-end_trim]
90 | no_open_pore_length = len(signal)
91 | print(' open-pore trimmed signal length = {:,}'.format(no_open_pore_length))
92 |
93 | if no_open_pore_length - (2 * args.trim_amount) < args.min_size:
94 | print(' too short - skipping')
95 | hdf5_file.close()
96 | os.remove(new_file)
97 | else:
98 | # Trim the signal and rewrite it.
99 | signal = signal[args.trim_amount:-args.trim_amount]
100 | del hdf5_file[signal_location]
101 | dset = hdf5_file.create_dataset(signal_location, compression='gzip',
102 | compression_opts=9, data=signal)
103 | new_length = len(signal)
104 | hdf5_file[read_location].attrs['duration'] = new_length
105 | print(' final trimmed signal length = {:,}'.format(new_length))
106 | hdf5_file.close()
107 | print()
108 |
109 |
110 | def make_output_dir(out_dir):
111 | if os.path.exists(out_dir):
112 | sys.exit('Error: output directory already exists')
113 | os.makedirs(out_dir)
114 |
115 |
116 | def get_signal_location(hdf5_file):
117 | names = []
118 | hdf5_file.visit(names.append)
119 | signal_locations = sorted([x for x in names if x.endswith('/Signal')])
120 | assert len(signal_locations) == 1
121 | return signal_locations[0]
122 |
123 |
124 | def find_signal_start_pos(signal):
125 | """
126 | Given a signal, this function attempts to identify the approximate position where the open
127 | pore signal ends and the real signal begins.
128 | """
129 | initial_trim_size = 10
130 | trim_increment = 25
131 | stdev_threshold = 20
132 | look_forward_windows = 5
133 | window_count_threshold = 4
134 |
135 | # Always trim off the first few values as these are often dodgy.
136 | pos = initial_trim_size
137 |
138 | # Look at the stdev of the signal in the upcoming windows. Trimming is finished when:
139 | # 1. the next window has a high stdev
140 | # 2. enough of the other upcoming windows have a high stdev
141 | while True:
142 | next_window_stdev = get_window_stdev(signal, pos, 0, trim_increment)
143 | if next_window_stdev > stdev_threshold:
144 | upcoming_window_stdevs = [get_window_stdev(signal, pos, i, trim_increment)
145 | for i in range(look_forward_windows)]
146 | num_high_stdevs = sum(1 if x > stdev_threshold else 0
147 | for x in upcoming_window_stdevs)
148 | if num_high_stdevs >= window_count_threshold:
149 | return pos
150 | pos += trim_increment
151 |
152 |
153 | class CannotTrim(IndexError):
154 | pass
155 |
156 |
157 | def get_window_stdev(signal, current_pos, window_num, increment):
158 | window_start = current_pos + (window_num * increment)
159 | window_end = window_start + increment
160 | if window_end > len(signal):
161 | raise CannotTrim
162 | return np.std(signal[window_start:window_end])
163 |
164 |
165 | if __name__ == '__main__':
166 | main()
167 |
--------------------------------------------------------------------------------