├── .github
└── ISSUE_TEMPLATE
│ └── bug_report.md
├── LICENSE.txt
├── README.md
├── plasx
├── __init__.py
├── compress_utils.py
├── constants.py
├── fasta_utils.py
├── learn.py
├── mmseqs.py
├── model.py
├── nb_utils.py
├── pd_utils.py
├── plasx_script.py
└── utils.py
├── requirements.txt
├── setup.py
└── test
├── test-contigs-cogs-and-pfams.txt
├── test-contigs-de-novo-families.txt
├── test-contigs-gene-calls.txt
├── test-contigs-scores.txt
├── test-contigs.db
└── test-contigs.fa
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 |
12 | Please provide a description of the bug
13 |
14 | **Terminal output**
15 |
16 | Please paste the output of the command terminal (or attach it as a file)
17 |
18 | **Software environment**
19 |
20 | Please paste the output of `conda list`, so that we can see if there is an installation problem
21 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | PlasX is a machine learning classifier for identifying plasmid sequences based on genetic architecture.
2 |
3 | This README includes a tutorial for predicting plasmids from any input set of contigs. It also includes instructions for reproducing the 226,194 predicted plasmid contigs from our study ["The Genetic and Ecological Landscape of Plasmids in the Human Gut" by Michael Yu, Emily Fogarty, A. Murat Eren](https://www.biorxiv.org/content/10.1101/2020.11.01.361691v2).
4 |
5 | # Installation
6 |
7 | PlasX requires `python >=3.7`. We recommend installing PlasX in a new virtual environment using Anaconda, to make installing dependencies easier. **PlasX requires Linux and at least 8Gb of system RAM. In the future, we will provide support for running PlasX on Mac OS and Windows.**
8 |
9 | ```
10 | # Create virtual environment named "plasx" (you can change the name to whatever you like)
11 | conda create --name plasx
12 | # Install dependencies (this might take a few minutes for Anaconda to figure out the right package versions).
13 | # The flags `-c anaconda -c conda-forge -c bioconda --override-channels --strict-channel-priority` specifies where packages should be downloaded from.
14 | conda install --name plasx -y -c anaconda -c conda-forge -c bioconda --override-channels --strict-channel-priority numpy pandas scipy scikit-learn numba python-blosc mmseqs2=10.6d92c
15 | ```
16 |
17 | Alternatively, create the environment and install dependencies in a single command
18 |
19 | ```
20 | conda create --name plasx -y -c anaconda -c conda-forge -c bioconda --override-channels --strict-channel-priority numpy pandas scipy scikit-learn numba python-blosc mmseqs2=10.6d92c
21 | ```
22 |
23 | Then, activate the new environment
24 | ```
25 | conda activate plasx
26 | ```
27 |
28 | Finally, download PlasX (e.g. with `git clone`) and then install it with `pip`
29 |
30 | ```
31 | # Download the PlasX code
32 | git clone https://github.com/michaelkyu/PlasX.git
33 | # Change directory into the repository, and then install using pip
34 | cd PlasX
35 | pip install .
36 | ```
37 |
38 | # Tutorial for predicting plasmids using PlasX
39 |
40 | PlasX can be run using the command line (make sure you've activated the correct virtual environment).
41 |
42 | ```
43 | $ plasx -h
44 | ```
45 |
46 | ```
47 | usage: plasx [-h] {setup,fit,search_de_novo_families,predict} ...
48 |
49 | Runs a PlasX model on a set of sequences. A score is returned for each contig.
50 | Plasmids have scores closer to 1, whereas chromosomes have scores closer to 0.
51 |
52 | positional arguments:
53 | {setup,fit,search_de_novo_families,predict}
54 | setup Downloads a pretrained PlasX model
55 | fit (Not implemented yet) Trains a new PlasX model
56 | search_de_novo_families
57 | Annotates genes to de novo families
58 | predict Runs trained PlasX model on annotated sequences
59 |
60 | optional arguments:
61 | -h, --help show this help message and exit
62 | (plasx)
63 | ```
64 |
65 | In this tutorial, we will identify plasmids using a PlasX model that was pretrained on a set of reference bacterial genomes and plasmid sequences from NCBI. We'll run this model on an example set of 40 contigs in `test/test-contigs.fa`, **but you can repeat these steps with your own contigs**. Running PlasX consists of three steps:
66 |
67 | 1. Identify genes and annotate COGs and Pfams using [anvio](https://merenlab.org/software/anvio/)
68 | 2. Annotate *de novo* gene families
69 | 3. Use PlasX to classify contigs as plasmid or non-plasmid sequences, based on the annotations in step #1 and #2
70 |
71 | The `test` directory contains copies of the files that will be created by these steps. You can use these files to skip ahead in the tutorial or to check correctness
72 |
73 | ## Step 0. Preliminary setup of your command line environment
74 |
75 |
76 | ```bash
77 | # Change into the directory where PlasX was downloaded (e.g. where `git clone` downloaded PlasX to).
78 | cd /path/to/PlasX
79 |
80 | # Change into the `test` subdirectory that contains test-contigs.fa
81 | cd test
82 |
83 | # Input and output filename will start with this prefix
84 | PREFIX='test-contigs'
85 |
86 | # The number of CPU cores that will be used to annotate genes. We recommend setting it to the number of CPUs available, to speed up the processing of many contigs
87 | THREADS=4
88 | ```
89 |
90 |
91 |
92 | ```bash
93 | # We are going to run PlasX on a fasta file containing 40 sequences. The file looks like this.
94 | head test-contigs.fa
95 | ```
96 |
97 | >AST0002_000000019451
98 | ATCTGATCCATCACGTACAGTGGATCCCCACCGTCATTATAGACCGGCTCCTGCAAACTCATAGGCACCTGTATGGCGTCCAGCGCATAGACAAAGGAGGTTTTCACTGCCTTTTCCGGTGCGCCGCCATGCTCCAGCCAGGAGGAGTTATGATAGTATTCCAGCACATTGACGCTGTTGGAAAAGCACAGGGCAGCGGT...
99 |
100 | >AST0002_000000028382
101 | TTGAGTACCATACATTTTTACATCATTCTCAAACCTCAAATTCAAAAATGAAATGCCATCACCTGCACAAAACTAGGCACTCAAACTGTATACTTTAATAAATTTCACATCTATCTTTATCTATAATATACCGTTCTACTCCCTCCACACAAGCTTTCTCGCTATTTTCAATAAATAATCCTTTTATTTCTATATATTTT...
102 |
103 | >AST0002_000000001053
104 | TCTCTCACGAAACAGCTTATTTATAATATCATCCCTTCTTAAACTTGTCAATAGCTTTTTTTAAAGTTTTGGAACCTTTTTTATTGCTGAACAAGTTATTTGGGACTTTACTAGTTTATCAAGTTTAAGTAATAAAGTCAACAAATTCTTCTTTTTAAAAAACAAAAAGAAGATACTAGTAACCTTTTTCTAGAATTTTA...
105 |
106 | ...
107 |
108 | ## Step 1. Identify genes and annotate COGs and Pfams using [anvio](https://merenlab.org/software/anvio/)
109 | * anvio is a software platform for analyzing omics data. Please install it using instructions at https://merenlab.org/2016/06/26/installation-v2/.
110 | * Here, we use anvio to call and annotate genes. All of the relevant anvio commands are described below. But if you're curious about anvio's other functionalities, you can learn more at https://merenlab.org/tutorials/infant-gut/.
111 |
112 | ### Create an anvio contigs database
113 |
114 |
115 | ```bash
116 | # Change into the Anaconda environment that contains anvio
117 | # - This step assumes that you installed anvio into a separate Anaconda environment than PlasX. You may modify this step depending on how you installed anvio.
118 | conda deactivate
119 | conda activate anvio
120 | ```
121 |
122 |
123 | ```bash
124 | # Create an anvio contigs database from the fasta file
125 | # - The `-L 0` parameter ensures that contigs remain intact and aren't split
126 | anvi-gen-contigs-database -L 0 -T $THREADS --project-name $PREFIX -f $PREFIX.fa -o $PREFIX.db
127 |
128 | # Export gene calls (including amino acid sequences) to text file
129 | anvi-export-gene-calls --gene-caller prodigal -c $PREFIX.db -o $PREFIX-gene-calls.txt
130 | ```
131 |
132 |
133 | ```bash
134 | # You should see something like this
135 | head $PREFIX-gene-calls.txt
136 | ```
137 |
138 | gene_callers_id contig start stop direction partial call_type source version aa_sequence
139 | 0 AST0002_000000019451 2 1001 r 1 1 prodigal v2.6.3 MKKKATYGNESISMLKGADRVRLRPAVIFGSDGLEGCEHAVFEILSNAIDEAREGHGKEILVTRYLDHSIQVEDFGRGCPVDWNPAEQRFNWELVFCELYAGGKYSNNEGENYEYSLGLNGLGACATQYASRYFDAVIRRDGKKYTLHFEKGENIGGLKTEKADRKQTGSCFHWMPDLDVFTDINIPAEYYADILKRQAVVNAGVTFRLRTEMADGSFQETDFCYENGILDYVKELTEGKAMTMPQFWEAERKGRDRADMADYKVKITAALCFSNSVNVLEYYHNSSWLEHGGAPEKAVKTSFVYALDAIQVPMSLQEPVYNDGGDPLYVMDQ
140 | 1 AST0002_000000019451 1152 1908 r 1 1 prodigal v2.6.3 ALAECLFDDEKNMVRIDMSEYMEKYSVSRLIGAPPGYVGYEEGGQLTEAVRRRPYSVILFDEVEKAHPDVFNVLLQVLDDGRITDSQGRTVDFKNTIIILTSNLGSQYLLDGIGPDGSITQEAKDQVNALLKKSFRPEFLNRLDEIVFYKPLTRDNITSIIDLQMKDLNRRLADKQLSCRLTPEAKHFIIDAAYDPLYGARPLRRYLQHTVETLIAKKILTGDMPMGSVLEIRVEDGELTVVVVMEATIVE
141 | 2 AST0002_000000028382 94 766 r 0 1 prodigal v2.6.3 MKLVHGDLSGEIINEQKECVEWIIESPDLFSKYVGELYRQFNKDEGKFVLSENNKEIDIAKYSEIIINPLSIEINNRKVLNKLYEELNKLSFNEVLYMKTLELTKLIQEYLLELEQETNYILEFNNEVEMSALFKAVDLKYEDSGEDFLERLVKYIKILVDLLSVKLFVFINARCFMNDEQIKKLCEEIKYIEIKGLFIENSEKACVEGVERYIIDKDRCEIY
142 | 3 AST0002_000000028382 762 1068 r 0 1 prodigal v2.6.3 MRVLVFFDLPVLTSENRRAYAKFRKFLLKNGFLMLQESVYCKLALNGSAVNAIVDSVHKNKPEEGLIQLLTVTEKQYAKMDIILGQVKSEVLDTDERLVIL
143 | 4 AST0002_000000028382 1072 1321 r 1 1 prodigal v2.6.3 FNLASDLMEPFRVLVDQEVYNMRLEQFEHEEKMILVNILNKEVQIDGKNQYVNNAIKIYCKSIFDALNEDDSALIRFYKIEL
144 | 5 AST0002_000000001053 197 596 r 0 1 prodigal v2.6.3 MIKIYTISSCTSCKKAKTWLNKHQLPYKEQNLGKEPLTKEEILTILSKTENGVESIVSKKNRYAKALNCDIDELSVSEVIDLIQENPRILKSPILIDDKRLQVGYKEDDIRAFLPRSIRNVENSQARMRAAL
145 | 6 AST0002_000000001053 772 1927 r 0 1 prodigal v2.6.3 MAKKTKKTEEITKKFGDERLKALDDALKNIEKDFGKGAVMRLGERAEQKVQVMSSGSLALDIALGAGGYPKGRIIEIYGPESSGKTTVALHAVAQTQKEGGIAAFIDAEHALDPAYAAALGVNIDELLLSQPDSGEQGLEIAGKLIDSGAVDLVVVDSVAALVPRAEIDGDIGDSHVGLQARMMSQAMRKLSASINKTKTIAIFINQLREKVGIMFGNPETTPGGRALKFYASVRLDVRGNTQIKGTGDKKDQNVGKETKIKVVKNKVAPPFKEAFVEIMYGEGISQTGELVKIASDIGIIQKAGAWFSYNGEKIGQGSENAKKYLADHPEIFAEIDHKVRVHYGLVELDEDDVVEDTQVEDTQVEDTSDELILDLDSTIEIEE
146 | 7 AST0002_000000001053 1962 3234 r 0 1 prodigal v2.6.3 MKAELIAVGTEILTGQITNTNAQFLSEKLAELGIDVYFHTAVGDNENRLLSVLDQSSKRSDLVILCGGLGPTEDDLTKQTLAKFLGKELIFDEEASKKLDSFFATRPKHTRTPNNERQAQIVEGAVPLQNLTGLAVGGIITVEGVTYVVLPGPPSELKPMVNQELIPALTENHTTLYSRVLRFFGVGESQLVTIIKDLIVNQTDPTIAPYAKVGEVILRLSTKASSQEEADRKLDVLEEQIRSTKTLDGKSLSDLIYGYGESNSLAYEVFYLLKKYGKTITAAESLTAGLFQASVADFPGASQVFKGGFVTYSMEEKAKMLDIPLSKLEEHGVVSHFTAEKMAEGARVKTDSDYGIALTGVAGPDALEGHQAGTVFIGIADRNQVRSIKVVIGGRSRSDVRYISTLYAFNLVRQALLQEDNSI
147 | 8 AST0002_000000001053 3708 3885 r 0 1 prodigal v2.6.3 MVNRCRWVPTDNKLYCDYHDKEWGKPIGDDEKLFELLCLESYQSGLSWLTVLKKTPGF
148 |
149 |
150 |
151 | ### Download COG 2014 and Pfam v32 databases
152 |
153 |
154 | ```bash
155 | # Download COGs (~2 min on fast network) and Pfam (~20 min)
156 | # - The flags `--cog-version COG14` and `--pfam-version 32.0` directs anvio to download the 2014 version of the COG database and v32.0 of Pfam, which are used by PlasX. Without these flags, anvio will by default download the latest versions of COG (v. 2020) and Pfam (v35.0), which PlasX does not use.
157 | # - The flags `--cog-data-dir COG2014` and `--pfam-data-dir Pfam_v32` directs anvio to store the COG and Pfam databases in new subfolders named `COG_2014` and `Pfam_v32`, respectively.
158 | anvi-setup-ncbi-cogs --cog-version COG14 --cog-data-dir COG_2014 -T $THREADS
159 | anvi-setup-pfams --pfam-version 32.0 --pfam-data-dir Pfam_v32
160 | ```
161 |
162 | ### Annotate COGs and Pfams and export to text files
163 |
164 |
165 | ```bash
166 | # Annotate COGs
167 | anvi-run-ncbi-cogs -T $THREADS --cog-version COG14 --cog-data-dir COG_2014 -c $PREFIX.db
168 |
169 | # Annotate Pfams
170 | anvi-run-pfams -T $THREADS --pfam-data-dir Pfam_v32 -c $PREFIX.db
171 |
172 | # Export functions to text file
173 | anvi-export-functions --annotation-sources COG14_FUNCTION,Pfam -c $PREFIX.db -o $PREFIX-cogs-and-pfams.txt
174 | ```
175 |
176 |
177 | ```bash
178 | # You should see something like this
179 | head $PREFIX-cogs-and-pfams.txt
180 | ```
181 |
182 | gene_callers_id source accession function e_value
183 | 0 COG14_FUNCTION COG0187 DNA gyrase/topoisomerase IV, subunit B 4.4e-136
184 | 1 COG14_FUNCTION COG0542 ATP-dependent Clp protease ATP-binding subunit ClpA 1.7e-95
185 | 3 COG14_FUNCTION COG3512 CRISPR/Cas system-associated protein Cas2, endoribonuclease 2.1e-28
186 | 4 COG14_FUNCTION COG1518 CRISPR/Cas system-associated endonuclease Cas1 3.1e-30
187 | 5 COG14_FUNCTION COG1393 Arsenate reductase and related proteins, glutaredoxin family 1.9e-61
188 | 6 COG14_FUNCTION COG0468 RecA/RadA recombinase 4.4e-180
189 | 7 COG14_FUNCTION COG1058!!!COG1546 Predicted nucleotide-utilizing enzyme related to molybdopterin-biosynthesis enzyme MoeA!!!Nicotinamide mononucleotide (NMN) deamidase PncC 7.8e-170
190 | 8 COG14_FUNCTION COG2818 3-methyladenine DNA glycosylase Tag 3.1e-21
191 | 9 COG14_FUNCTION COG0632 Holliday junction resolvasome RuvABC DNA-binding subunit 6.8e-84
192 |
193 |
194 |
195 | ## Step 2. Annotate *de novo* gene families
196 |
197 | ### Change into the Anaconda environment that contains PlasX
198 |
199 |
200 | ```bash
201 | conda deactivate
202 | conda activate plasx
203 | ```
204 |
205 | ### Download a pretrained PlasX machine learning model. This consists of a pretrained database of *de novo* families and a set of logistic regression coefficients.
206 |
207 |
208 | ```bash
209 | # By default, the model will be downloaded to the location that PlasX was installed. Thus, you only need to run this command once for your PlasX installation.
210 | # - ~5 min download on fast network
211 | plasx setup \
212 | --de-novo-families 'https://zenodo.org/record/5819401/files/PlasX_mmseqs_profiles.tar.gz' \
213 | --coefficients 'https://zenodo.org/record/5819401/files/PlasX_coefficients_and_gene_enrichments.txt.gz'
214 | ```
215 |
216 | ### Annotate genes using the database of *de novo* gene families
217 |
218 | **Note that we have only tested the next command on Linux, and it might not run correctly on Mac OS and Windows machines. Most of PlasX's code is Python-based and should be capable of running on almost any operating system. However, this specific command depends on non-Python code from the [mmseqs2 software package, version 10.6d92c](https://github.com/soedinglab/MMseqs2), which may need to be installed and configured differently on non-Linux systems. In the future, we will provide support for running PlasX on Mac OS and Windows.**
219 |
220 |
221 | ```bash
222 | # ~1 hr if THREADS=4. ~5 min if THREADS=128.
223 | # - For faster processing, set THREADS to the number of CPU cores available.
224 | # - This command requires a high amount of RAM (at least ~60Gb). If your machine has low RAM, then you need to set the `--splits` flag to a high number.
225 | # This will split the de novo families into chunks, reducing the max RAM usage. E.g. if you have only ~8Gb, we recommend setting `--splits` to 32 or higher.
226 | plasx search_de_novo_families \
227 | -g $PREFIX-gene-calls.txt \
228 | -o $PREFIX-de-novo-families.txt \
229 | --threads $THREADS \
230 | --splits 32 \
231 | --overwrite
232 | ```
233 |
234 |
235 | ```bash
236 | # You should see something like this
237 | head $PREFIX-de-novo-families.txt
238 | ```
239 |
240 | gene_callers_id contig start stop direction rev_compd length e_value accession
241 | 1 AST0002_000000019451 1152 1908 r True 756 0.0 mmseqs_40_33078316
242 | 1 AST0002_000000019451 1152 1908 r True 756 0.0 mmseqs_30_43406241
243 | 1 AST0002_000000019451 1152 1908 r True 756 0.0 mmseqs_25_49900063
244 | 1 AST0002_000000019451 1152 1908 r True 756 0.0 mmseqs_20_50193611
245 | 2 AST0002_000000028382 94 766 r True 672 6.194e-19 mmseqs_30_33026007
246 | 2 AST0002_000000028382 94 766 r True 672 4.061e-32 mmseqs_20_18536381
247 | 2 AST0002_000000028382 94 766 r True 672 1e-45 mmseqs_5_34842522
248 | 3 AST0002_000000028382 762 1068 r True 306 9.561e-31 mmseqs_40_40392677
249 | 3 AST0002_000000028382 762 1068 r True 306 1.752e-36 mmseqs_30_46987655
250 |
251 |
252 |
253 |
254 | ## Step 3. Use PlasX to classify contigs as plasmid or non-plasmid sequences, based on the annotations in step #1 and #2
255 | PlasX assigns a score to every contig. This score ranges from 0 (likely not plasmid) to 1 (likely plasmid). We recommend applying a threshold of at least >0.5 to identify plasmids. You can raise this threshold even higher (e.g. >0.9) to filter for high-confidence plasmids.
256 |
257 |
258 | ```bash
259 | plasx predict \
260 | -a $PREFIX-cogs-and-pfams.txt $PREFIX-de-novo-families.txt \
261 | -g $PREFIX-gene-calls.txt \
262 | -o $PREFIX-scores.txt \
263 | --overwrite
264 | ```
265 |
266 |
267 | ```bash
268 | # The output should look like this. The first column are the contig names, and the second column is the PlasX score.
269 | # - In this example, PlasX reports that AST0002_000000001053 is probably not a plasmid (score is close to 0), while AST0002_000000008287 is probably a plasmid (score is close to 1)
270 | head $PREFIX-scores.txt
271 | ```
272 |
273 | contig score
274 | AST0002_000000001053 2.3737687782754214e-08
275 | AST0002_000000001122 2.995346606467998e-07
276 | AST0002_000000001459 6.333592291893041e-06
277 | AST0002_000000001776 0.9592232672966521
278 | AST0002_000000003048 0.5622421419516015
279 | AST0002_000000006389 0.6089640039139832
280 | AST0002_000000006967 0.2730847890122725
281 | AST0002_000000007621 0.6630016070098446
282 | AST0002_000000008287 0.9848824181163179
283 |
284 |
285 | # Reproduce plasmid predictions from the study ["The Genetic and Ecological Landscape of Plasmids in the Human Gut" by Michael Yu, Emily Fogarty, A. Murat Eren](https://www.biorxiv.org/content/10.1101/2020.11.01.361691v2).
286 |
287 | In this study, we predicted 226,194 plasmid contigs. You can download the PlasX scores of these plasmids at https://zenodo.org/record/5819401/files/predicted_plasmids_summary.txt.gz.
288 |
289 | ```bash
290 | wget https://zenodo.org/record/5819401/files/predicted_plasmids_summary.txt.gz
291 | gunzip predicted_plasmids_summary.txt.gz
292 | ```
293 |
294 | You can reproduce these scores by running PlasX on precomputed gene annotations at https://zenodo.org/record/5732447/files/predicted_plasmids_gene_annotations.txt.gz.
295 |
296 | ```bash
297 | # Download and extract precomputed gene annotations of predicted plasmids
298 | wget https://zenodo.org/record/5732447/files/predicted_plasmids_gene_annotations.txt.gz
299 | gunzip predicted_plasmids_gene_annotations.txt.gz
300 | ```
301 |
302 |
303 | ```bash
304 | # Run PlasX to calculate scores for the predicted plasmids
305 | plasx predict \
306 | -a predicted_plasmids_gene_annotations.txt \
307 | -o predicted_plasmids_scores.txt \
308 | --overwrite
309 | ```
310 |
311 |
312 | ```bash
313 | # Scores are written to a file that looks like this
314 | head predicted_plasmids_scores.txt
315 | ```
316 |
317 | contig score
318 | AST0002_000000000224 0.9713393458995763
319 | AST0002_000000000565 0.9999998989973333
320 | AST0002_000000000640 0.5220555371966891
321 | AST0002_000000000659 0.9999999966474049
322 | AST0002_000000000996 0.9932700514639006
323 | AST0002_000000001523 0.5269207274589872
324 | AST0002_000000001535 0.5845180870306678
325 | AST0002_000000001737 0.5296216606001394
326 | AST0002_000000001776 0.9726152909151958
327 |
328 |
329 | You can also reproduce the PlasX scores for all ~36,000,000 metagenomic contigs in our study (the predicted plasmids is a small subset of these contigs). You can do this from scratch by downloading the fasta files of all contigs at https://zenodo.org/record/5730607/files/metagenomes_contigs.tar.gz and then adapting the Tutorial with the appropriate file names. However, note that annotating genes will take a long time (~1 day using 256 CPU cores). To make things faster, you can skip the annotation step by downloading precomputed annotations at https://zenodo.org/record/5731658/files/metagenomes_gene_annotations.tar.gz, and then directly proceed to calculating PlasX scores.
330 |
331 | ```bash
332 | # Download and extract gene annotations of all metagenomic contigs. NOTE: this is a very large file that will take a few hours to download and extract.
333 | wget https://zenodo.org/record/5731658/files/metagenomes_gene_annotations.tar.gz
334 | tar -zxf metagenomes_gene_annotations.tar.gz
335 | ```
336 |
337 | ```bash
338 | # Run PlasX to calculate scores for all contigs from metagenome AST0002 (this command can be modified for any other metagenome)
339 | plasx predict \
340 | -a AST0002_gene_annotations.txt \
341 | -o AST0002-scores.txt \
342 | --overwrite
343 | ```
344 |
--------------------------------------------------------------------------------
/plasx/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/michaelkyu/PlasX/5c9acfd00a597da27ef5261acf72dbaf2117b645/plasx/__init__.py
--------------------------------------------------------------------------------
/plasx/compress_utils.py:
--------------------------------------------------------------------------------
1 | # Some of the code in this file was modified from the pickle-blosc software at https://github.com/limix/pickle-blosc. The license for pickle-blosc is reproduced below.
2 | #
3 | #
4 | # The MIT License (MIT)
5 | # =====================
6 | #
7 | # Copyright (c) `2018` `Danilo Horta`
8 | #
9 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
10 | # this software and associated documentation files (the "Software"), to deal in
11 | # the Software without restriction, including without limitation the rights to
12 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
13 | # of the Software, and to permit persons to whom the Software is furnished to do
14 | # so, subject to the following conditions:
15 | #
16 | # The above copyright notice and this permission notice shall be included in all
17 | # copies or substantial portions of the Software.
18 | #
19 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 | # SOFTWARE.
26 |
27 |
28 |
29 | import multiprocessing
30 | import pickle as pkl
31 | import blosc
32 | import io
33 | import time
34 | import os
35 |
36 | def set_threads(threads=None):
37 | from plasx import utils
38 |
39 | if threads is None:
40 | # Get the maximum number of cores on this machine
41 | threads = utils.get_max_threads()
42 |
43 | blosc.set_nthreads(threads)
44 |
45 |
46 | def blosc_compress(obj, path_or_buf=None, cname='zstd', shuffle=None, clevel=5, obj_type=None):
47 | """Compresses a Python object `obj` using the blosc library, and writes to `path_or_buf`
48 |
49 | obj_type :
50 |
51 | If 'str', then `obj` is a Python string that is encoded and
52 | then compressed. If 'pickle', then the object is pickled and
53 | then compressed. Default: `obj` is assumed to be a binary
54 | value to be compressed directly
55 |
56 | """
57 | if shuffle is None:
58 | shuffle = blosc.NOSHUFFLE
59 |
60 | if obj_type=='str':
61 | arr = obj.encode()
62 | elif obj_type=='pickle':
63 | # arr = pkl.dumps(obj, -1)
64 |
65 | # Set a pickle protocol of 4
66 | # -- to avoid having to support protocol 3 and below
67 | # -- and to avoid someone else running a newer version of Python inadvertently pickling with protocol >=5 (which then cannot be read by other users of PlasX)
68 | arr = pkl.dumps(obj, 4)
69 | else:
70 | arr = obj
71 |
72 | start = time.time()
73 | if path_or_buf:
74 | with open(path_or_buf, "wb") as f:
75 | s = 0
76 | while s < len(arr):
77 | e = min(s + blosc.MAX_BUFFERSIZE, len(arr))
78 | carr = blosc.compress(arr[s:e], typesize=8, cname=cname, shuffle=shuffle, clevel=clevel)
79 | f.write(carr)
80 | s = e
81 | pickle_time = time.time() - start
82 | size = os.path.getsize(path_or_buf)
83 | return pickle_time, size
84 | else:
85 | s = 0
86 | carr_list = []
87 | while s < len(arr):
88 | e = min(s + blosc.MAX_BUFFERSIZE, len(arr))
89 | carr = blosc.compress(arr[s:e], typesize=8, cname=cname, shuffle=shuffle, clevel=clevel)
90 | carr_list.append(carr)
91 | s = e
92 | carr = b''.join(carr_list)
93 | return carr
94 |
95 | class BloscReadStream(io.RawIOBase):
96 | def __init__(self, path_or_buf, verbose=False, bufsize=None, obj_type='file'):
97 | """
98 | If path_or_buf is supposed to bytes, and not a file-like object, then there are two options:
99 |
100 | (1) Before calling __init__(), wrap path_or_buf into a file-like object with io.BytesIO(path_or_buf)
101 | (2) Set obj_type=='bytes'
102 | """
103 |
104 | if obj_type=='file':
105 | if isinstance(path_or_buf, io.IOBase):
106 | self.f = path_or_buf
107 | else:
108 | assert os.path.exists(path_or_buf)
109 | self.f = open(path_or_buf, "rb")
110 | elif obj_type=='bytes':
111 | self.f = io.BytesIO(path_or_buf)
112 | else:
113 | raise Exception('Unsupported input type: {}'.format(obj_type))
114 | self.count = 0
115 | self.read_time = 0
116 | self.verbose = verbose
117 |
118 | if bufsize is None:
119 | bufsize = int(8e9)
120 | self.arr = memoryview(bytearray(bufsize))
121 | self.start = 0
122 | self.end = 0
123 | self.cblock = None
124 |
125 | def close(self):
126 | self.f.close()
127 |
128 | def readable(self):
129 | return True
130 |
131 | def read(self, n):
132 | """TODO: preallocate a buffer for self.f.read(ctbytes), to prevent new
133 | allocation for every read. The size of this buffer can be
134 | pre-empted by seeking through all of the headers in the file.
135 |
136 | """
137 |
138 | start = time.time()
139 | if self.verbose:
140 | print(time.time(), 'n: %s (%0.2f Gb)' % (n, n / 1e9))
141 | #print('n: %s (%0.2f Gb)' % (n, n / 1e9))
142 |
143 | if self.verbose:
144 | print('\tStart:', self.start, 'End:', self.end, 'Buffer size:', len(self.arr))
145 |
146 | if len(self.arr) < n:
147 | if self.verbose:
148 | print('\tExtending buffer from %s to %s bytes' % (len(self.arr), n))
149 | print('\tCurrent start / end:', self.start, self.end)
150 | newarr = memoryview(bytearray(n))
151 | newarr[ : self.end - self.start ] = self.arr[self.start : self.end]
152 | self.arr = newarr
153 | self.start, self.end = 0, self.end - self.start
154 | elif (len(self.arr) - self.end) < n:
155 | if self.verbose:
156 | print('\tShifting %s bytes' % (self.end - self.start))
157 | self.arr[ : self.end - self.start] = self.arr[self.start : self.end]
158 | self.start, self.end = 0, self.end - self.start
159 |
160 | while (self.end - self.start) < n:
161 | # Read the BLOSC 16-byte header. See https://github.com/Blosc/c-blosc/blob/master/README_HEADER.rst
162 | header = self.f.read(16)
163 | if len(header) == 0:
164 | if self.verbose: print('\tEmpty header')
165 | break
166 | nbytes = int.from_bytes(header[4:8], "little")
167 | ctbytes = int.from_bytes(header[12:16], "little")
168 |
169 | if self.cblock is None:
170 | self.cblock = memoryview(bytearray(ctbytes))
171 | elif len(self.cblock) < ctbytes:
172 | self.cblock = memoryview(bytearray(max(ctbytes, 2*len(self.cblock))))
173 |
174 | if len(self.arr) < (self.end + nbytes):
175 | # Extend the buffer array `self.arr`. Extend by either
176 | # twice the length of the array or the required length
177 | # to accomodate the next decompression, whichever is
178 | # longer
179 | bufsize = max(2*len(self.arr), self.end+nbytes)
180 | if self.verbose: print('\tExtending new buffer from %s to %s bytes' % (len(self.arr), bufsize))
181 | newarr = memoryview(bytearray(bufsize))
182 | newarr[:self.end] = self.arr[:self.end]
183 | self.arr = newarr
184 |
185 | self.cblock[:16] = header
186 | self.cblock[16 : ctbytes] = self.f.read(ctbytes - 16)
187 | self.arr[self.end : self.end + nbytes] = blosc.decompress(self.cblock[: ctbytes])
188 |
189 | self.end += nbytes
190 |
191 | self.count += 1
192 | if self.verbose: print('\tRead iteration:', self.count,
193 | ', compress/decompress block size: %s / %s' % (ctbytes, nbytes))
194 |
195 | new_start = self.start + n
196 | if self.end < new_start:
197 | if verbose:
198 | print('\tRequested {:n} bytes, but only sending back {:n} bytes'.format(n, self.end - self.start))
199 |
200 | # I think this should never happen, because pickle should
201 | # not over-request more bytes than is in the actual object
202 | # (I assume the pickle format knows about the total data
203 | # size)
204 | raise Exception('Check if this is proper behavior and okay, or if it indicates a bug')
205 | new_start = self.end
206 |
207 | retval = self.arr[self.start : new_start]
208 | self.start = new_start
209 |
210 | delta_time = time.time() - start
211 | if self.verbose: print('\tRead and decompress time:', delta_time)
212 | self.read_time += delta_time
213 |
214 | return retval
215 |
216 | def readinto(self, b):
217 | raise(NotImplementedError)
218 |
219 | def readline(self, size):
220 | raise(NotImplementedError)
221 |
222 |
223 | def blosc_decompress(path_or_buf, stream='auto', obj_type=None, verbose=False):
224 | """
225 | Decompress the file `path_or_buf`, which is assumed to be created by the function `blosc_compress`
226 |
227 | There was a bug in pickle-blosc on reading the number of bytes in the header. I've fixed it.
228 | """
229 |
230 |
231 | if stream=='auto':
232 | if not isinstance(path_or_buf, bytes) and os.path.exists(path_or_buf) and (os.path.getsize(path_or_buf) >= 32e9):
233 | # Stream only if this is a file and is >=32GB in size
234 | stream = True
235 | else:
236 | stream = False
237 |
238 | if isinstance(path_or_buf, bytes):
239 | path_or_buf = io.BytesIO(path_or_buf)
240 |
241 | if stream:
242 | assert obj_type=='pickle'
243 | return pkl.load(BloscReadStream(path_or_buf, verbose=verbose))
244 | else:
245 | arr = []
246 |
247 | try:
248 | f = open(path_or_buf, "rb")
249 | opened = True
250 | except:
251 | f = path_or_buf
252 | opened = False
253 | finally:
254 | while True:
255 | # Read the BLOSC 16-byte header. See https://github.com/Blosc/c-blosc/blob/master/README_HEADER.rst
256 | header = f.read(16)
257 | if len(header) == 0:
258 | break
259 | ctbytes = int.from_bytes(header[12:16], "little")
260 | carr = header + f.read(ctbytes - 16)
261 | arr.append(blosc.decompress(carr))
262 | if opened:
263 | f.close()
264 |
265 | if obj_type=='str':
266 | return (b"".join(arr)).decode()
267 | elif obj_type=='pickle':
268 | return pkl.loads(b"".join(arr))
269 | else:
270 | return b"".join(arr)
271 |
272 | def pickle(obj, path_or_buf, cname='zstd', shuffle=None, clevel=5, compress=True, makedirs=False, threads=None):
273 | if makedirs:
274 | os.makedirs(os.path.dirname(path_or_buf), exist_ok=True)
275 |
276 | set_threads(threads)
277 |
278 | if compress:
279 | return blosc_compress(obj, path_or_buf, cname='zstd', shuffle=None, clevel=clevel, obj_type='pickle')
280 | else:
281 | with open(path_or_buf, 'wb') as f:
282 | pkl.dump(obj, f)
283 |
284 | def unpickle(path_or_buf, stream='auto', verbose=False, keys=None, threads=None):
285 |
286 | set_threads(threads)
287 |
288 | ret = blosc_decompress(path_or_buf, stream=stream, obj_type='pickle', verbose=verbose)
289 |
290 | import gc ; gc.collect()
291 |
292 | def iterable_get(ret, key_list):
293 | x = ret
294 | for k in key_list:
295 | x = x[k]
296 | return x
297 |
298 | if keys is not None:
299 | if isinstance(keys, str):
300 | keys = [keys]
301 |
302 | # If `keys` is specified, then the data is assumed to be a
303 | # dictionary. Return the values in the dictionary at `keys`
304 | ret = [iterable_get(ret, k) if isinstance(k, list) else ret[k] for k in keys]
305 |
306 | import gc ; gc.collect()
307 |
308 | return ret
309 |
310 | def write_compressed_txt(obj, path_or_buf, cname='zstd', shuffle=None, clevel=5):
311 | return blosc_compress(obj, path_or_buf, cname='zstd', shuffle=None, clevel=clevel, obj_type='str')
312 |
313 | def read_compressed_txt(path_or_buf):
314 | return blosc_decompress(path_or_buf, stream='auto', obj_type='str')
315 |
--------------------------------------------------------------------------------
/plasx/constants.py:
--------------------------------------------------------------------------------
1 | import plasx
2 | from pathlib import Path
3 |
4 | #ident_list = [90, 80, 70, 60, 50, 40, 30, 25, 20, 15, 10, 5]
5 |
6 | ident_list = [90, 80, 70, 60, 50, 40, 30, 25, 20, 5]
7 |
8 | data_dir = Path(plasx.__file__).parent / 'data'
9 |
--------------------------------------------------------------------------------
/plasx/fasta_utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import shutil
3 | import subprocess
4 | import tempfile
5 | from pathlib import Path
6 |
7 | import numpy as np
8 | import pandas as pd
9 |
10 | from plasx import utils, compress_utils
11 |
12 | def gene_calls_to_fasta(gene_calls, source=None, output=None, compress=None):
13 | """Converts a table of gene calls (where one column is amino acid sequence) into a fasta string
14 |
15 | The headers in the fasta are formatted as (inspired by anvio's format)
16 |
17 | >{id}|contig:{contig_name}|start:{start}|stop:{stop}|direction:{direction}|rev_compd:{rev_compd}|length:{length}
18 |
19 | Note: This function is called as a subroutine in get_gene_sequences(), but it can also be called independently.
20 | """
21 |
22 | gene_calls = utils.read_table(gene_calls)
23 |
24 | gene_calls = gene_calls.dropna(subset=['aa_sequence'])
25 | if source is not None:
26 | gene_calls = gene_calls[gene_calls['source']==source]
27 |
28 | fasta_items = '>' + gene_calls['gene_callers_id'].astype(str) + \
29 | '|contig:' + gene_calls['contig'].astype(str) + \
30 | '|start:' + gene_calls['start'].astype(str) + \
31 | '|stop:' + gene_calls['stop'].astype(str) + \
32 | '|direction:' + gene_calls['direction'].astype(str) + \
33 | '|rev_compd:' + (gene_calls['direction']=='r').astype(str) + \
34 | '|length:' + (gene_calls['stop'] - gene_calls['start']).astype(str) + \
35 | '\n' + gene_calls['aa_sequence']
36 |
37 | fasta = '\n'.join(fasta_items)
38 |
39 | if output is not None:
40 | # Write fasta into a plain text file (optionally, compressed)
41 | if compress:
42 | compress_utils.write_compressed_txt(fasta, output)
43 | else:
44 | with open(output, 'wb') as f:
45 | f.write(fasta+'\n')
46 |
47 | return fasta
48 |
49 | def subset_fasta(headers, fa_path):
50 | """Return a subset of the sequences in a fasta file.
51 |
52 | headers : The headers of the desired sequences
53 |
54 | fa_path : path to fasta file
55 | """
56 |
57 | raise Exception('Deprecated. Use utils.get_fasta_dict()')
58 |
59 | headers = set(headers)
60 | sequences = []
61 |
62 | from Bio import SeqIO
63 | for seq in SeqIO.parse(fa_path, 'fasta'):
64 | if seq.name in headers:
65 | sequences.append(seq)
66 | return sequences
67 |
68 | def run_alv(fa, width=None):
69 |
70 | if width is None:
71 | width = 150
72 |
73 | with tempfile.NamedTemporaryFile('wt') as f:
74 | f.write(fa)
75 | f.flush()
76 | # alv_proc = subprocess.run(['/scratch/miniconda/envs/anvio-master-zelda/bin/alv', '-k', '-w', str(width), f.name],
77 |
78 | # alv_proc = subprocess.run(['alv', '-k', '-w', str(width), f.name], capture_output=True)
79 | alv_proc = subprocess.run(' '.join(['alv', '-k', '-w', str(width), f.name]), capture_output=True, shell=True)
80 |
81 | alv_proc.check_returncode()
82 | alv_output = alv_proc.stdout.decode()
83 | return alv_output
84 |
85 | def muscle(sequences, intype=None, rettype='fasta', width=None, headers=None, cmd=None):
86 | #child = subprocess.Popen('/scratch/miniconda/envs/anvio-master-zelda/bin/muscle',
87 | if cmd is None:
88 | cmd = 'muscle'
89 | # cmd = 'muscle -maxiters 2 -diags1'
90 | # cmd = 'muscle -maxiters 1 -diags1 -sv -distance1 kbit20_3'
91 |
92 | # cmd = shlex.split(cmd)
93 | shell = True
94 |
95 | if isinstance(sequences, dict):
96 | # print(sequences.items())
97 | headers, sequences = list(zip(*sequences.items()))
98 | elif (intype is None) or (intype=='seq_list'):
99 | if headers is None:
100 | headers = ('seq%s' % i for i in range(len(sequences)))
101 | else:
102 | raise Exception("Unsupported input format")
103 |
104 | child = subprocess.Popen(cmd,
105 | stdin=subprocess.PIPE,
106 | stdout=subprocess.PIPE,
107 | stderr=subprocess.PIPE,
108 | universal_newlines=True,
109 | shell=shell)
110 |
111 | for h, seq in zip(headers, sequences):
112 | if os.path.isfile(seq):
113 | from Bio import SeqIO
114 | tmp = SeqIO.read(seq, 'fasta')
115 | h, seq = tmp.name, tmp.seq
116 | child.stdin.write('>%s\n%s\n' % (h, seq))
117 | child.stdin.close()
118 |
119 | muscle_fa = child.stdout.read()
120 |
121 | if rettype=='fasta':
122 | return muscle_fa
123 | elif rettype=='alv':
124 | return run_alv(muscle_fa, width=width)
125 | else:
126 | raise Exception("Unsupported output format")
127 |
128 | def fasta_dict_2_str(fasta_dict):
129 | """Converts dictionary mapping fasta headers to sequences, to a fasta string"""
130 |
131 | return '\n'.join('>{}\n{}\n'.format(h,s) for h,s in fasta_dict.items()) + '\n'
132 |
133 | def write_fasta(fasta, output, separate=False, compressed=False, input_type=None):
134 | """Writes fasta to file. Can take in a fasta string or dictionary.
135 |
136 | output:
137 |
138 | Write all sequences to this file (or directory, if separate=True)
139 |
140 | separate:
141 |
142 | If True, write each sequence into a separate file into the
143 | output directory. Each file will be named as .fa
144 |
145 | """
146 |
147 | if input_type is None:
148 | if isinstance(fasta, pd.Series):
149 | fasta = fasta.to_dict()
150 | input_type = 'dict'
151 | elif isinstance(fasta, dict):
152 | input_type = 'dict'
153 | elif isinstance(fasta, str):
154 | input_type = 'str'
155 | else:
156 | raise Exception('Cannot infer fasta input type')
157 | assert input_type in ['dict', 'str']
158 |
159 | if separate:
160 | if input_type == 'str':
161 | fasta = get_fasta_dict(fasta, input_type=='str')
162 |
163 | os.makedirs(output, exist_ok=True)
164 | for h, s in fasta.items():
165 | write_fasta('>{}\n{}\n'.format(h,s),
166 | output=os.path.join(output, '{}.fa'.format(h)),
167 | compressed=compressed)
168 | else:
169 | if input_type == 'dict':
170 | fasta = fasta_dict_2_str(fasta)
171 |
172 | if compressed:
173 | compress_utils.write_compressed_txt(fasta, output)
174 | else:
175 | with open(output, 'wt') as o:
176 | o.write(fasta)
177 |
178 | def get_fasta_dict(fasta, input_type=None, input_fmt='fasta', subset=None, verbose=False, n_jobs=None):
179 | """Reads in the filename or the fasta string itself, and outputs a
180 | dictionary mapping fasta headers to sequences.
181 |
182 | fasta :
183 |
184 | Can be a list of inputs, each of which are opened and then all fasta headers+sequences are concatenated in a single dictionary.
185 |
186 | input_type :
187 |
188 | If 'str', then `fasta` is interpreted as the fasta string itself
189 |
190 | If 'filename', then `fasta` is interpreted as a file path
191 |
192 | If 'pickle', then 'fasta' is interpreted as a pickled file
193 |
194 | If None, then the type is inferred.
195 |
196 | """
197 |
198 | if input_type is None:
199 | ## Infer input type
200 | if isinstance(fasta, (str, Path)):
201 | if os.path.exists(fasta):
202 | fasta = str(fasta)
203 |
204 | if fasta[-8:]=='.pkl.blp':
205 | input_type = 'pickle'
206 | elif fasta[-4:]=='.blp':
207 | input_type = 'blp'
208 | elif fasta[-3:]=='.gz':
209 | input_type = 'gz'
210 | else:
211 | input_type = 'filename'
212 | else:
213 | input_type = 'str'
214 | elif hasattr(fasta, '__iter__'):
215 | if isinstance(fasta, dict):
216 | input_type = 'dict'
217 | else:
218 | input_type = 'list'
219 |
220 | if input_type=='list':
221 | if n_jobs is None:
222 | n_jobs = 1
223 | n_jobs = min(n_jobs, len(fasta))
224 |
225 | fasta_dict = {}
226 | if n_jobs==1:
227 | for f in fasta:
228 | fasta_dict.update(get_fasta_dict(f, subset=subset, verbose=verbose))
229 |
230 | else:
231 | from joblib import Parallel, delayed
232 | results = Parallel(n_jobs=n_jobs)(delayed(get_fasta_dict)(f, subset=subset, verbose=10) for f in fasta)
233 | for f in results:
234 | fasta_dict.update(f)
235 | else:
236 | assert not isinstance(subset, str), Exception('`subset` cannot be a string.')
237 |
238 | #parse_with_SeqIO = True
239 | parse = True
240 |
241 | if input_type=='pickle':
242 | if verbose: print('Reading {}'.format(fasta))
243 | fasta = compress_utils.unpickle(fasta)
244 | if isinstance(fasta, bytes):
245 | fasta = fasta.decode()
246 |
247 | if isinstance(fasta, dict):
248 | return fasta
249 |
250 | import io
251 | fasta = io.StringIO(fasta)
252 | elif input_type=='blp':
253 | fasta = compress_utils.read_compressed_txt(fasta)
254 | import io
255 | fasta = io.StringIO(fasta)
256 | elif input_type=='gz':
257 | import gzip
258 | fasta = gzip.open(fasta, 'rt')
259 | elif input_type=='str':
260 | import io
261 | fasta = io.StringIO(fasta)
262 | elif input_type=='filename':
263 | if verbose: print('Reading {}'.format(fasta))
264 | elif input_type=='dict':
265 | # parse_with_SeqIO = False
266 | parse = False
267 | else:
268 | raise Exception()
269 |
270 | # if parse_with_SeqIO:
271 | # from Bio import SeqIO
272 | # fasta_list = ((record.id, str(record.seq)) for record in SeqIO.parse(fasta, input_fmt))
273 | if parse:
274 | fasta_list = parse_fasta_file(fasta).items()
275 | else:
276 | fasta_list = fasta.items()
277 |
278 | if isinstance(subset, str):
279 | raise Exception('`subset` cannot be a string.')
280 | elif subset is None:
281 | # fasta_dict = {record.id : str(record.seq) for record in itertools.islice(SeqIO.parse(fasta, input_fmt), 0, 10000000)}
282 | # fasta_dict = {record.id : str(record.seq) for record in SeqIO.parse(fasta, input_fmt))}
283 | fasta_dict = {header : seq for header, seq in fasta_list}
284 | elif callable(subset):
285 | # fasta_dict = {record.id : str(record.seq) for record in SeqIO.parse(fasta, input_fmt) if subset(record.id)}
286 | fasta_dict = {header : seq for header, seq in fasta_list if subset(header)}
287 | elif hasattr(subset, '__iter__'):
288 | # fasta_dict = {record.id : str(record.seq) for record in SeqIO.parse(fasta, input_fmt) if record.id in subset}
289 | fasta_dict = {header : seq for header, seq in fasta_list if header in subset}
290 |
291 | return fasta_dict
292 |
293 | def parse_fasta_file(fasta):
294 | """Parses a fasta file into a dictionary"""
295 | fasta_dict = {}
296 |
297 | def add_seq(key, seq):
298 | fasta_dict[key] = ''.join([x.strip() for x in seq])
299 |
300 | with open(fasta, 'rt') as f:
301 | is_first_seq = True
302 | for line in f.readlines():
303 | if len(line)==0:
304 | continue
305 | elif line.startswith('>'):
306 | if not is_first_seq:
307 | # Add previous sequence
308 | add_seq(key, seq)
309 |
310 | # Start of a new sequence
311 | is_first_seq = False
312 | key = line[1:].strip()
313 | seq = []
314 | else:
315 | seq.append(line)
316 |
317 | add_seq(key, seq)
318 |
319 | return fasta_dict
320 |
321 | def concat_fasta_files(input_list, output, compress='infer', verbose=True):
322 | """
323 | Reads sequences from multiple fasta files, and concatenates them into a single file
324 |
325 | TODO: merge this with `concat_files`
326 | """
327 |
328 | with open(output, 'w') as f:
329 | for i, fa_path in enumerate(input_list):
330 | if verbose and (i%100==0): print(i, end=',')
331 | if compress=='blp' or (compress=='infer' and str(fa_path)[-4:]=='.blp'):
332 | fa = compress_utils.read_compressed_txt(fa_path)
333 | else:
334 | with open(fa_path, 'r') as g:
335 | fa = g.read()
336 | f.write(fa)
337 | f.write('\n')
338 | if verbose: print()
339 |
340 | def concat_files(input_files, output_file, filesep=None):
341 | """
342 | Concatenates files together, byte for byte.
343 |
344 | Optionally, append an string (e.g. newline) between files. Be careful that newlines are encoded appropriately.
345 |
346 | Code inspired by https://stackoverflow.com/questions/13613336/python-concatenate-text-files
347 | """
348 |
349 | if isinstance(filesep, str):
350 | # Attempt to encode string into bytes
351 | filesep = filesep.encode()
352 |
353 | with open(output_file,'wb') as wfd:
354 | for f in input_files:
355 | with open(f,'rb') as fd:
356 | shutil.copyfileobj(fd, wfd)
357 |
358 | if filesep is not None:
359 | wfd.write(filesep)
360 |
361 | def index_fasta_headers(input_fa, output_fa, start_count=0, header_filter=None):
362 | """Formats a fasta file, so that the sequence headers are replaced
363 | with consecutive integers, e.g. 0,1,2,...
364 |
365 | TO_IMPLEMENT: if `nr` is True, then redundant sequences are checked and removed (they are given the same index)
366 |
367 | input_fa : input fasta file
368 |
369 | output_fa : output fasta file, with renamed headers
370 |
371 | header_file : Two column table, with first column being the
372 | original header, and the second column being the new header
373 |
374 | start_count : The start of the header indexing (Default: 0)
375 |
376 | Returns
377 | --------
378 |
379 | headers : list of the original headers, in the same order as the input
380 |
381 | """
382 | count = start_count
383 | headers = []
384 | headers_df_list = []
385 |
386 | max_headers_per_chunk = 5000000
387 |
388 | if isinstance(input_fa, (str, Path)):
389 | input_fa = [ input_fa ]
390 |
391 | with open(output_fa, 'wt') as out:
392 | for i_fa_idx, i_fa in enumerate(input_fa):
393 | if (i_fa_idx%100)==0: utils.tprint(i_fa_idx, end=', ')
394 |
395 | i_fa = str(i_fa)
396 |
397 | try:
398 | if i_fa[-4:]=='.blp':
399 | open_file = False
400 | f = compress_utils.read_compressed_txt(i_fa).splitlines()
401 | else:
402 | open_file = True
403 | f = open(i_fa, 'rt')
404 |
405 | keep_sequence = False
406 | for i, x in enumerate(f):
407 | x = x.strip() # Remove newlines
408 |
409 | if len(x)>0:
410 | if x[0]=='>':
411 | x = x[1:]
412 |
413 | keep_sequence = (header_filter is None) or header_filter(x)
414 | if keep_sequence:
415 | if count > start_count:
416 | out.write('\n')
417 |
418 | # Write sequence to file
419 | out.write('>%s\n' % count)
420 | headers.append(x)
421 | count += 1
422 |
423 | if len(headers) == max_headers_per_chunk:
424 | utils.tprint('Read %s sequences' % (count - start_count))
425 | headers_df_list.append(fasta_headers_to_table(headers))
426 | if len(headers_df_list) > 0:
427 | headers_df_list = [ utils.better_pd_concat(headers_df_list, ignore_index=True) ]
428 | headers = []
429 | elif keep_sequence:
430 | out.write(x)
431 | finally:
432 | if open_file:
433 | f.close()
434 |
435 | headers_df_list.append(fasta_headers_to_table(headers))
436 | headers_df = utils.better_pd_concat(headers_df_list, ignore_index=True)
437 |
438 | if start_count != 0:
439 | # The default index is 0,1,2,..., because "ignore_index=True" is passed to pd.concat
440 | # If start_count is not 0, then manually need to set the index
441 | headers_df = np.arange(start_count, start_count + headers_df.shape[0])
442 |
443 | return headers_df
444 |
445 | def fasta_headers_to_table(headers):
446 | """Takes the fasta headers that are output by anvi-get-sequences-for-gene-calls and parses them out into a table.
447 |
448 | Table has memory-efficient data types, i.e. strings are converted into categoricals
449 | """
450 |
451 | df = pd.Series(headers).str.split('|', expand=True)
452 | df.columns = ['gene_callers_id', 'contig', 'start', 'stop', 'direction', 'rev_compd', 'length']
453 | df['gene_callers_id'] = df['gene_callers_id'].astype(np.int64)
454 | for c in df.columns[1:]:
455 | x = df[c].str.split(':', expand=True)[1]
456 | if c in ['contig', 'direction']:
457 | df[c] = x.astype('category')
458 | elif c in ['start', 'stop', 'length']:
459 | df[c] = x.astype(np.dtype('int64'))
460 | elif c=='rev_compd':
461 | #df[c] = x.astype('bool')
462 | df[c] = (x == 'True').astype('bool')
463 | return df
464 |
--------------------------------------------------------------------------------
/plasx/learn.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import numpy as np
4 |
5 | import scipy
6 |
7 | def lr_transform_base(coef, intercept, X, prob=False):
8 | coef = np.array(coef)
9 | intercept = np.array(intercept)
10 |
11 | assert np.squeeze(coef).ndim==1 and intercept.ndim==0
12 |
13 | X_eff = (X.dot(coef.reshape(-1,1)) + intercept).flatten()
14 | if prob:
15 | from scipy.special import expit
16 | Y_hat = expit(X_eff)
17 | return Y_hat
18 | else:
19 | return X_eff
20 |
21 | def lr_transform(lr, X, prob=False):
22 | lr_transform_base(lr.coef_, lr.intercept_, X, prob=prob)
23 |
24 |
--------------------------------------------------------------------------------
/plasx/model.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import numpy as np
4 | import pandas as pd
5 |
6 | from plasx import utils, constants, learn
7 |
8 | class PlasX_model:
9 | """Consists of a logistic regression set of coefficients, and a list of annotation sources."""
10 |
11 | def __init__(self, coef, intercept, features, params):
12 |
13 | self.coef = coef
14 | self.intercept = intercept
15 | self.features = features
16 | self.params = params
17 |
18 | @classmethod
19 | def load(cls, path):
20 | """First try unpickling, and if that doesn't work, then try parsing it as a text table"""
21 |
22 | try:
23 | return utils.unpickle(path)
24 | except:
25 | return cls.from_table(path)
26 |
27 | def save(self, path):
28 | utils.pickle(self, path)
29 |
30 | def __getstate__(self):
31 | return utils.subset_dict(self.__dict__.copy(), ['coef', 'intercept', 'features', 'params'])
32 |
33 | def __setstate__(self, state):
34 | self.__dict__.update(state)
35 |
36 | @classmethod
37 | def from_sklearn(cls, model, features):
38 | instance = cls(utils.as_flat(model.coef_), model.intercept_[0], features, model.get_params())
39 |
40 | # Remember the sklearn class name
41 | instance.params['class'] = str(type(model))
42 |
43 | return instance
44 |
45 | @classmethod
46 | def from_table(cls, path=None):
47 | if path is None:
48 | path = constants.data_dir / 'PlasX_coefficients_and_gene_enrichments.txt'
49 | if not os.path.exists(path):
50 | raise FileNotFoundError
51 |
52 | df = utils.read_table(path).set_index('accession')['PlasX_coefficient']
53 | assert 'INTERCEPT' in df.index,\
54 | "One of the accessions needs to be the word 'INTERCEPT', which represents the intercept of the logistic regression"
55 | df_coef = df.drop(index='INTERCEPT')
56 |
57 | instance = cls(list(df_coef.values), df.loc['INTERCEPT'], list(df_coef.index), {})
58 | return instance
59 |
60 | def _get_feature_matrix(self, C, contig_column, annotation_column, shift_1=False, verbose=False):
61 | """Converts a long-format table of gene family annotations into a contig-by-gene-family feature matrix.
62 |
63 | Return type is a scipy sparse csr matrix."""
64 |
65 | import scipy.sparse
66 |
67 | C = C.astype({col : 'category' for col in [contig_column, annotation_column]})
68 |
69 | # Remove annotations that are not in the vocab
70 | C = C[utils.catin(C[annotation_column], self.features)].copy()
71 | C[annotation_column] = C[annotation_column].cat.set_categories(self.features)
72 |
73 | utils.tprint('Pivoting annotation table into a contig-by-gene feature matrix', verbose=verbose)
74 | X, rownames, colnames = utils.sparse_pivot(C, index=contig_column, columns=annotation_column, rettype='spmatrix')
75 | rownames, colnames = np.array(rownames), np.array(colnames)
76 |
77 | # Check that categorical ordering of accessions is consistent with the model coefficients
78 | assert np.all(self.features == colnames)
79 | assert(len(self.coef) == len(colnames))
80 |
81 | # adds 1 to the accession values so that 0 is reserved to
82 | # designate padding (and then recognized for masking)
83 | # -- See learn.get_data() where this is done too
84 | if shift_1:
85 | # A dummy column of zeros
86 | pad_column = scipy.sparse.csr_matrix(([],([],[])),(X.shape[0],1), dtype=X.dtype)
87 | X = scipy.sparse.hstack([pad_column, X])
88 | colnames = np.append('PAD', colnames)
89 |
90 | X = scipy.sparse.csr_matrix(X)
91 |
92 | return X, rownames, colnames
93 |
94 | def predict(self, annotations, verbose=None, contig_column=None, annotation_column=None, gene_calls=None,
95 | output=None, output_kws=None):
96 |
97 | # If going to save file, check that overwriting is okay now, before doing more computation
98 | if (output is not None) and ('overwrite' in output_kws):
99 | utils.check_overwrite(output, output_kws['overwrite'])
100 |
101 | # Set default names of contig/annotation-columns
102 | if contig_column is None:
103 | contig_column = 'contig'
104 | annotation_column_was_none = False
105 | if annotation_column is None:
106 | annotation_column_was_none = True
107 | annotation_column = 'accession'
108 |
109 | if gene_calls is not None:
110 | gene_calls = utils.read_table(gene_calls, verbose=verbose)
111 |
112 | def map_gene_callers_id_to_contig(functions):
113 | """Maps gene_callers_id column to contig.
114 |
115 | Example use case: a table from anvi-export-functions
116 | contains only gene_callers_id. The mapping to contigs can
117 | be found from anvi-export-gene-calls
118 | """
119 |
120 | if (gene_calls is not None) and (contig_column not in functions.columns):
121 | functions = functions.merge(gene_calls[[contig_column, 'gene_callers_id']], on=['gene_callers_id'])
122 |
123 | return functions
124 |
125 | try:
126 | C = utils.read_table(annotations,
127 | cols=[contig_column, annotation_column],
128 | verbose=verbose,
129 | post_apply=map_gene_callers_id_to_contig)
130 | except KeyError:
131 | if annotation_column_was_none:
132 | annotation_column = 'annotation'
133 | C = utils.read_table(annotations,
134 | cols=[contig_column, annotation_column],
135 | verbose=verbose,
136 | post_apply=map_gene_callers_id_to_contig)
137 |
138 |
139 | # Process annotations table by string splitting '!!!'
140 | C = utils.df_str_split(C, '!!!', annotation_column)
141 |
142 | # Create contig-by-gene-family feature matrix
143 | utils.tprint('Formatting table', verbose=verbose)
144 | X, rownames, colnames = self._get_feature_matrix(C, contig_column, annotation_column)
145 |
146 | # Run model by applying logistic transformation
147 | utils.tprint('Calculating logistic transformation', verbose=verbose)
148 | pred = learn.lr_transform_base(self.coef, self.intercept, X, prob=True)
149 |
150 | # Format prediction scores into a pd.Series with the contigs as index
151 | utils.tprint('Creating pd.Series', verbose=verbose)
152 | pred = pd.Series(pred, index=rownames)
153 |
154 | print('output:', output)
155 |
156 | utils.write_table(pred.rename_axis('contig').rename('score').reset_index(),
157 | output,
158 | txt=True,
159 | **output_kws)
160 |
161 | return pred
162 |
--------------------------------------------------------------------------------
/plasx/nb_utils.py:
--------------------------------------------------------------------------------
1 | import heapq
2 | import time
3 | from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
4 |
5 | import numpy as np
6 | from numba import jit, vectorize, prange, int32, int64, float32, float64
7 |
8 | from plasx import utils
9 |
10 | """
11 | Utility functions implemented in numba
12 | """
13 |
14 | # @vectorize(nopython=True)
15 | # def nb_divide(x, y):
16 | # return x / y
17 |
18 | def nb_maximum_py(x, y):
19 | """Parallelized version of division"""
20 |
21 | z = np.empty(x.size, x.dtype)
22 | for i in prange(x.size):
23 | z[i] = max(x[i], y[i])
24 | return z
25 |
26 | def nb_minimum_py(x, y):
27 | """Parallelized version of division"""
28 |
29 | z = np.empty(x.size, x.dtype)
30 | for i in prange(x.size):
31 | z[i] = min(x[i], y[i])
32 | return z
33 |
34 | def nb_divide_py(x, y):
35 | """Parallelized version of division"""
36 |
37 | z = np.empty(x.size, x.dtype)
38 | for i in prange(x.size):
39 | z[i] = x[i] / y[i]
40 | return z
41 |
42 | def nb_add_py(x, y):
43 | """Parallelized version of add"""
44 |
45 | z = np.empty(x.size, x.dtype)
46 | for i in prange(x.size):
47 | z[i] = x[i] + y[i]
48 | return z
49 |
50 | def nb_subtract_py(x, y):
51 | """Parallelized version of add"""
52 |
53 | z = np.empty(x.size, x.dtype)
54 | for i in prange(x.size):
55 | z[i] = x[i] - y[i]
56 | return z
57 |
58 | def nb_cast_py(x, dtype):
59 | z = np.empty(x.size, dtype)
60 | for i in prange(x.size):
61 | z[i] = dtype(x[i])
62 | return z
63 |
64 | def nb_copy_py(x):
65 | z = np.empty(x.size, x.dtype)
66 | for i in prange(x.size):
67 | z[i] = x[i]
68 | return z
69 |
70 | def nb_idx_py(x, y):
71 | """Parallelized version of indexing"""
72 |
73 | z = np.empty(y.size, x.dtype)
74 | for i in prange(y.size):
75 | z[i] = x[y[i]]
76 | return z
77 |
78 | def nb_repeat_py(x,y):
79 | """Parallelized version of np.repeat"""
80 |
81 | # Cannot use prange to calculating cumsum
82 | y_sum = 0
83 | y_cumsum = np.empty(y.size, y.dtype)
84 | for i in range(y.size):
85 | y_cumsum[i] = y_sum
86 | y_sum += y[i]
87 |
88 | z = np.empty(y_sum, x.dtype)
89 | for i in prange(y.size):
90 | curr = y_cumsum[i]
91 | for j in range(y[i]):
92 | z[curr+j] = x[i]
93 | return z
94 |
95 | for func in ['nb_maximum', 'nb_minimum',
96 | 'nb_divide', 'nb_add', 'nb_subtract',
97 | 'nb_cast',
98 | 'nb_copy',
99 | 'nb_idx',
100 | 'nb_repeat']:
101 | exec("""{func} = jit({func}_py, nopython=True, nogil=True, fastmath=True, parallel=True)""".format(func=func))
102 | exec("""{func}_st = jit({func}_py, nopython=True, nogil=True, fastmath=True, parallel=False)""".format(func=func))
103 |
104 |
105 | # from numba import int32, int64, float32, float64
106 |
107 | # #@vectorize(nopython=True, parallel=True)
108 | # @vectorize([float64(int32, int32),
109 | # float64(int64, int64),
110 | # float32(float32, float32),
111 | # float64(float64, float64)], nopython=True, target='parallel')
112 | # def nb_divide2(x, y):
113 | # """Parallelized version of division"""
114 | # return x / y
115 | # # z = np.empty(x.size, x.dtype)
116 | # # for i in prange(x.size):
117 | # # z[i] = x[i] / y[i]
118 |
119 |
120 | @jit(nopython=True, nogil=True)
121 | def extend_1d_arr(x):
122 | """Extends a 1d array by twice its size, with random non-empty values
123 | at the second half
124 |
125 | """
126 | new_x = np.empty(x.size * 2, x.dtype)
127 | new_x[ : x.size] = x
128 | return new_x
129 |
130 | @jit(nopython=True, nogil=True)
131 | def extend_2d_arr(x):
132 | """Extends a 2d array by twice its ROWS, with random non-empty values
133 | at the second half
134 |
135 | """
136 |
137 | new_x = np.empty((x.shape[0] * 2, x.shape[1]), x.dtype)
138 | new_x[ : x.shape[0], :] = x
139 | return new_x
140 |
141 | @jit(nopython=True, nogil=True)
142 | def remove_duplicates(x):
143 | """
144 | Scans through x and removes duplicates.
145 |
146 | NOTE: Assumes the same x's are grouped consecutively
147 | """
148 |
149 | x_unique = np.zeros(100000, x.dtype)
150 | xc = x[0]
151 | g = 0
152 | for xx in x:
153 | if xx != xc:
154 | if g == x_unique.size:
155 | x_unique = extend_1d_arr(x_unique)
156 |
157 | x_unique[g] = xc
158 | xc = xx
159 | g += 1
160 |
161 | if g == x_unique.size:
162 | x_unique = extend_1d_arr(x_unique)
163 | x_unique[g] = xc
164 | x_unique = x_unique[: g+1]
165 | return x_unique
166 |
167 | @jit(nopython=True, nogil=True)
168 | def remove_duplicates_2d(x):
169 | """
170 | Scans through x and removes duplicates.
171 |
172 | NOTE: Assumes the same x's are grouped consecutively
173 | """
174 |
175 | x_unique = np.zeros((100000, x.shape[1]), x.dtype)
176 | xc = x[0,:]
177 | g = 0
178 | for xi in range(x.shape[0]):
179 | xx = x[xi,:]
180 | if (xx != xc).any():
181 | if g == x_unique.shape[0]:
182 | x_unique = extend_2d_arr(x_unique)
183 |
184 | x_unique[g, :] = xc
185 | xc = xx
186 | g += 1
187 |
188 | if g == x_unique.shape[0]:
189 | x_unique = extend_2d_arr(x_unique)
190 | x_unique[g, :] = xc
191 | x_unique = x_unique[: g+1, :]
192 | return x_unique
193 |
194 | @jit(nopython=True, nogil=True)
195 | def lexsort_nb(a, b):
196 | """numba implementation of np.lexsort. Taken from https://github.com/numpy/numpy/issues/12755"""
197 |
198 | idxs = np.argsort(a, kind="quicksort")
199 | return idxs[np.argsort(b[idxs], kind="mergesort")]
200 |
201 | @jit(nopython=True, nogil=True)
202 | def lexsort_nb2(a, first_mergesort=False):
203 | #def lexsort_nb2(a, first_kind='quicksort'):
204 | """Same as lexsort_nb(), but takes in a k-by-N array (sorting by k
205 | keys) instead of two keys (a and b) in lexsort_nb()
206 |
207 | first_mergesort : use mergesort for the first key
208 | """
209 |
210 | assert a.shape[0] >= 1
211 | # For the first sort, you can use either 'quicksort' or 'mergesort'
212 | # -- quicksort is generally faster if the array is unsorted (default)
213 | # -- mergesort is generally faster by almost 2x if the array is sorted (I need to do more testing to verify 2x. It seems sometimes that there's no significant speedup.
214 | if first_mergesort:
215 | idxs = np.argsort(a[0,:], kind="mergesort")
216 | else:
217 | idxs = np.argsort(a[0,:], kind='quicksort')
218 |
219 | for i in range(1, a.shape[0]):
220 | # For subsequent sorts, use mergesort to have stable sorting
221 | idxs = idxs[np.argsort(a[i,:][idxs], kind="mergesort")]
222 | return idxs
223 |
224 | def lexsort_nb2_py(a, first_mergesort=False):
225 | """Same as lexsort_nb2() but a python version in order to use numpy's
226 | native sort
227 |
228 | """
229 |
230 | assert a.shape[0] >= 1
231 | if first_mergesort:
232 | idxs = np.argsort(a[0,:], kind="mergesort")
233 | else:
234 | idxs = np.argsort(a[0,:], kind='quicksort')
235 |
236 | for i in range(1, a.shape[0]):
237 | # For subsequent sorts, use mergesort to have stable sorting
238 | idxs = idxs[np.argsort(a[i,:][idxs], kind="mergesort")]
239 | return idxs
240 |
241 | def test_lexsort(N=1000000):
242 | """Test runtime and correctness of numba lexsort implementations"""
243 |
244 | a = np.random.rand(N)
245 | b = np.random.randint(N // 4, size=N)
246 | ab = np.vstack((a,b))
247 |
248 | from IPython import get_ipython
249 | ipython = get_ipython()
250 |
251 | print('np.lexsort')
252 | ipython.magic("timeit np.lexsort([a, b])")
253 | print('lexsort_nb')
254 | ipython.magic("timeit lexsort_nb(a, b)")
255 | print('lexsort_nb2')
256 | ipython.magic("timeit lexsort_nb2(ab)")
257 |
258 | # %timeit lexsort_nb2(ab)
259 | # %timeit lexsort_nb(a, b)
260 | # %timeit np.lexsort([a, b])
261 |
262 | assert (np.lexsort([a, b]) == lexsort_nb(a, b)).all()
263 | assert (np.lexsort([a, b]) == lexsort_nb2(ab)).all()
264 |
265 |
266 |
267 | @jit(nopython=True, nogil=True)
268 | def get_boundaries(x):
269 | # Assumes that the same x are grouped consecutively (but not
270 | # necessarily sorted). Doesn't assume that y is sorted.
271 |
272 | if x.size > 0:
273 | n = 1000000
274 | x_unique = np.empty(n, x.dtype)
275 |
276 | xc = x[0] # Current x
277 |
278 | boundaries = np.empty(n+1, dtype=np.int32)
279 | boundaries[0] = 0
280 |
281 | g = 0
282 | for i in range(x.size):
283 | xx = x[i]
284 | if xx != xc:
285 | if g == x_unique.size:
286 | x_unique = extend_1d_arr(x_unique)
287 | boundaries = extend_1d_arr(boundaries)
288 | x_unique[g] = xc
289 | g += 1
290 | boundaries[g] = i
291 | xc = xx
292 | if g == x_unique.size:
293 | x_unique = extend_1d_arr(x_unique)
294 | boundaries = extend_1d_arr(boundaries)
295 |
296 | x_unique[g] = xc
297 | boundaries[g+1] = x.size
298 |
299 | x_unique = x_unique[: g+1]
300 | boundaries = boundaries[: g+2]
301 | else:
302 | boundaries = np.empty(0, dtype=np.int32)
303 | x_unique = np.empty(0, dtype=x.dtype)
304 |
305 | return x_unique, boundaries
306 |
307 | @jit(nopython=True, nogil=True)
308 | def get_boundaries2(x):
309 | """Alternative, simpler implementation of get_boundaries()"""
310 | boundaries = (x[1:] != x[:-1]).nonzero()[0] + 1
311 | boundaries = np.append(np.append(0, boundaries), x.size)
312 | #boundaries = np.append(np.append([0], boundaries), [x.size])
313 | return boundaries
314 |
315 | @jit(nopython=True, nogil=True)
316 | def get_boundaries_2d(x):
317 | """2D version.
318 |
319 | Alternative, simpler implementation of get_boundaries()"""
320 |
321 | # boundaries = np.empty(x.shape[0] + 1, np.int32)
322 | # for i in range(x.shape[0]):
323 | # boundaries[i+1]
324 |
325 | boundaries = ((x[1:,:] != x[:-1,:]).sum(1) >= 1).nonzero()[0] + 1
326 | boundaries = np.append(np.append(0, boundaries), x.shape[0])
327 | return boundaries
328 |
329 | def get_boundaries_py(x):
330 | """Alternative, simpler implementation of get_boundaries()"""
331 | is_boundary = np.empty(x.size+1, np.bool_)
332 | n = 2
333 | for i in prange(1, x.size):
334 | unequal = x[i] != x[i-1]
335 | is_boundary[i] = unequal
336 | n += unequal
337 | is_boundary[0] = True
338 | is_boundary[x.size] = True
339 |
340 | boundaries = np.empty(n, np.int64)
341 | j = 0
342 | for i in range(is_boundary.size):
343 | if is_boundary[i]:
344 | boundaries[j] = i
345 | j += 1
346 |
347 | return boundaries
348 |
349 | get_boundaries_mt = jit(get_boundaries_py, nopython=True, nogil=True, parallel=True)
350 | get_boundaries_st = jit(get_boundaries_py, nopython=True, nogil=True, parallel=False)
351 |
352 |
353 | @jit(nopython=True, nogil=True)
354 | def is_sorted(arr):
355 | if len(arr.shape)==1:
356 | return ((arr[1:] - arr[:-1])>=0).all()
357 | elif len(arr.shape)==2:
358 | for i in range(arr.shape[0]-1):
359 | if not lte(arr[i,:], arr[i+1,:]):
360 | return False
361 | return True
362 |
363 | # idx = lexsort_nb2(arr.T[::-1,:], first_mergesort=True)
364 | # return (idx == np.arange(arr.shape[0])).all()
365 |
--------------------------------------------------------------------------------
/plasx/pd_utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import operator
3 | import functools
4 | import time
5 | import numpy as np
6 | import pandas as pd
7 | import scipy
8 | from pathlib import Path
9 |
10 | from plasx import utils
11 |
12 | def catin(series, domain, keep_index=False):
13 | """Alias for categorical_isin()"""
14 |
15 | return categorical_isin(series, domain, keep_index=keep_index)
16 |
17 | def categorical_isin(series, domain, keep_index=False):
18 | """Does a faster version of pd.Series.isin() for categorical
19 | dtypes. Does this by only checking the unique categories
20 |
21 | Calculates the equivalent of `series.isin(domain)`
22 |
23 | """
24 |
25 | isin = series.cat.categories.isin(domain)[series.cat.codes.values]
26 | if keep_index:
27 | pd.Series(isin, index=series.index)
28 | else:
29 | return isin
30 |
31 | def int_loc(query, domain, check=True):
32 | """Fast querying into `domain`, a pd.Series with an integer index. Querying at locations in the numpy array `query`.
33 |
34 | The equivalent of domain.loc[query]
35 |
36 | The implementation trick is to create an array with values located at the domain's index.
37 |
38 | Disadvantage: requires creating a very big array
39 |
40 | If check=True, then do some extra processing to validate the input
41 | """
42 |
43 | if len(domain.index) > 0:
44 | min_val = domain.index.min()
45 | max_val = domain.index.max()
46 | else:
47 | min_val, max_val = 0, 0
48 |
49 | if check:
50 | assert pd.api.types.is_integer_dtype(query), f"query was dtype {type(query)}, but it needs to be an integer dtype"
51 | assert pd.api.types.is_integer_dtype(domain.index), f"domain was dtype {type(domain)}, but it needs to be an integer dtype"
52 | assert min_val >= 0, f"Minimum value of domain was {min_val}, but it needs to be >=0"
53 | assert isinstance(query, np.ndarray)
54 | assert (max_val <= 10**9), \
55 | "The max value in this domain's index is above 1 billion, which will require creating an array with memory >8gb. Make sure you are okay with this and then set check=False"
56 | assert domain.index.duplicated().sum()==0 # Check that the domain' index does not have duplicate values
57 | assert np.all(isin_int(query, domain.index, max_val=max_val)) # Check that all of query is in the domain
58 |
59 | arr = np.empty(max_val + 1, domain.dtype)
60 | arr[domain.index] = domain.values
61 | return arr[query]
62 |
63 | def isin_int(series, domain, max_val=None):
64 | """Fast np.in1d when series and domain are both integers.
65 |
66 | Equivalent to np.in1d(series, domain)
67 |
68 | The implementation trick is to create a boolean presence/absence array.
69 | """
70 |
71 | if max_val is None:
72 | if len(series) > 0:
73 | max_val = np.max(series)
74 | else:
75 | max_val = 0
76 |
77 | mask = np.zeros(max_val + 1, np.bool_)
78 | mask[domain[domain <= max_val]] = True
79 |
80 | return mask[series]
81 |
82 | def better_pd_concat(df_list, sort=True, **kwargs):
83 | """Does the same as pandas.concat(), but categorical columns will ALWAYS be preserved as categorical
84 |
85 | The (bad) behavior of pandas.concat() is to return an object dtype
86 | if the list of Series have different 'categories'.
87 |
88 | """
89 |
90 | from pandas.api.types import union_categoricals
91 |
92 | if all(isinstance(x, pd.Series) for x in df_list):
93 | # Everything is a pd.Series
94 |
95 | df_concat = pd.concat(df_list, ignore_index=True)
96 | df_concat.index = union_categoricals([x.index for x in df_list])
97 |
98 | assert len(df_concat) == sum(map(len, df_list))
99 | return df_concat
100 | else:
101 | # Check that the columns across the dataframes are all the same (and same order)
102 | try:
103 | for i in range(len(df_list) - 1):
104 | assert (df_list[i].columns == df_list[
105 | i + 1].columns).all(), 'Columns are not in the same order across dataframes. Suggest re-running with sort=True.'
106 | except AssertionError as e:
107 | if sort:
108 | df_list = [df[sorted(df.columns)] for df in df_list]
109 | else:
110 | raise e
111 |
112 | columns = df_list[0].columns
113 | dtypes = df_list[0].dtypes
114 |
115 | non_categ_columns = [c for c in columns if dtypes[c].name != 'category']
116 | categ_columns = [c for c in columns if dtypes[c].name == 'category']
117 |
118 | df_concat = pd.concat([df[non_categ_columns] for df in df_list], **kwargs)
119 |
120 | for c in categ_columns:
121 | df_concat[c] = union_categoricals([df[c] for df in df_list])
122 |
123 | # Use original ordering of columns
124 | df_concat = df_concat[columns]
125 |
126 | return df_concat
127 |
128 |
129 | def sync_categories(to_sync):
130 | """For an input set of categorical series, set their categories to be
131 | the same (the union of categories across all series).
132 |
133 | Does modifications inplace.
134 |
135 | to_sync : list-like of pandas Categorical Series
136 |
137 | """
138 |
139 | import functools
140 | union_categories = functools.reduce(lambda x, y: x.union(y),
141 | [x.cat.categories for x in to_sync])
142 |
143 | # Update 12/19/21: Need to return synced categoricals as new
144 | # objects, as inplace=True has become deprecated in newer pandas
145 | # versions
146 | return [x.cat.set_categories(union_categories) for x in to_sync]
147 |
148 | # for x in to_sync:
149 | # x.cat.set_categories(union_categories, inplace=True)
150 |
151 | # return to_sync
152 |
153 |
154 | def merge(left, right, **kwargs):
155 | """Alias for better_merge()"""
156 | return better_merge(left, right, **kwargs)
157 |
158 | def better_merge(left, right, stepwise=None, **kwargs):
159 | """Does the same as pandas.merge(), but categorical columns that are
160 | joined will be first converted into numerical codes before
161 | joining. After joining, the codes will be converted back into
162 | categoricals.
163 |
164 | In this process, the ordering of categories may be messed up.
165 |
166 | The (bad) behavior of pandas.merge() is to return an object dtype
167 | for the joined categorical columns.
168 |
169 | """
170 |
171 | if stepwise:
172 | ### If merging on multiple columns, then do a groupby on the
173 | ### first column, and then merge.
174 |
175 | on = kwargs['on']
176 | assert 'left_on' not in kwargs and 'right_on' not in kwargs
177 | key_list = np.asarray(pd.concat([left[on[0]], right[on[0]]], ignore_index=True).drop_duplicates())
178 | # left_dict = {a:b for a,b in left.groupby(on[0], observed=True)}
179 | # right_dict = {a:b for a,b in right.groupby(on[0], observed=True)}
180 | utils.tprint('Creating dictionaries')
181 | left_dict = {a:b for a,b in utils.subset(left, {on[0]:key_list}, unused=False).groupby(on[0], observed=True)}
182 | right_dict = {a:b for a,b in utils.subset(right, {on[0]:key_list}, unused=False).groupby(on[0], observed=True)}
183 |
184 | utils.tprint('Creating sub merges')
185 | to_concat = []
186 | assert 'how' in kwargs and kwargs['how']=='inner'
187 | for key in set(left_dict.keys()) & set(right_dict.keys()):
188 | to_concat.append(left_dict[key].merge(right_dict[key], on=on[1:], **kwargs))
189 |
190 | utils.tprint('Concating')
191 | ret = pd.concat(to_concat)
192 | utils.tprint('Done')
193 | return ret
194 |
195 | left_on, right_on = kwargs.get('left_on', None), kwargs.get('right_on', None)
196 | if kwargs['on']:
197 | left_on = kwargs['on']
198 | right_on = kwargs['on']
199 |
200 | if isinstance(left_on, str):
201 | left_on = [left_on]
202 | if isinstance(right_on, str):
203 | right_on = [right_on]
204 |
205 | if left_on and right_on:
206 | left = left.copy()
207 | right = right.copy()
208 |
209 | new_categories_dict = {}
210 |
211 | for left_col, right_col in zip(left_on, right_on):
212 |
213 | if str(left[left_col].dtype.name) == 'category':
214 | # print(left_col, right_col)
215 | assert right[right_col].dtype.name == 'category'
216 |
217 | categories_union = left[left_col].cat.categories.union(right[right_col].cat.categories)
218 | left[left_col] = left[left_col].cat.set_categories(categories_union)
219 | right[right_col] = right[right_col].cat.set_categories(categories_union)
220 |
221 | left[left_col] = left[left_col].cat.codes
222 | right[right_col] = right[right_col].cat.codes
223 |
224 | new_categories_dict[left_col] = categories_union
225 | new_categories_dict[right_col] = categories_union
226 |
227 | elif left_on:
228 | raise Exception()
229 | elif right_on:
230 | raise Exception()
231 |
232 | # return left, right, categories_union
233 |
234 | # Do merge
235 | start = time.time()
236 | merge_df = pd.merge(left, right, **kwargs)
237 | print('Merge_time:', time.time() - start)
238 | print('Merge shape:', merge_df.shape)
239 |
240 | # Change numerical codes back into categoricals
241 | for col, new_categories in new_categories_dict.items():
242 | # merge_df[col] = pd.Categorical.from_codes(merge_df[col], categories=new_categories)
243 | merge_df[col] = pd.Categorical.from_codes(merge_df[col].values, categories=new_categories)
244 |
245 | return merge_df
246 |
247 |
248 | def dask_merge(left, right, compute=True, left_splits=None, right_splits=None, **kwargs):
249 | """Does pandas.merge, but uses dask. Splits pandas dataframes into dataframes automatically"""
250 |
251 | # pandas.merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)[source]
252 |
253 | # TODO: make the default splits be the squareroot of the number of
254 | # CPUs (since merging is number of left splits * number of right
255 | # splits)
256 | if left_splits is None:
257 | left_splits = 4
258 | if right_splits is None:
259 | right_splits = 4
260 |
261 | # Convert into dask dataframes
262 | # print(type(left), type(right))
263 | if not isinstance(left, dd.core.DataFrame):
264 | left = dd.from_pandas(left, npartitions=left_splits)
265 | if not isinstance(right, dd.core.DataFrame):
266 | right = dd.from_pandas(right, npartitions=right_splits)
267 |
268 | merge = left.merge(right, **kwargs)
269 | if compute:
270 | merge = merge.compute()
271 | return merge
272 |
273 |
274 | def df_2_long_df(sp, dic=None, colname='i', rowname='j', dataname='data', how='outer'):
275 | """Same as spmatrix_2_long_df, but takes in dataframes as input"""
276 |
277 | """TODO : merge this formatting code (converting to dictionary) with spmatrix_2_long"""
278 | try:
279 | # Test if `sp` is a dictionary, by seeing if it has .keys() attribute
280 | sp.keys()
281 | sp_dict = sp
282 | except:
283 | if isinstance(sp, (list, tuple)):
284 | # 'data_1', 'data_2', etc.
285 | sp_dict = {'%s_%s' % (dataname, i): x for i, x in enumerate(sp)}
286 | else:
287 | # 'data' --> sp
288 | sp_dict = {dataname: sp}
289 |
290 | if dic is None: dic = {}
291 | dic['name'] = list(sp_dict.values())[0].index.values
292 |
293 | # Convert dataframes to COO matrices
294 | sp_dict = {k: dense_to_sparse_df(v).sparse.to_coo() for k, v in sp_dict.items()}
295 |
296 | return wide_2_long_df(sp_dict,
297 | dic=dic,
298 | colname=colname,
299 | rowname=rowname,
300 | dataname=dataname,
301 | how=how)
302 |
303 |
304 | def dense_to_sparse_df(df, fill_value=None):
305 | """Cast columns in a pd.DataFrame to Sparse dtypes.
306 |
307 | If `fill_value` is not specified, then assume default fill_values
308 | for each numerical dtype (e.g. nan for np.float)
309 |
310 | """
311 |
312 | def to_sparse_dtype(s, fill_value=None):
313 | """Changes a pandas dtype into its sparse version. If the dtype is
314 | already sparse, then don't do anything
315 |
316 | """
317 |
318 | if 'Sparse' in s.name:
319 | return s
320 | else:
321 | if fill_value is not None:
322 | # Convert the fill_value into the specific numpy
323 | # dtype. E.g. if fill_value==0 (a Python integer) and
324 | # dtype is np.float64, then the fill_value gets
325 | # converted to np.float64(0)
326 | fill_value = s.type(fill_value)
327 | return pd.SparseDtype(s, fill_value=fill_value)
328 |
329 | # return df.astype({k : pd.SparseDtype(v, fill_value=fill_value) for k, v in df.dtypes.items()})
330 | return df.astype({k: to_sparse_dtype(v, fill_value=fill_value) for k, v in df.dtypes.items()})
331 |
332 |
333 | def wide_2_long_df(sp, dic=None, rowname='i', colname='j', dataname='data', how='outer'):
334 | """Return a long-format dataframe that shows only the non-zero values
335 | of a scipy sparse matrix. If multiple matrices are given, then the
336 | intersection or union of non-zero values are given. """
337 |
338 | try:
339 | # Test if `sp` is a dictionary, by seeing if it has .keys() attribute
340 | sp.keys()
341 | sp_dict = sp
342 | except:
343 | if isinstance(sp, (list, tuple)):
344 | # 'data_1', 'data_2', etc.
345 | sp_dict = {'%s_%s' % (dataname, i): x for i, x in enumerate(sp)}
346 | else:
347 | # 'data' --> sp
348 | sp_dict = {dataname: sp}
349 |
350 | # Convert numpy arrays and dataframes into COO matrices
351 | for k, v in list(sp_dict.items()):
352 | if isinstance(v, np.ndarray):
353 | sp_dict[k] = scipy.sparse.coo_matrix(v)
354 | elif isinstance(v, pd.DataFrame):
355 | if dic is None: dic = {}
356 | if 'name' not in dic:
357 | dic['name'] = k.index.values
358 |
359 | sp_dict[k] = dense_to_sparse_df(v).sparse.to_coo()
360 |
361 | if how == 'outer':
362 | i, j = sum([sp > 0 for sp in sp_dict.values()]).nonzero()
363 | if how == 'inner':
364 | from functools import reduce
365 | tmp = reduce(lambda a, b: a.multiply(b), (x > 0 for x in sp in sp.values()))
366 | tmp.eliminate_zeros()
367 | i, j = tmp.nonzero()
368 |
369 | df = pd.DataFrame({sp_name: utils.as_flat(utils.sp_as_indexable(sp)[i, j]) \
370 | for sp_name, sp in sp_dict.items()})
371 |
372 | if dic is None:
373 | df[rowname] = i
374 | df[colname] = j
375 | else:
376 | for k, v in dic.items():
377 | # categorical_from_nonunique is needed, because the same
378 | # description can be shared by multiple COG accesions,
379 | # e.g. the description "uncharacterized protein"
380 | df[rowname + '_' + k] = categorical_from_nonunique(i, v)
381 | df[colname + '_' + k] = categorical_from_nonunique(j, v)
382 |
383 | return df
384 |
385 |
386 | def categorical_from_nonunique(codes, categories):
387 | """If `categories` is an array of non-unique values, then
388 | pd.Categorical.from_codes() won't work out of the box.
389 |
390 | This function will create a pd.Categorical by collapsing redundant
391 | categories and represent them with a single code.
392 |
393 | This involves changing the codes to new codes.
394 |
395 | """
396 |
397 | # if categories.dtype == np.dtype('O'):
398 | # # If `categories` is an array mix of dtypes, e.g. ints, nans,
399 | # # and strings, then its dtype is np.dtype('O'). In this case,
400 | # # running np.unique will throw an error because it can't compare strings vs integers for example.
401 | # unique_categories = np.array(list(set(categories)))
402 | # else:
403 | # #unique_categories = np.unique(categories)
404 | # unique_categories = pd.Series(categories).drop_duplicates().values
405 |
406 | unique_categories = pd.Series(categories).drop_duplicates().values
407 |
408 | # Maps unique categories to consecutive integers: 1,2,3,...
409 | unique_categories_index = pd.Series(np.arange(unique_categories.size), index=unique_categories)
410 |
411 | # reindex[i] = new code for code `i`
412 | reindex = unique_categories_index[categories].values
413 | new_codes = reindex[codes]
414 |
415 | return pd.Categorical.from_codes(new_codes, categories=unique_categories)
416 |
417 |
418 | def sparse_melt(sp, rownames=None, colnames=None, index_name=None, var_name=None, value_name=None, square=None):
419 | if index_name is None:
420 | index_name = 'index'
421 | if var_name is None:
422 | var_name = 'column'
423 | if value_name is None:
424 | value_name = 'value'
425 | if square is None:
426 | square = False
427 |
428 | if square:
429 | assert colnames is None, "You should only specify `rownames`, if square=True"
430 | colnames = rownames
431 |
432 | edges = sp.nonzero()
433 | edges_i, edges_j = edges
434 | df = pd.DataFrame({index_name : edges_i if (rownames is None) else pd.Categorical.from_codes(edges_i, rownames),
435 | var_name : edges_j if (colnames is None) else pd.Categorical.from_codes(edges_j, colnames),
436 | value_name : utils.as_flat(sp[edges_i, edges_j])})
437 | return df
438 |
439 | def sparse_pivot(df,
440 | index=None,
441 | columns=None,
442 | values=None,
443 | index_use_index=False,
444 | columns_use_index=False,
445 | fill_value=0.0,
446 | offset_hack=None,
447 | square=False,
448 | remove_unused_categories=False,
449 | directed=None,
450 | binary=None,
451 | verbose=False,
452 | method=None,
453 | default_value=None,
454 | aggfunc=None,
455 | rettype='sparse'):
456 | """Turns a long-format DataFrame into a wide-format sparse
457 | DataFrame. Does same functionality as pd.pivot, but returns a
458 | sparse (rather than normal) DataFrame
459 |
460 | df :
461 |
462 | dataframe
463 |
464 | index, columns, values:
465 |
466 | Columns in `df` to be pivoted. Same as the parameters for pd.DataFrame.pivot(). Cannot be `None`.
467 |
468 | `index` and `columns` should be categorical Series. `values` should be numerical Series.
469 |
470 | rettype:
471 |
472 | 'sparse' : pd.DataFrame with Sparse series
473 |
474 | 'spmatrix' : scipy sparse COO matrix
475 |
476 | square :
477 |
478 | If True, then reorder the category code values of `index` and `columns` to be the same
479 |
480 | """
481 |
482 | assert (index_use_index + columns_use_index) != 2, 'Cannot use index twice'
483 |
484 |
485 | if method=='pd':
486 | # Use pandas.pivot_table, but do some preformatting to make things faster
487 |
488 | assert rettype=='dense_df'
489 |
490 | df = df.copy()
491 |
492 | # Change `index` and `columns` into a list
493 | if isinstance(index, str) or (not hasattr(index, '__iter__') and index in df.columns):
494 | index = [ index ]
495 | if isinstance(columns, str) or (not hasattr(index, '__iter__') and columns in df.columns):
496 | columns = [ columns ]
497 |
498 | # Convert categories into codes (This is the biggest help in making the code run fast)
499 | def convert_cat_to_codes(columns):
500 | categories = []
501 | for c in columns:
502 | if df[c].dtype.name=='category':
503 | if remove_unused_categories:
504 | df[c] = df[c].cat.remove_unused_categories()
505 | categories.append(df[c].cat.categories)
506 | df[c] = df[c].cat.codes
507 | else:
508 | categories.append(None)
509 | return categories
510 | index_categories = convert_cat_to_codes(index)
511 | column_categories = convert_cat_to_codes(columns)
512 |
513 | if default_value is None:
514 | assert values is not None, "Specify the `values` variables"
515 | else:
516 | # Set a default value if the column `values` is not specified
517 | assert values is None
518 | assert 'value1234' not in df.columns
519 | df['value1234'] = default_value
520 | values = 'value1234'
521 |
522 | if aggfunc is None:
523 | # Default is to sum up values
524 | # - NOTE**** THIS IS DIFFERENT FROM THE DEFAULT AGGFUNC 'mean' in pd.pivot_table()
525 | aggfunc = 'sum'
526 |
527 | return pd.pivot_table(df, index=index, columns=columns, values=values,
528 | fill_value=fill_value, aggfunc=aggfunc)
529 |
530 | if index_use_index:
531 | index = pd.Series(df.index)
532 | else:
533 | index = df[index]
534 |
535 | if columns_use_index:
536 | columns = pd.Series(df.index)
537 | else:
538 | columns = df[columns]
539 |
540 | # Convert to categories
541 | try:
542 | index.cat
543 | except:
544 | index = index.astype('category')
545 |
546 | try:
547 | columns.cat
548 | except:
549 | columns = columns.astype('category')
550 |
551 |
552 | if remove_unused_categories:
553 | index = index.cat.remove_unused_categories()
554 | columns = columns.cat.remove_unused_categories()
555 |
556 | if square:
557 | if verbose: utils.tprint('Syncing index and column categorical coding')
558 | index = index.copy()
559 | columns = columns.copy()
560 | index, columns = sync_categories([index, columns])
561 | assert np.all(index.cat.categories == columns.cat.categories)
562 | if verbose: utils.tprint('Done syncing')
563 |
564 | if values is None:
565 | # Default value of 1
566 | values = np.ones(index.size, np.int64)
567 | else:
568 | values = df[values].values
569 |
570 |
571 | # if len(index.shape)==1:
572 | # # A single variable index
573 | # pass
574 | # else:
575 | # # A MultiIndex
576 | # index.
577 |
578 | shape = (index.cat.categories.size, columns.cat.categories.size)
579 |
580 | if fill_value != 0:
581 | # If you set fill_value to not 0, then maybe it's because your
582 | # dataframe contains 0's that are significant and should be
583 | # preserved in the output. In scipy.sparse, those 0's will be
584 | # removed. To counter this, a hack is to add an offset to all
585 | # values. For example, if all values are non-negative, then
586 | # simply adding an offset of 1 will do the trick. However, an
587 | # appropriate an offset can be tricky to set, e.g. values
588 | # could be -1 or 0 such that an offset of 1 would be
589 | # confusing. Thus, to avoid data-specific trickiness, here you
590 | # must manually specify the offset in the variable
591 | # `offset_hack`.
592 |
593 | assert rettype != 'spmatrix', 'Only a fill-value of 0 is supported if returning a scipy sparse matrix'
594 |
595 | assert offset_hack is not None
596 | sp = scipy.sparse.coo_matrix((values + offset_hack, (index.cat.codes, columns.cat.codes)), shape=shape)
597 | else:
598 | sp = scipy.sparse.coo_matrix((values, (index.cat.codes, columns.cat.codes)), shape=shape)
599 |
600 | # Need to eliminate zeros, as their presence will lead to a bug
601 | # when calling pandas' from_spmatrix() function
602 | # https://github.com/pandas-dev/pandas/issues/29814
603 | sp.eliminate_zeros()
604 |
605 | if binary:
606 | assert fill_value==0.
607 |
608 | # Threshold matrix if values are >0
609 | sp = (sp > 0).astype(int)
610 |
611 | if rettype in ['sparse', 'dense_df', 'spmatrix', 'ig']:
612 | # rownames = index.cat.categories[: index.cat.codes.max() + 1]
613 | # colnames = columns.cat.categories[: columns.cat.codes.max() + 1]
614 |
615 | rownames = index.cat.categories
616 | colnames = columns.cat.categories
617 |
618 | if rettype == 'sparse':
619 | df_sp = pd.DataFrame.sparse.from_spmatrix(sp, index=rownames, columns=colnames)
620 |
621 | # Change fill value
622 | dtype = sp.dtype.type
623 | fill_value_cast = dtype(fill_value)
624 | assert fill_value_cast == fill_value, \
625 | "Need to check that the fill value was preserved. E.g. This may have" \
626 | "happened if the underlying data was np.int64, and the" \
627 | "fill_value was 0.5"
628 | df_sp = df_sp.astype(pd.SparseDtype(dtype, fill_value_cast))
629 |
630 | if fill_value != 0:
631 | df_sp = df_sp - offset_hack
632 |
633 | return df_sp
634 | elif rettype == 'dense_df':
635 | return pd.DataFrame(sp.toarray(), index=rownames, columns=colnames)
636 | elif rettype == 'spmatrix':
637 | return sp, rownames, colnames
638 | elif rettype == 'ig':
639 | return utils.create_ig(sp, weighted=True, directed=directed,
640 | rownames=rownames, colnames=None if square else colnames, square=square)
641 | else:
642 | raise Exception('Unsupported return type')
643 |
644 |
645 | def df_str_split(df, pat, column):
646 | """
647 | Splits up a string in a dataframe row into substrings across multiple rows.
648 |
649 | df : dataframe
650 |
651 | pat : pattern to split. Same as in pd.Series.str.split
652 |
653 | column: column to split on
654 | """
655 |
656 | if df.shape[0] > 0:
657 | orig_columns = df.columns
658 | other_cols = [x for x in df.columns if x != column]
659 |
660 | df = df.set_index(other_cols)[column].str.split(pat, expand=True)
661 | df = df.stack().reset_index(other_cols)
662 | df.reset_index(drop=True, inplace=True)
663 | df.rename(columns={0: column}, inplace=True)
664 |
665 | # Necessary because reset_index() may not preserve original order of columns
666 | df = df[orig_columns]
667 | return df
668 |
669 |
670 | def fast_concat(df_list, fill_value=np.nan):
671 | """
672 | Faster pandas concatenation? (TODO: document when is it faster?)
673 | """
674 |
675 | all_columns = pd.Series(np.concatenate([df.columns.values for df in df_list])).unique()
676 | all_columns.sort()
677 | all_columns_series = pd.Series({b: a for a, b in enumerate(all_columns)})
678 | all_indices = np.concatenate([df.index.values for df in df_list])
679 |
680 | nrows = sum([df.shape[0] for df in df_list])
681 |
682 | # # Test if there are more than one data type in the dataframes
683 | # if (df_list[0].dtypes.unique().size > 1) or np.unique([y for x in df_list for y in x.dtypes]).size > 1:
684 | # concat_arr = np.full((nrows, all_columns.size), fill_value, dtype=np.dtype('O'), order='C')
685 |
686 | # # Else, assume it's all float data types in the dataframe
687 | # else:
688 | # concat_arr = np.full((nrows, all_columns.size), fill_value, dtype=np.float64, order='C')
689 |
690 | concat_arr = np.full((nrows, all_columns.size), fill_value, dtype=np.float64, order='C')
691 |
692 | curr_row = 0
693 | for df in df_list:
694 | concat_arr[curr_row: curr_row + df.shape[0], all_columns_series[df.columns].values] = df.values
695 | curr_row += df.shape[0]
696 | concat_df = pd.DataFrame(concat_arr, columns=all_columns, index=all_indices)
697 |
698 | return concat_df
699 |
700 |
701 | def expand_df(df, newcols, fill_value=0, dtype=None, sparse=None, copy=False, sort=False):
702 | """Add new columns to a dataframe. Handles sparse dataframes.
703 |
704 | sort :
705 |
706 | If True, then rearrange order of all columns lexicographically. Default: False
707 |
708 | copy :
709 |
710 | Copies the dataframe before modifying it. Only applies when
711 | `sparse` is set to False or inferred to be False. If `sparse`
712 | is True, then the dataframe is always copied regardless of
713 | this parameter.
714 |
715 | """
716 |
717 | if sparse is None:
718 | try:
719 | # A column is sparse if and only if the column has a '.sparse' attribute
720 | df.iloc[:, 0].sparse
721 | sparse = True
722 | except:
723 | sparse = False
724 |
725 | if len(newcols) > 0:
726 | if sparse:
727 | if dtype is None:
728 | # Set the dtype to be the first column's dtype
729 | # (Assumes all columns have the same type)
730 | dtype = df.dtypes[0].type
731 | sp_dtype = pd.SparseDtype(dtype, fill_value=dtype(fill_value))
732 |
733 | sp = scipy.sparse.coo_matrix(([], ([], [])), dtype=dtype, shape=(df.shape[0], len(newcols)))
734 | df_sp = pd.DataFrame.sparse.from_spmatrix(
735 | sp,
736 | index=df.index,
737 | columns=newcols)
738 | df_sp = df_sp.astype(sp_dtype)
739 | df = pd.concat([df, df_sp], axis=1)
740 | else:
741 | if copy:
742 | df = df.copy()
743 |
744 | # Cast the fill value to the data type of the existing columns
745 | if dtype is None:
746 | dtype = df.dtypes[0].type
747 | fill_value = dtype(fill_value)
748 |
749 | for c in newcols:
750 | df[c] = fill_value
751 |
752 | return df
753 |
754 | def unused_cat(df, inplace=False, columns=None):
755 | """Alias for remove_unused_categories()"""
756 | return remove_unused_categories(df, inplace=inplace, columns=columns)
757 |
758 | def remove_unused_categories(df, inplace=False, columns=None):
759 | """Like pd.Series.cat.remove_unused_categories(), but does this for every categorical column in a DataFrame.
760 |
761 | From: https://stackoverflow.com/a/57827201/13485976
762 | """
763 |
764 | if not inplace:
765 | df = df.copy()
766 |
767 | if isinstance(df, pd.Series):
768 | if pd.api.types.is_categorical_dtype(df):
769 | df = df.cat.remove_unused_categories()
770 |
771 | else:
772 | if columns is None:
773 | columns = df.columns
774 |
775 | for c in columns:
776 | if pd.api.types.is_categorical_dtype(df[c]):
777 | df[c] = df[c].cat.remove_unused_categories()
778 |
779 | return df
780 |
781 | def drop_dup(df, subset=None):
782 | """Alias for fast_drop_duplicates()"""
783 | return fast_drop_duplicates(df, subset=subset)
784 |
785 | def fast_drop_duplicates(df, subset=None):
786 | is_duplicated = fast_duplicated(df, subset=subset)
787 | df = df[~ is_duplicated]
788 | return df
789 |
790 | def fast_duplicated(df, subset=None):
791 | """Quickly computes which indices to keep in a dataframe.
792 |
793 | Much faster than DataFrame.drop_duplicates() when columns are categorical. The trick is to convert to numerical codes
794 | """
795 |
796 | if subset is None:
797 | subset = df.columns
798 | # df_codes = pd.DataFrame({c : df[c] if df[c].dtype.name!='category' else df[c].cat.codes for c in subset})
799 | df_codes = pd.DataFrame({c : df[c].cat.codes if pd.api.types.is_categorical_dtype(df[c]) else df[c].values for c in subset})
800 |
801 | is_duplicated = df_codes.duplicated().values
802 | return is_duplicated
803 |
804 |
805 | def fast_loc(series, query_index, rettype=None, unused=None):
806 | """
807 | Fast version of series.loc[query_index] where series is a pd.Series.
808 |
809 | If query_index has a lot of redundant values, then it's faster to just call series.loc[] on the unique values and then repeat those results
810 | """
811 |
812 | if isinstance(query_index, pd.Series):
813 | query_index = query_index.values
814 | if not isinstance(query_index, pd.Categorical):
815 | query_index = pd.Categorical(query_index)
816 |
817 | if (unused is None) or unused:
818 | # Remove unused categories, so you don't waste time accessing their values
819 | # -- This might be extra overhead to identify unused categories if there aren't many of them
820 | query_index = query_index.remove_unused_categories()
821 |
822 | loc_results = series.loc[np.array(query_index.categories)].values[query_index.codes] #query_index.rename_categories(np.array())
823 |
824 | if rettype=='series':
825 | loc_results = pd.Series(loc_results, index=query_index)
826 |
827 | return loc_results
828 |
829 |
830 | def update_series(series_A, series_B):
831 | """
832 | series_A.update(series_B) will only update keys that are already in series_A.
833 |
834 | This function will also update keys that are NOT in series_A but are in series_B.
835 |
836 | Returns
837 | -------
838 |
839 | An updated copy of series_A (NOT INPLACE)
840 | """
841 |
842 | series_A = series_A.copy()
843 |
844 | series_A.update(series_B)
845 |
846 | return pd.concat([series_A, series_B.loc[series_B.index.difference(series_A.index)]])
847 |
848 | def subset(df, keys=None, agg='and', unused=True, copy=True, invert=False, columns=None, verbose=False, return_mask=None, **kwargs):
849 | """
850 | Convenience function for doing subsetting of dataframes, e.g.
851 |
852 | df[(df[c1]==v1) & utils.catin(df[c2], v2)]
853 |
854 | Any extra keyword arguments `kwargs` are assumed to be keys.
855 | """
856 |
857 | if len(df)==0:
858 | # If the input dataframe is empty, then the mask will be empty obviously. However, the returned dataframe will lose all columns, so shape is (0,0).
859 | # - To prevent this, just return the dataframe
860 | return df
861 |
862 | if keys is None:
863 | keys = {}
864 | keys = {**keys, **kwargs}
865 |
866 | mask = []
867 | for k, v in keys.items():
868 | if verbose:
869 | utils.tprint('Calculating mask from column %s' % k)
870 | # print( isinstance(df, pd.Series) )
871 |
872 | # if isinstance(k, str) and any(k.startswith(s) for s in ['<', '>', '!']):
873 | # if k.startswith('>='):
874 | # k = k[2:]
875 | # op = operator.ge
876 | # elif k.startswith('<='):
877 | # k = k[2:]
878 | # op = operator.le
879 | # elif k.startswith('>'):
880 | # k = k[1:]
881 | # op = operator.gt
882 | # elif k.startswith('<'):
883 | # k = k[1:]
884 | # op = operator.lt
885 | # elif k.startswith('!'):
886 | # k = k[1:]
887 | # op = operator.ne
888 | # series = df if isinstance(df, pd.Series) else df[k]
889 | # mask.append(op(series,v))
890 |
891 | if isinstance(k, str) and any(k.startswith(s) for s in ['<', '>', '!']):
892 | if k.startswith('>='):
893 | k = k[2:]
894 | op = operator.ge
895 | elif k.startswith('<='):
896 | k = k[2:]
897 | op = operator.le
898 | elif k.startswith('>'):
899 | k = k[1:]
900 | op = operator.gt
901 | elif k.startswith('<'):
902 | k = k[1:]
903 | op = operator.lt
904 | elif k.startswith('!'):
905 | k = k[1:]
906 | op = 'invert' # Indicates a logical not of the mask
907 | # op = operator.ne
908 | else:
909 | op = None
910 |
911 | series = df if isinstance(df, pd.Series) else df[k]
912 | if callable(v):
913 | m = series.apply(v)
914 | elif hasattr(v, '__iter__') and not isinstance(v, str):
915 | if series.dtype.name=='category':
916 | m = catin(series, v)
917 | else:
918 | m = series.isin(v)
919 | elif (op is not None) and (op != 'invert'):
920 | m = op(series, v)
921 | else:
922 | m = series==v
923 |
924 | if op=='invert':
925 | m = ~m
926 |
927 | mask.append(m)
928 |
929 | # if callable(v):
930 | # mask.append(series.apply(v))
931 | # elif hasattr(v, '__iter__') and not isinstance(v, str):
932 | # if series.dtype.name=='category':
933 | # mask.append(catin(series, v))
934 | # else:
935 | # mask.append(series.isin(v))
936 | # else:
937 | # mask.append(series==v)
938 |
939 | if verbose:
940 | utils.tprint('Aggregating masks')
941 | if agg=='and':
942 | mask = functools.reduce(lambda x,y: x & y, mask)
943 | elif agg=='or':
944 | mask = functools.reduce(lambda x,y: x | y, mask)
945 | else:
946 | raise Exception('Invalid agg: %s' % agg)
947 |
948 | if invert:
949 | mask = ~ mask
950 |
951 | if return_mask:
952 | return mask
953 |
954 | if verbose:
955 | utils.tprint('Applying mask')
956 | if columns is None:
957 | df = df[mask]
958 | else:
959 | df = df.loc[mask, columns]
960 |
961 | if unused:
962 | if verbose:
963 | utils.tprint('Removing unused categories')
964 |
965 | if unused is True:
966 | df = unused_cat(df)
967 | else:
968 | assert hasattr(unused, '__iter__')
969 | df = unused_cat(df, columns=unused)
970 | else:
971 | if copy:
972 | if verbose:
973 | utils.tprint('Copying dataframe')
974 |
975 | df = df.copy()
976 |
977 | if verbose:
978 | utils.tprint('Done')
979 | return df
980 |
981 | def sp_to_df(sp,
982 | rownames=None,
983 | colnames=None,
984 | row_header=None,
985 | col_header=None,
986 | value_header=None):
987 | """Convert a scipy sparse matrix into a long-format DataFrame
988 | """
989 |
990 | sp = sp.tocoo()
991 |
992 | df = pd.DataFrame()
993 |
994 | if row_header is None:
995 | row_header = 'row'
996 | if rownames is None:
997 | rows = sp.row
998 | else:
999 | rows = pd.Categorical.from_codes(sp.row, rownames)
1000 | df[row_header] = rows
1001 |
1002 | if col_header is None:
1003 | col_header = 'col'
1004 | if colnames is None:
1005 | cols = sp.col
1006 | else:
1007 | cols = pd.Categorical.from_codes(sp.col, colnames)
1008 | df[col_header] = cols
1009 |
1010 | if value_header is None:
1011 | value_header = 'value'
1012 | df[value_header] = sp.data
1013 |
1014 | return df
1015 |
1016 | def read_table(A, read_table_kws=None, cols=None, verbose=None, post_apply=None, post_apply_kws=None):
1017 | """Reads a table, by auto-inferring data type.
1018 |
1019 | Possible inputs are:
1020 |
1021 | (1) a Dataframe (which is just returned)
1022 | (2) a pickled file containing a Dataframe
1023 | (3) a text table
1024 | (4) a list or tuple of any of the three above"""
1025 |
1026 | if isinstance(A, (list, tuple)):
1027 | C = pd.concat([read_table(aa, read_table_kws=read_table_kws, cols=cols, post_apply=post_apply, post_apply_kws=post_apply_kws) for aa in A])
1028 |
1029 | elif isinstance(A, pd.DataFrame):
1030 | C = A
1031 |
1032 | elif os.path.exists(A):
1033 | if verbose:
1034 | utils.tprint('Reading table from {}'.format(A))
1035 | try:
1036 | C = utils.unpickle(A)
1037 | except:
1038 | if read_table_kws is None:
1039 | read_table_kws = {}
1040 | if 'header' not in read_table_kws:
1041 | read_table_kws['header'] = 0
1042 | C = pd.read_table(A, **read_table_kws)
1043 | elif isinstance(A, (str, Path)):
1044 | raise Exception('File {} does not exist'.format(A))
1045 | else:
1046 | raise Exception('Unsupported file type')
1047 |
1048 | # print('Before apply:')
1049 | # from IPython.display import display
1050 | # display(C)
1051 |
1052 | if post_apply is not None:
1053 | # Apply a function to the table
1054 | if post_apply_kws is None:
1055 | post_apply_kws = {}
1056 | C = post_apply(C, **post_apply_kws)
1057 |
1058 | # print('After apply:')
1059 | # display(C)
1060 |
1061 | if cols is not None:
1062 | C = C[cols]
1063 |
1064 | return C
1065 |
1066 | def write_table(A, path, pkl=None, txt=None, txt_kws=None, overwrite=None, overwrite_err_msg=None):
1067 | """Writes a pandas dataframe, either by pickling+compressing or to text file.
1068 |
1069 | Auto-ignores if `path` is None
1070 |
1071 | overwrite : If False, then check if file already exists, and raise Exception if so. Default: True.
1072 | """
1073 |
1074 | if path is None:
1075 | # If path is None, then assume that we didn't want to write anything
1076 | return
1077 |
1078 | if pkl is None and txt is None:
1079 | pkl = True
1080 | assert bool(pkl) != bool(txt)
1081 |
1082 | utils.check_overwrite(path, overwrite, overwrite_err_msg)
1083 |
1084 | if pkl:
1085 | utils.pickle(A, path)
1086 | else:
1087 | if txt_kws is None:
1088 | txt_kws = {}
1089 | if 'header' not in txt_kws:
1090 | txt_kws['header'] = True
1091 | if 'index' not in txt_kws:
1092 | txt_kws['index'] = False
1093 | if 'sep' not in txt_kws:
1094 | txt_kws['sep'] = '\t'
1095 |
1096 | A.to_csv(path, **txt_kws)
1097 |
--------------------------------------------------------------------------------
/plasx/plasx_script.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import textwrap
3 |
4 | from plasx import constants, compress_utils
5 |
6 | def setup(args):
7 | from plasx.mmseqs import download_pretrained_plasx_model
8 | download_pretrained_plasx_model(data_dir=args.data_dir,
9 | mmseqs_profiles_url=args.mmseqs_profiles_url,
10 | coefficients_url=args.coefficients_url)
11 |
12 | def predict(args):
13 | from plasx import utils
14 | from plasx.model import PlasX_model
15 |
16 | if args.model is None:
17 | args.model = constants.data_dir / 'PlasX_coefficients_and_gene_enrichments.txt'
18 |
19 | utils.tprint('Loading model from {}'.format(args.model))
20 | try:
21 | model = PlasX_model.from_table(args.model)
22 | except FileNotFoundError:
23 | raise FileNotFoundError("No PlasX model found. Need to specify a table with PlasX coefficients, or download this table via `plasx setup` to the PlasX install directory.")
24 | # model = PlasX_model.load(args.model)
25 |
26 | utils.tprint('Running model')
27 | scores = model.predict(args.annotations,
28 | verbose=True,
29 | gene_calls=args.gene_calls,
30 | output=args.output,
31 | output_kws=dict(overwrite= 2 if args.overwrite else 1))
32 |
33 | def search(args):
34 | from plasx.mmseqs import annotate_de_novo_families
35 |
36 | compress_utils.set_threads(args.threads)
37 |
38 | annotate_de_novo_families(args.gene_calls,
39 | output=args.output,
40 | output_dir=args.tmp,
41 | target_db=args.target_db,
42 | overwrite= 2 if args.overwrite else 1,
43 | output_kws=dict(txt=True),
44 | threads=args.threads,
45 | splits=args.splits,
46 | clean_tmp=not args.save_tmp)
47 |
48 | def fit(args):
49 | raise Exception("Not Implemented")
50 | print(args)
51 |
52 | def get_parser():
53 | description = textwrap.dedent(\
54 | """Runs a PlasX model on a set of sequences. A score is returned for
55 | each contig. Plasmids have scores closer to 1, whereas chromosomes
56 | have scores closer to 0.""")
57 |
58 | parser = argparse.ArgumentParser(
59 | description=description)
60 | parser.set_defaults(func=lambda args: parser.print_help())
61 |
62 | # Add subparsers
63 | subparsers = parser.add_subparsers()
64 |
65 | setup_parser = subparsers.add_parser('setup', help='Downloads a pretrained PlasX model')
66 | setup_parser.set_defaults(func=setup)
67 | required = setup_parser.add_argument_group('required arguments')
68 | optional = setup_parser.add_argument_group('optional arguments')
69 | optional.add_argument(
70 | '--de-novo-families', dest='mmseqs_profiles_url', default=None,
71 | help="""URL of precomputed mmseqs profiles""")
72 | optional.add_argument(
73 | '--coefficients', dest='coefficients_url', default=None,
74 | help="""URL of precomputed coefficients and intercept of logistic regression""")
75 | optional.add_argument(
76 | '-o', dest='data_dir', default=None,
77 | help="""Directory to save model. Default: in the install location of PlasX.""")
78 |
79 | fit_parser = subparsers.add_parser('fit', help='(Not implemented yet) Trains a new PlasX model')
80 | fit_parser.set_defaults(func=fit)
81 |
82 | ## Search parser
83 | search_parser = subparsers.add_parser('search_de_novo_families', help='Annotates genes to de novo families. Uses MMseqs2 for fast sequence alignment.')
84 | search_parser.set_defaults(func=search)
85 | required = search_parser.add_argument_group('required arguments')
86 | optional = search_parser.add_argument_group('optional arguments')
87 | required.add_argument(
88 | '-g', '--gene-calls', dest='gene_calls', required=True,
89 | help='Table of gene calls, with amino acid sequences')
90 | required.add_argument(
91 | '-o', '--output', dest='output', required=True,
92 | help="""File to save predictions""")
93 | optional.add_argument(
94 | '-db', dest='target_db', default=None,
95 | help="""Location of precomputed MMseqs2 profiles. You only need to specify this if you downloaded the PlasX model to a custom location using the '-o' flag in `plasx setup`. Default: PlasX will search the default download location in its installation diretory.""")
96 | optional.add_argument(
97 | '-T', '--threads', dest='threads', type=int, default=None,
98 | help="""Number of threads to run MMseqs2 with. Default: The number of CPUs available on this machine.""")
99 | optional.add_argument(
100 | '-S', '--splits', dest='splits', type=int, default=1,
101 | help="""This will split PlasX's set of de novo families into an equal number of chunks for searching, reducing the maximum RAM usage. Searching will fail if your machine has insufficient RAM, so you should consider increasing the number of splits. If you have only ~8Gb of RAM, then we recommend settings -S to 32. Setting -S to 0 will let MMseqs2 decide the number of splits automatically. Default: 1 split.""")
102 | optional.add_argument(
103 | '--tmp', dest='tmp', default=None,
104 | help="""Directory to save temporary intermediate files, including ones created by MMseqs2. This directory is deleted upon termination, unless '--save-tmp' is specified. Default: a directory with a random name is created (e.g. inside /tmp)""")
105 | optional.add_argument(
106 | '--save-tmp', dest='save_tmp', action='store_true',
107 | help="""Do NOT delete the directory of intermediate files upon termination. Note: these files use a lot of disk storage, so only keep them if needed for debugging.""")
108 | optional.add_argument(
109 | '--overwrite', dest='overwrite', action='store_true', default=False,
110 | help="""Overwrite files""")
111 |
112 |
113 | ## Predict parser
114 | predict_parser = subparsers.add_parser('predict', help='Runs trained PlasX model on annotated sequences')
115 | predict_parser.set_defaults(func=predict)
116 | required = predict_parser.add_argument_group('required arguments')
117 | optional = predict_parser.add_argument_group('optional arguments')
118 | required.add_argument(
119 | '-a', '--annotations', dest='annotations', nargs='+', required=True,
120 | help='Table of gene annotations to COGs, Pfams, and de novo families')
121 | required.add_argument(
122 | '-o', '--output', dest='output', required=True,
123 | help="""File to save predictions. If not set, then predictions are printed to stdout.""")
124 | optional.add_argument(
125 | '-m', '--model', dest='model',
126 | help='Pretrained PlasX model')
127 | optional.add_argument(
128 | '-g', '--gene-calls', dest='gene_calls', default=None,
129 | help='Table of gene calls, mapping gene_callers_id to contig')
130 | optional.add_argument(
131 | '--overwrite', dest='overwrite', action='store_true', default=False,
132 | help="""Overwrite files""")
133 |
134 | return parser
135 |
136 | def run(args=None):
137 | parser = get_parser()
138 |
139 | args = parser.parse_args(args=args)
140 | args.func(args)
141 |
142 | if __name__=='__main__':
143 | run()
144 |
--------------------------------------------------------------------------------
/plasx/utils.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import subprocess
3 | import os
4 | import time
5 | import tempfile
6 | import shutil
7 | import shlex
8 | import multiprocessing
9 | from datetime import datetime
10 | from contextlib import contextmanager
11 | from pathlib import Path
12 |
13 | import pandas as pd
14 | import numpy as np
15 | import scipy.sparse
16 |
17 | from plasx import nb_utils
18 | from plasx.fasta_utils import *
19 | from plasx.pd_utils import *
20 | from plasx.compress_utils import *
21 |
22 |
23 | def get_max_threads():
24 | return multiprocessing.cpu_count()
25 |
26 | def multiline(df, sep='|', newsep='\n', inplace=False):
27 | """Attempts to replace a separator string (default: '|') with
28 | whitespace (default: '\n') in every column of a dataframe"""
29 |
30 | if not inplace:
31 | df = df.copy()
32 |
33 | for c in df.columns:
34 | try:
35 | df[c] = df[c].str.replace(sep, newsep)
36 | except:
37 | pass
38 |
39 | return df
40 |
41 | def display(df):
42 | """Attempt to print the contents of a pandas DataFrame using
43 | IPython's display() function, if installed. Otherwise, use the
44 | standard print() function.
45 |
46 | """
47 |
48 | try:
49 | from IPython.display import display
50 | display(df)
51 | except ModuleNotFoundError as e:
52 | print(df)
53 |
54 | def pretty_print(df,
55 | newlines=True,
56 | col_newlines=True,
57 | max_rows=None,
58 | max_columns=None,
59 | max_colwidth=None,
60 | transpose=True,
61 | precision=3,
62 | float_format=None,
63 | multi=False,
64 | simple=None,
65 | vcols=None,
66 | vertical_cols=None):
67 | """More human-viewable display of pd.DataFrame and numpy arrays.
68 |
69 | newlines :
70 |
71 | If True, then set pandas style to display whitespace as newlines
72 |
73 | transpose :
74 |
75 | If True, then show pd.Series as a 1-by-* DataFrame. This is
76 | sometimes easier to view, especially if displaying multiple
77 | pd.Series
78 |
79 | """
80 |
81 | from IPython.display import display, HTML
82 |
83 | # Set numpy display config
84 | np.set_printoptions(precision=2, linewidth=200)
85 |
86 | if max_rows is None:
87 | max_rows = pd.options.display.max_rows
88 |
89 | if max_columns is None:
90 | # The default 'pd.options.display.max_columns' is actually 20,
91 | # but I find that I typically want to view more columns, so I set it 50
92 | # here
93 | max_columns = 75
94 |
95 | if max_colwidth is None:
96 | max_colwidth = 150
97 | elif max_colwidth=='default':
98 | max_colwidth = pd.options.display.max_colwidth
99 |
100 | if isinstance(float_format, str):
101 | float_format = lambda x: float_format % x
102 |
103 | if isinstance(df, pd.Series) and transpose:
104 | # Convert pd.Series to a 1-by-* pd.DataFrame
105 | df = df.to_frame().T
106 |
107 | if multi:
108 | df = multiline(df)
109 |
110 | if (vertical_cols is None) and (vcols is not None):
111 | vertical_cols = vcols
112 |
113 | with pd.option_context("display.max_rows", max_rows):
114 | with pd.option_context("max_colwidth", max_colwidth):
115 | with pd.option_context("display.max_columns", max_columns):
116 | with pd.option_context("precision", precision):
117 | # with pd.option_context('display.float_format', float_format):
118 | # newlines==True is only applicable when `df` is a DataFrame (because pd.Series has no property `style`)
119 | if newlines and isinstance(df, pd.DataFrame):
120 | if col_newlines:
121 | df = df.rename(columns=lambda x: '\n'.join(x.replace('_',' ').split()) if isinstance(x, str) else x)
122 |
123 | if simple:
124 | # Filter for columns that contain scalar values, e.g. no tuples, lists, etc.
125 | # Also, filter out strings that are >1000 characters
126 | df = df.loc[:, [all([not hasattr(x, '__iter__') or (isinstance(x, str) and len(x) < 1000) for x in df[c]]) for c in df.columns]]
127 |
128 | # Ipython bug: max_rows is not adhered to by
129 | # Ipython.display() when dataframe style is set.
130 | # Fix: Do a head()
131 | df_head = df.head(max_rows)
132 |
133 | # If index is categorical, then change to the original dtype for faster display
134 | if len(df_head.index.names)==1 and df.index.dtype.name=='category':
135 | df_head = df_head.copy()
136 | df_head.index = np.array(df_head.index)
137 |
138 | if vertical_cols:
139 | df_head = df_head.style.set_table_styles(
140 | [dict(selector="th",props=[('max-width', '80px')]),
141 | # [dict(selector="th",props=[('max-width', '40ch')]),
142 | dict(selector="th.col_heading",
143 | props=[("writing-mode", "vertical-rl"),
144 | ('transform', 'rotateZ(180deg)'),
145 | ('vertical-align', 'top'),
146 | # ('white-space', 'pre-wrap'),
147 | ])]
148 | )
149 |
150 | else:
151 | # df_head = df_head.set_properties(**{'white-space': 'pre-wrap',})
152 | df_head = df_head.style.set_properties(**{'white-space': 'pre-wrap',})
153 |
154 |
155 | display(df_head)
156 |
157 | # df_tail = df.tail(max_rows)
158 | # df_tail = df_tail.style.set_properties(**{'white-space': 'pre-wrap',})
159 | # display(df_tail)
160 | else:
161 | display(df)
162 |
163 | # if newlines:
164 | # # Need to manually do a pd.DataFrame.head() because the
165 | # # pd.option_context doesn't really do much as conversion
166 | # # to HTML is done first
167 | # max_rows = pd.options.display.max_rows
168 | # display( HTML( df.head(max_rows).to_html().replace("\\n","
") ) )
169 | # else:
170 | # display( df )
171 |
172 | # Reset numpy display config
173 | np.set_printoptions()
174 |
175 | def pprint(df, **kwargs):
176 | pretty_print(df, **kwargs)
177 |
178 | def run_cmd(cmd, tee=True, shell=True, env=None, wait=True, debug=False, verbose=False, **kwargs):
179 | """Runs a command, and returns the output live.
180 |
181 | If stdout and stderr are not specified, then they are piped by default, and printed live
182 | """
183 |
184 | if env:
185 | cmd = utils.make_cmd(cmd, env=env)
186 |
187 | if debug or verbose:
188 | tprint('Running command:')
189 | print(cmd)
190 | if debug:
191 | return
192 |
193 | # if ('shell' not in kwargs) or (('shell' in kwargs) and (not kwargs['shell'])):
194 | if not shell:
195 | cmd = shlex.split(cmd)
196 |
197 | if 'stdout' not in kwargs:
198 | kwargs['stdout'] = subprocess.PIPE
199 | if 'stderr' not in kwargs:
200 | kwargs['stderr'] = subprocess.STDOUT
201 |
202 | p = subprocess.Popen(cmd, shell=shell, **kwargs)
203 |
204 | if tee:
205 | # Live stream the output
206 | # From https://stackoverflow.com/a/18422264
207 | for line in iter(p.stdout.readline, b''): # replace '' with b'' for Python 3
208 | # sys.stdout.write(line)
209 | sys.stdout.write(line.decode())
210 | #f.write(line)
211 | else:
212 | if wait:
213 | p.wait()
214 |
215 | if tee or wait:
216 | p.wait()
217 | poll = p.poll()
218 | if poll != 0 :
219 | print('poll:', poll)
220 | assert poll==0, 'Did not successfully run command: {}'.format(cmd)
221 | return p
222 |
223 | def make_cmd(*cmd_list, env=None, sep='&&\\\n'):
224 | """Formats a set of commands that's suitable to run with
225 | `subprocess`. Handles two tasks:
226 |
227 | (1) Automatically adds commands to initialize a conda virtual
228 | environment (e.g. anvio-master-zelda) in order to have the
229 | correct paths.
230 |
231 | (2) Split multiple commands by newlines and the '&&' connector.
232 |
233 | """
234 |
235 | if isinstance(cmd_list, str):
236 | cmd_list = [ cmd_list ]
237 | else:
238 | cmd_list = list(cmd_list)
239 |
240 | if env is None:
241 | pass
242 | else:
243 | cmd_list.insert(0, 'conda activate {}'.format(env))
244 |
245 | # Constants for loading conda environments in a subprocess
246 | conda_local = 'eval "$(/scratch/miniconda/bin/conda shell.bash hook)" && conda deactivate'
247 |
248 | cmd_list.insert(0, conda_local)
249 |
250 | return (' ' + sep).join(cmd_list)
251 |
252 | def eprint(i, length, prefix='', suffix='', print=True):
253 | """
254 | Prints out an loop enumeration statement, e.g.
255 |
256 | Sample: 1 out of 122: USA0001_01 (02:16:40 PM)
257 | """
258 |
259 | string = '{prefix}: {i} out of {length}: {suffix}'.format(prefix=prefix, i=i+1, length=length, suffix=suffix)
260 | if print:
261 | time_print(string)
262 | else:
263 | return string
264 |
265 | def tprint(*x, day=False, second=True, end='\n', verbose=None):
266 | if (verbose is None) or verbose:
267 | time_print(*x, day=day, second=second, end=end)
268 |
269 | def time_print(*x, day=False, second=True, end='\n'):
270 | fmt = []
271 | if day: fmt.append('%x')
272 | if second: fmt.append('%X')
273 | fmt = ' '.join(fmt)
274 |
275 | # if len(x)==1: x = x[0]
276 | # # If a string, then re-incase it as a list, to prevent individual
277 | # # characters being passed
278 | # if isinstance(x, (str, np.str_)): x = [x]
279 |
280 | print(*x, '(%s)' % datetime.now().strftime(fmt), end=end)
281 | sys.stdout.flush()
282 |
283 | @contextmanager
284 | def silence_output(stdout=True, stderr=True):
285 | """Silences stdout and/or stderr with a context, e.g.
286 |
287 | with silence_stdout():
288 | print("will not print")
289 |
290 | print("this will print")
291 |
292 | Code inspired from
293 | https://stackoverflow.com/questions/6735917/redirecting-stdout-to-nothing-in-python
294 |
295 | """
296 |
297 | devnull = open(os.devnull, "w")
298 | if stdout: old_stdout = sys.stdout
299 | if stderr: old_stderr = sys.stderr
300 |
301 | try:
302 | if stdout: sys.stdout = devnull
303 | if stderr: sys.stderr = devnull
304 | yield devnull
305 | finally:
306 | if stdout: sys.stdout = old_stdout
307 | if stderr: sys.stderr = old_stderr
308 |
309 | @contextmanager
310 | def redirect_output(stdout=None, stderr=None):
311 | try:
312 | old_stdout = sys.stdout
313 | old_stderr = sys.stderr
314 |
315 | if stdout: sys.stdout = stdout
316 | if stderr: sys.stderr = stderr
317 | yield 0
318 | finally:
319 | if stdout: sys.stdout = old_stdout
320 | if stderr: sys.stderr = old_stderr
321 |
322 |
323 | def rearrange(df, columns, indices, start=None):
324 | """
325 | Rearranges columns in a dataframe, so that `columns` occurs at the column indices specified by `indices`
326 | """
327 |
328 | if isinstance(columns, str):
329 | columns = [columns]
330 | indices = [indices]
331 |
332 | # if isinstance(indices, int) or indices=='len':
333 | # indices = [indices for _ in range(len(columns))]
334 | if isinstance(indices, int) and (start is True):
335 | indices = np.arange(indices, indices + len(columns))
336 |
337 | new_columns = [c for c in df.columns if c not in columns]
338 | for c, i in zip(columns, indices):
339 | if i=='len':
340 | new_columns.append(c)
341 | else:
342 | new_columns.insert(i, c)
343 | return df[new_columns]
344 |
345 | def as_flat(x):
346 | if scipy.sparse.issparse(x) and (x.nnz==0):
347 | # Need to handle the special case when the input `x` is 1-by-0 scipy sparse matrix.
348 | # - This happens when you index a scipy matrix with empty indices, e.g. sp[[],[]].
349 | # - Solution: manually create an empty 1-D array with the same dtype
350 | return np.array([], dtype=x.dtype)
351 | else:
352 | return np.array(x).flatten()
353 |
354 |
355 |
356 | def downcast_uint(x):
357 | """Convert an array so that
358 | Get the smallest uint data type to downcast np.ndarray `x`, without clipping values"""
359 |
360 | assert np.issubdtype(x.dtype, np.integer) or np.issubdtype(x.dtype, np.bool_)
361 |
362 | if x.size==0:
363 | # This is an empty array, so use np.uint8
364 | return x.astype(np.bool)
365 |
366 | max_val = x.max()
367 |
368 | # Check that value is non-negative
369 | assert max_val >= 0
370 |
371 | if max_val <= 1:
372 | return x.astype(np.bool)
373 | elif max_val <= (2**8 - 1):
374 | return x.astype(np.uint8)
375 | elif max_val <= (2**16 - 1):
376 | return x.astype(np.uint16)
377 | elif max_val <= (2**32 - 1):
378 | return x.astype(np.uint32)
379 | elif max_val <= (2**64 - 1):
380 | return x.astype(np.uint64)
381 |
382 |
383 |
384 | @contextmanager
385 | def TemporaryDirectory(name=None, post_delete=None, path=True, verbose=False,
386 | overwrite=None, overwrite_err_msg=None):
387 | """Creates a context manager that can be invoked with the paradigm
388 |
389 | with TemporaryDirectory() as f:
390 |
391 |
392 | The advantage of this function over tempfile.TemporaryDirectory()
393 | is that this function can take in a pre-specified directory
394 | name. In that case, the directory is not deleted at the end of the
395 | `with` statement, unless post_delete=True.
396 |
397 | If a pre-specified directory name is given, then that directory is
398 | created, if it doesn't already exist.
399 |
400 | If path=True, then return a pathlib.Path instance (instead of a
401 | string)
402 |
403 | overwrite : If False, then check if file already exists, and raise Exception if so. Default: True.
404 |
405 | post_delete : If True, then delete the directory upon exiting this context. If False, don't delete. If not specified, then set to True if `name` is None, otherwise False.
406 | """
407 |
408 | try:
409 | if name is None:
410 | if post_delete is None:
411 | post_delete = True
412 | name = tempfile.mkdtemp()
413 | if verbose:
414 | print('Created temporary directory:', name)
415 | else:
416 | check_overwrite(name, overwrite, overwrite_err_msg)
417 | os.makedirs(name, exist_ok=True)
418 | if post_delete is None:
419 | post_delete = False
420 |
421 | if verbose:
422 | print('Using temporary directory:', name, end='')
423 | if post_delete:
424 | print(' (This will be deleted after execution)')
425 | else:
426 | print(' (This will NOT be deleted after execution)')
427 |
428 | if path:
429 | name = Path(name)
430 |
431 | yield name
432 |
433 | finally:
434 | if post_delete:
435 | if verbose:
436 | print('Deleting temporary directory:', name)
437 | shutil.rmtree(name)
438 | else:
439 | if verbose:
440 | print(f'Temporary directory {name} was NOT deleted.')
441 |
442 | def check_overwrite(path, overwrite=None, overwrite_err_msg=None):
443 | """
444 | overwrite has three modes (Default: 0)
445 |
446 | 0 : Don't do anything. Just let the file/directory be overwritten however.
447 | 1 : Check if file at location 'path' already exists, and raise Exception if so.
448 | 2 : Check if file at location 'path' already exists, and delete it if so.
449 | """
450 |
451 | if overwrite is None:
452 | overwrite = 0
453 | assert overwrite in [0,1,2]
454 |
455 | if (overwrite != 0) and os.path.exists(path):
456 | if overwrite==1:
457 | if overwrite_err_msg is None:
458 | overwrite_err_msg = f"Attempting to create file or directory at {path}, but it already exists. Delete it, or set overwrite to True."
459 | raise Exception(overwrite_err_msg)
460 |
461 | elif overwrite==2:
462 | if os.path.isfile(path):
463 | os.remove(path)
464 | else:
465 | shutil.rmtree(path)
466 |
467 |
468 | def subset_dict(d, keys):
469 | """Return subset of dictionary"""
470 |
471 | return {k : d[k] for k in keys}
472 |
473 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy
2 | pandas
3 | scipy
4 | scikit-learn
5 | numba
6 | blosc
7 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup, find_packages
2 |
3 | # import pathlib
4 | # here = pathlib.Path(__file__).parent.resolve()
5 | # # Get the long description from the README file
6 | # long_description = (here / 'README.md').read_text(encoding='utf-8')
7 |
8 | long_description = None
9 |
10 | setup(
11 | name='plasx',
12 | # version='0.1',
13 | description='A plasmid sequence classifier',
14 | long_description=long_description,
15 | long_description_content_type='text/markdown',
16 | url='https://github.com/michaelkyu/plasx',
17 | author='Michael Ku Yu',
18 | author_email='michaelkuyu@gmail.com',
19 | classifiers=[
20 | 'Development Status :: 3 - Alpha',
21 | 'Intended Audience :: Science/Research',
22 | 'Topic :: Scientific/Engineering :: Bio-Informatics',
23 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
24 | 'Programming Language :: Python :: 3',
25 | 'Programming Language :: Python :: 3.7',
26 | 'Programming Language :: Python :: 3.8',
27 | 'Programming Language :: Python :: 3.9',
28 | 'Programming Language :: Python :: 3 :: Only',
29 | ],
30 | keywords='plasmid, metagenomics',
31 | packages=find_packages(),
32 | python_requires='>=3.7, <4',
33 | install_requires=[
34 | 'numpy',
35 | 'pandas',
36 | 'scipy',
37 | 'scikit-learn',
38 | 'numba',
39 | 'blosc'],
40 | entry_points={
41 | 'console_scripts': [
42 | 'plasx=plasx.plasx_script:run',
43 | ],
44 | },
45 | project_urls={
46 | 'Source': 'https://github.com/michaelkyu/plasx/',
47 | },
48 | )
49 |
--------------------------------------------------------------------------------
/test/test-contigs-cogs-and-pfams.txt:
--------------------------------------------------------------------------------
1 | gene_callers_id source accession function e_value
2 | 0 COG14_FUNCTION COG0187 DNA gyrase/topoisomerase IV, subunit B 4.4e-136
3 | 1 COG14_FUNCTION COG0542 ATP-dependent Clp protease ATP-binding subunit ClpA 1.7e-95
4 | 3 COG14_FUNCTION COG3512 CRISPR/Cas system-associated protein Cas2, endoribonuclease 2.1e-28
5 | 4 COG14_FUNCTION COG1518 CRISPR/Cas system-associated endonuclease Cas1 3.1e-30
6 | 5 COG14_FUNCTION COG1393 Arsenate reductase and related proteins, glutaredoxin family 1.9e-61
7 | 6 COG14_FUNCTION COG0468 RecA/RadA recombinase 4.4e-180
8 | 7 COG14_FUNCTION COG1058!!!COG1546 Predicted nucleotide-utilizing enzyme related to molybdopterin-biosynthesis enzyme MoeA!!!Nicotinamide mononucleotide (NMN) deamidase PncC 7.8e-170
9 | 8 COG14_FUNCTION COG2818 3-methyladenine DNA glycosylase Tag 3.1e-21
10 | 9 COG14_FUNCTION COG0632 Holliday junction resolvasome RuvABC DNA-binding subunit 6.8e-84
11 | 11 COG14_FUNCTION COG0323 DNA mismatch repair ATPase MutL 6.1e-283
12 | 13 COG14_FUNCTION COG3279 DNA-binding response regulator, LytR/AlgR family 9.7e-28
13 | 15 COG14_FUNCTION COG0249 DNA mismatch repair ATPase MutS 0
14 | 16 COG14_FUNCTION COG4550 Cell fate regulator YmcA, YheA/YmcA/DUF963 family (controls sporulation, competence, biofilm development) 5e-13
15 | 17 COG14_FUNCTION COG1438 Arginine repressor 1.2e-42
16 | 18 COG14_FUNCTION COG0018 Arginyl-tRNA synthetase 4e-278
17 | 19 COG14_FUNCTION COG0015 Adenylosuccinate lyase 2.7e-242
18 | 20 COG14_FUNCTION COG1893 Ketopantoate reductase 3.9e-84
19 | 21 COG14_FUNCTION COG0026 Phosphoribosylaminoimidazole carboxylase (NCAIR synthetase) 1.9e-185
20 | 22 COG14_FUNCTION COG0041 Phosphoribosylcarboxyaminoimidazole (NCAIR) mutase 9.4e-73
21 | 23 COG14_FUNCTION COG0151 Phosphoribosylamine-glycine ligase 1.4e-219
22 | 24 COG14_FUNCTION COG3942 Surface antigen 9.1e-66
23 | 27 COG14_FUNCTION COG0334 Glutamate dehydrogenase/leucine dehydrogenase 2.9e-175
24 | 28 COG14_FUNCTION COG3705 ATP phosphoribosyltransferase regulatory subunit HisZ 7.7e-61
25 | 29 COG14_FUNCTION COG0040 ATP phosphoribosyltransferase 7.2e-68
26 | 30 COG14_FUNCTION COG0141 Histidinol dehydrogenase 1.1e-166
27 | 31 COG14_FUNCTION COG0131 Imidazoleglycerol phosphate dehydratase HisB 2.4e-65
28 | 32 COG14_FUNCTION COG0118 Imidazoleglycerol phosphate synthase glutamine amidotransferase subunit HisH 1.3e-66
29 | 33 COG14_FUNCTION COG0106 Phosphoribosylformimino-5-aminoimidazole carboxamide ribonucleotide (ProFAR) isomerase 3e-81
30 | 34 COG14_FUNCTION COG0107 Imidazole glycerol phosphate synthase subunit HisF 5.5e-102
31 | 35 COG14_FUNCTION COG0139!!!COG0140 Phosphoribosyl-AMP cyclohydrolase!!!Phosphoribosyl-ATP pyrophosphohydrolase 2.3e-85
32 | 36 COG14_FUNCTION COG2723 Beta-glucosidase/6-phospho-beta-glucosidase/beta-galactosidase 8.2e-174
33 | 37 COG14_FUNCTION COG1387 Histidinol phosphatase or related hydrolase of the PHP family 2.2e-58
34 | 39 COG14_FUNCTION COG0053 Divalent metal cation (Fe/Co/Zn/Cd) transporter 8.1e-89
35 | 40 COG14_FUNCTION COG3589 Uncharacterized protein 1.4e-72
36 | 41 COG14_FUNCTION COG1158 Transcription termination factor Rho 5.5e-138
37 | 42 COG14_FUNCTION COG0639 Diadenosine tetraphosphatase ApaH/serine/threonine protein phosphatase, PP2A family 2.2e-51
38 | 43 COG14_FUNCTION COG0583 DNA-binding transcriptional regulator, LysR family 4.1e-64
39 | 44 COG14_FUNCTION COG0726 Peptidoglycan/xylan/chitin deacetylase, PgdA/CDA1 family 1.6e-52
40 | 46 COG14_FUNCTION COG1966 Carbon starvation protein CstA 1.1e-171
41 | 48 COG14_FUNCTION COG3049 Penicillin V acylase or related amidase, Ntn superfamily 2.2e-133
42 | 51 COG14_FUNCTION COG4870 Cysteine protease, C1A family 5.4e-116
43 | 52 COG14_FUNCTION COG1105 Fructose-1-phosphate kinase or kinase (PfkB) 1.9e-52
44 | 53 COG14_FUNCTION COG0656 Aldo/keto reductase, related to diketogulonate reductase 4.6e-109
45 | 54 COG14_FUNCTION COG2207!!!COG4753 AraC-type DNA-binding domain and AraC-containing proteins!!!Two-component response regulator, YesN/AraC family, consists of REC and AraC-type DNA-binding domains 3.4e-66
46 | 58 COG14_FUNCTION COG1346 Putative effector of murein hydrolase 1.3e-65
47 | 59 COG14_FUNCTION COG1380 Putative effector of murein hydrolase LrgA, UPF0299 family 2.8e-16
48 | 61 COG14_FUNCTION COG0112 Glycine/serine hydroxymethyltransferase 7.8e-175
49 | 63 COG14_FUNCTION COG1386 Chromosome segregation and condensation protein ScpB 3.2e-46
50 | 64 COG14_FUNCTION COG1354 Chromatin segregation and condensation protein Rec8/ScpA/Scc1, kleisin family 3.1e-52
51 | 65 COG14_FUNCTION COG1994 Zn-dependent protease (includes SpoIVFB) 9.8e-19
52 | 66 COG14_FUNCTION COG0323!!!COG1293 DNA mismatch repair ATPase MutL!!!Predicted component of the ribosome quality control (RQC) complex, YloA/Tae2 family, contains fibronectin-binding (FbpA) and DUF814 domains 3.2e-146
53 | 67 COG14_FUNCTION COG0249 DNA mismatch repair ATPase MutS 6.8e-290
54 | 69 COG14_FUNCTION COG3279 DNA-binding response regulator, LytR/AlgR family 2e-37
55 | 70 COG14_FUNCTION COG3290 Sensor histidine kinase regulating citrate/malate metabolism 2.5e-54
56 | 71 COG14_FUNCTION COG0373 Glutamyl-tRNA reductase 1.2e-41
57 | 72 COG14_FUNCTION COG0452 Phosphopantothenoylcysteine synthetase/decarboxylase 2.6e-56
58 | 73 COG14_FUNCTION COG0791 Cell wall-associated hydrolase, NlpC family 9.7e-27
59 | 74 COG14_FUNCTION COG1696 D-alanyl-lipoteichoic acid acyltransferase DltB, MBOAT superfamily 3.7e-11
60 | 79 COG14_FUNCTION COG1396 Transcriptional regulator, contains XRE-family HTH domain 2.7e-09
61 | 80 COG14_FUNCTION COG0629 Single-stranded DNA-binding protein 9e-23
62 | 85 COG14_FUNCTION COG0497 DNA repair ATPase RecN 7.9e-94
63 | 88 COG14_FUNCTION COG4200 Uncharacterized protein 3.4e-24
64 | 89 COG14_FUNCTION COG4200 Uncharacterized protein 2.6e-29
65 | 90 COG14_FUNCTION COG0600 ABC-type nitrate/sulfonate/bicarbonate transport system, permease component 6.3e-74
66 | 91 COG14_FUNCTION COG1116 ABC-type nitrate/sulfonate/bicarbonate transport system, ATPase component 2.8e-47
67 | 92 COG14_FUNCTION COG0465 ATP-dependent Zn proteases 4.6e-164
68 | 93 COG14_FUNCTION COG0018 Arginyl-tRNA synthetase 1.3e-84
69 | 94 COG14_FUNCTION COG1268 Biotin transporter BioY 8.4e-21
70 | 96 COG14_FUNCTION COG1192 Cellulose biosynthesis protein BcsQ 1.8e-105
71 | 97 COG14_FUNCTION COG1475 Chromosome segregation protein Spo0J, contains ParB-like nuclease domain 4.1e-51
72 | 99 COG14_FUNCTION COG1669 Predicted nucleotidyltransferase 6.1e-13
73 | 100 COG14_FUNCTION COG0582 Integrase 1.7e-73
74 | 101 COG14_FUNCTION COG1996 DNA-directed RNA polymerase, subunit RPC12/RpoP, contains C4-type Zn-finger 3.6e-18
75 | 103 COG14_FUNCTION COG4227 Antirestriction protein ArdC 9.3e-50
76 | 104 COG14_FUNCTION COG0553!!!COG0827!!!COG4646 Superfamily II DNA or RNA helicase, SNF2 family!!!Adenine-specific DNA methylase!!!Adenine-specific DNA methylase, N12 class 4.6e-10
77 | 105 COG14_FUNCTION COG1122 Energy-coupling factor transporter ATP-binding protein EcfA2 2e-57
78 | 107 COG14_FUNCTION COG5418 Predicted secreted protein 3.8e-30
79 | 108 COG14_FUNCTION COG0103 Ribosomal protein S9 1.5e-66
80 | 109 COG14_FUNCTION COG0102 Ribosomal protein L13 3.5e-77
81 | 110 COG14_FUNCTION COG0675 Transposase 1.7e-131
82 | 111 COG14_FUNCTION COG1943 REP element-mobilizing transposase RayT 1.5e-50
83 | 113 COG14_FUNCTION COG1478 F420-0:Gamma-glutamyl ligase (F420 biosynthesis) 6e-164
84 | 114 COG14_FUNCTION COG0607 Rhodanese-related sulfurtransferase 1.7e-25
85 | 115 COG14_FUNCTION COG2191 Formylmethanofuran dehydrogenase subunit E 1.7e-07
86 | 116 COG14_FUNCTION COG2265 tRNA/tmRNA/rRNA uracil-C5-methylase, TrmA/RlmC/RlmD family 3.3e-33
87 | 118 COG14_FUNCTION COG1609 DNA-binding transcriptional regulator, LacI/PurR family 1.1e-58
88 | 119 COG14_FUNCTION COG0507 ATP-dependent exoDNAse (exonuclease V), alpha subunit, helicase superfamily I 2.4e-166
89 | 121 COG14_FUNCTION COG0583 DNA-binding transcriptional regulator, LysR family 2.1e-105
90 | 123 COG14_FUNCTION COG1607 Acyl-CoA hydrolase 3.6e-43
91 | 124 COG14_FUNCTION COG0583 DNA-binding transcriptional regulator, LysR family 2.1e-71
92 | 125 COG14_FUNCTION COG0679 Predicted permease 4.5e-90
93 | 128 COG14_FUNCTION COG1674 DNA segregation ATPase FtsK/SpoIIIE and related proteins 5.1e-24
94 | 130 COG14_FUNCTION COG2946 DNA relaxase NicK 1.1e-266
95 | 133 COG14_FUNCTION COG0433 Archaeal DNA helicase HerA or a related bacterial ATPase, contains HAS-barrel and ATPase domains 5.9e-270
96 | 135 COG14_FUNCTION COG2801 Transposase InsO and inactivated derivatives 1.8e-72
97 | 138 COG14_FUNCTION COG3206 Uncharacterized protein involved in exopolysaccharide biosynthesis 3.9e-83
98 | 141 COG14_FUNCTION COG0776 Bacterial nucleoid DNA-binding protein 4.9e-21
99 | 142 COG14_FUNCTION COG3843 Type IV secretory pathway, VirD2 components (relaxase) 8.8e-14
100 | 148 COG14_FUNCTION COG0675 Transposase 2.7e-67
101 | 149 COG14_FUNCTION COG1943 REP element-mobilizing transposase RayT 5.9e-19
102 | 150 COG14_FUNCTION COG1112!!!COG1198 Superfamily I DNA and/or RNA helicase!!!Primosomal protein N' (replication factor Y) - superfamily II helicase 1.6e-13
103 | 152 COG14_FUNCTION COG0577!!!COG1136 ABC-type antimicrobial peptide transport system, permease component!!!ABC-type lipoprotein export system, ATPase component 7.4e-41
104 | 153 COG14_FUNCTION COG4974 Site-specific recombinase XerD 4.9e-169
105 | 154 COG14_FUNCTION COG0292 Ribosomal protein L20 1.1e-35
106 | 156 COG14_FUNCTION COG5527 Protein involved in initiation of plasmid replication 2.6e-28
107 | 158 COG14_FUNCTION COG1695 DNA-binding transcriptional regulator, PadR family 1.3e-70
108 | 159 COG14_FUNCTION COG0745 DNA-binding response regulator, OmpR family, contains REC and winged-helix (wHTH) domain 2.9e-10
109 | 160 COG14_FUNCTION COG0745 DNA-binding response regulator, OmpR family, contains REC and winged-helix (wHTH) domain 4.1e-16
110 | 161 COG14_FUNCTION COG1961 Site-specific DNA recombinase related to the DNA invertase Pin 9.3e-66
111 | 165 COG14_FUNCTION COG1598 Predicted nuclease of the RNAse H fold, HicB family 9.4e-36
112 | 170 COG14_FUNCTION COG1961 Site-specific DNA recombinase related to the DNA invertase Pin 1.2e-61
113 | 172 COG14_FUNCTION COG0286 Type I restriction-modification system, DNA methylase subunit 1e-87
114 | 173 COG14_FUNCTION COG0732 Restriction endonuclease S subunit 5.7e-77
115 | 174 COG14_FUNCTION COG0732 Restriction endonuclease S subunit 2.3e-38
116 | 175 COG14_FUNCTION COG0582 Integrase 1.6e-112
117 | 176 COG14_FUNCTION COG0732 Restriction endonuclease S subunit 7.6e-54
118 | 177 COG14_FUNCTION COG0582 Integrase 1.5e-18
119 | 179 COG14_FUNCTION COG1192 Cellulose biosynthesis protein BcsQ 8.3e-23
120 | 180 COG14_FUNCTION COG1475 Chromosome segregation protein Spo0J, contains ParB-like nuclease domain 2.5e-16
121 | 183 COG14_FUNCTION COG3843 Type IV secretory pathway, VirD2 components (relaxase) 1.4e-28
122 | 184 COG14_FUNCTION COG0553!!!COG0827!!!COG4646 Superfamily II DNA or RNA helicase, SNF2 family!!!Adenine-specific DNA methylase!!!Adenine-specific DNA methylase, N12 class 1.6e-239
123 | 185 COG14_FUNCTION COG4974 Site-specific recombinase XerD 2.9e-38
124 | 187 COG14_FUNCTION COG4734 Antirestriction protein 9.3e-29
125 | 189 COG14_FUNCTION COG4974 Site-specific recombinase XerD 4.1e-116
126 | 192 COG14_FUNCTION COG1961 Site-specific DNA recombinase related to the DNA invertase Pin 6.1e-56
127 | 193 COG14_FUNCTION COG1961 Site-specific DNA recombinase related to the DNA invertase Pin 3.5e-71
128 | 162 Pfam PF17295.2 Domain of unknown function (DUF5348) 7e-28
129 | 165 Pfam PF05534.12 HicB family 1.1e-13
130 | 165 Pfam PF15919.5 HicB_like antitoxin of bacterial toxin-antitoxin system 4.1e-17
131 | 158 Pfam PF13601.6 Winged helix DNA-binding domain 3.7e-10
132 | 158 Pfam PF03551.14 Transcriptional regulator PadR-like family 1.7e-12
133 | 156 Pfam PF01051.21 Initiator Replication protein 1.3e-37
134 | 161 Pfam PF00239.21 Resolvase, N terminal domain 2.6e-32
135 | 160 Pfam PF00486.28 Transcriptional regulatory protein, C terminal 2.7e-26
136 | 159 Pfam PF00486.28 Transcriptional regulatory protein, C terminal 5.7e-23
137 | 152 Pfam PF00005.27 ABC transporter 4.4e-16
138 | 150 Pfam PF11784.8 Protein of unknown function (DUF3320) 1.4e-11
139 | 148 Pfam PF01385.19 Probable transposase 5.9e-15
140 | 148 Pfam PF07282.11 Putative transposase DNA-binding domain 1.7e-09
141 | 153 Pfam PF00589.22 Phage integrase family 1.9e-55
142 | 153 Pfam PF02899.17 Phage integrase, N-terminal SAM-like domain 6.8e-22
143 | 153 Pfam PF13495.6 Phage integrase, N-terminal SAM-like domain 2.2e-10
144 | 154 Pfam PF00453.18 Ribosomal protein L20 5.9e-29
145 | 149 Pfam PF01797.16 Transposase IS200 like 2.6e-35
146 | 105 Pfam PF13304.6 AAA domain, putative AbiEii toxin, Type IV TA system 5.7e-14
147 | 96 Pfam PF13614.6 AAA domain 1.8e-77
148 | 105 Pfam PF00005.27 ABC transporter 2.9e-35
149 | 96 Pfam PF02374.15 Anion-transporting ATPase 6.1e-13
150 | 96 Pfam PF01656.23 CobQ/CobB/MinD/ParA nucleotide binding domain 5.6e-32
151 | 96 Pfam PF06564.12 Cellulose biosynthesis protein BcsQ 1.4e-18
152 | 101 Pfam PF14311.6 Probable Zinc-ribbon domain 1.7e-17
153 | 106 Pfam PF07155.12 ECF-type riboflavin transporter, S component 1.2e-12
154 | 96 Pfam PF00142.18 4Fe-4S iron sulfur cluster binding proteins, NifH/frxC family 2.5e-17
155 | 96 Pfam PF09140.11 ATPase MipZ 2.8e-20
156 | 99 Pfam PF01909.23 Nucleotidyltransferase domain 8.3e-14
157 | 96 Pfam PF10609.9 NUBPL iron-transfer P-loop NTPase 8.2e-16
158 | 97 Pfam PF02195.18 ParB-like nuclease domain 8.8e-32
159 | 100 Pfam PF00589.22 Phage integrase family 3.5e-32
160 | 99 Pfam PF18765.1 Polymerase beta, Nucleotidyltransferase 3.8e-14
161 | 123 Pfam PF03061.22 Thioesterase superfamily 1.9e-17
162 | 129 Pfam PF14359.6 Domain of unknown function (DUF4406) 3.3e-36
163 | 127 Pfam PF14057.6 GGGtGRT protein 1e-77
164 | 124 Pfam PF00126.27 Bacterial regulatory helix-turn-helix protein, lysR family 9.7e-22
165 | 121 Pfam PF00126.27 Bacterial regulatory helix-turn-helix protein, lysR family 1.1e-20
166 | 130 Pfam PF12844.7 Helix-turn-helix domain 2.3e-15
167 | 130 Pfam PF01381.22 Helix-turn-helix 5.7e-19
168 | 130 Pfam PF13560.6 Helix-turn-helix domain 1e-12
169 | 121 Pfam PF03466.20 LysR substrate binding domain 6e-46
170 | 124 Pfam PF03466.20 LysR substrate binding domain 1.2e-33
171 | 125 Pfam PF03547.18 Membrane transport protein 1.7e-23
172 | 130 Pfam PF02486.19 Replication initiation factor 1.3e-67
173 | 130 Pfam PF18106.1 Rolling Circle replication initiation protein N-terminal domain 2.2e-34
174 | 92 Pfam PF00004.29 ATPase family associated with various cellular activities (AAA) 1e-36
175 | 92 Pfam PF17862.1 AAA+ lid domain 8.2e-17
176 | 89 Pfam PF12730.7 ABC-2 family transporter protein 3.7e-19
177 | 88 Pfam PF12730.7 ABC-2 family transporter protein 2.1e-17
178 | 91 Pfam PF00005.27 ABC transporter 5.3e-18
179 | 93 Pfam PF03485.16 Arginyl tRNA synthetase N terminal domain 1.4e-19
180 | 94 Pfam PF02632.14 BioY family 3.2e-34
181 | 90 Pfam PF00528.22 Binding-protein-dependent transport system inner membrane component 4.4e-26
182 | 93 Pfam PF14501.6 GHKL domain 3.5e-20
183 | 92 Pfam PF01434.18 Peptidase family M41 1.5e-68
184 | 93 Pfam PF00750.19 tRNA synthetases class I (R) 3.9e-44
185 | 53 Pfam PF00248.21 Aldo/keto reductase family 1.4e-48
186 | 48 Pfam PF02275.18 Linear amide C-N hydrolases, choloylglycine hydrolase family 1.1e-54
187 | 51 Pfam PF07833.11 Copper amine oxidase N-terminal domain 2.6e-12
188 | 54 Pfam PF17853.1 GGDEF-like domain 5.7e-13
189 | 54 Pfam PF12833.7 Helix-turn-helix domain 2e-16
190 | 54 Pfam PF00165.23 Bacterial regulatory helix-turn-helix proteins, AraC family 1.3e-10
191 | 59 Pfam PF03788.14 LrgA family 1.6e-27
192 | 58 Pfam PF04172.16 LrgB-like family 2.3e-79
193 | 51 Pfam PF00112.23 Papain family cysteine protease 3.5e-16
194 | 52 Pfam PF00294.24 pfkB family carbohydrate kinase 2.6e-50
195 | 52 Pfam PF08543.12 Phosphomethylpyrimidine kinase 1.2e-12
196 | 54 Pfam PF00072.24 Response regulator receiver domain 2.9e-27
197 | 76 Pfam PF17989.1 Actin like proteins N terminal domain 1.6e-12
198 | 83 Pfam PF12684.7 PDDEXK-like domain of unknown function (DUF3799) 2.3e-53
199 | 82 Pfam PF02732.15 ERCC4 domain 7.5e-09
200 | 72 Pfam PF02441.19 Flavoprotein 1.2e-21
201 | 79 Pfam PF01381.22 Helix-turn-helix 2.1e-12
202 | 73 Pfam PF00877.19 NlpC/P60 family 7.6e-33
203 | 73 Pfam PF08239.11 Bacterial SH3 domain 8.6e-10
204 | 80 Pfam PF00436.25 Single-strand binding protein family 2e-31
205 | 76 Pfam PF06406.11 StbA protein 9.1e-11
206 | 179 Pfam PF13614.6 AAA domain 1.4e-42
207 | 179 Pfam PF02374.15 Anion-transporting ATPase 3e-10
208 | 179 Pfam PF01656.23 CobQ/CobB/MinD/ParA nucleotide binding domain 2.3e-19
209 | 179 Pfam PF06564.12 Cellulose biosynthesis protein BcsQ 1.5e-11
210 | 179 Pfam PF00142.18 4Fe-4S iron sulfur cluster binding proteins, NifH/frxC family 9.5e-13
211 | 173 Pfam PF01420.19 Type I restriction modification DNA specificity domain 5.9e-30
212 | 176 Pfam PF01420.19 Type I restriction modification DNA specificity domain 1.6e-19
213 | 174 Pfam PF01420.19 Type I restriction modification DNA specificity domain 4.5e-09
214 | 179 Pfam PF09140.11 ATPase MipZ 1.9e-11
215 | 172 Pfam PF02384.16 N-6 DNA Methylase 3.7e-29
216 | 179 Pfam PF10609.9 NUBPL iron-transfer P-loop NTPase 5.4e-13
217 | 175 Pfam PF00589.22 Phage integrase family 1.5e-28
218 | 177 Pfam PF00589.22 Phage integrase family 5.9e-14
219 | 175 Pfam PF13495.6 Phage integrase, N-terminal SAM-like domain 1.9e-11
220 | 170 Pfam PF00239.21 Resolvase, N terminal domain 1.6e-35
221 | 179 Pfam PF07015.11 VirC1 protein 1.2e-07
222 | 133 Pfam PF12846.7 AAA-like domain 2.2e-12
223 | 141 Pfam PF00216.21 Bacterial DNA-binding protein 6.3e-37
224 | 135 Pfam PF13276.6 HTH-like domain 3.7e-16
225 | 141 Pfam PF18291.1 HU domain fused to wHTH, Ig, or Glycine-rich motif 1.8e-14
226 | 143 Pfam PF05713.11 Bacterial mobilisation protein (MobC) 8.2e-13
227 | 138 Pfam PF01076.19 Plasmid recombination enzyme 8.3e-23
228 | 142 Pfam PF03432.14 Relaxase/Mobilisation nuclease domain 1.4e-35
229 | 143 Pfam PF01402.21 Ribbon-helix-helix protein, copG family 7e-08
230 | 135 Pfam PF00665.26 Integrase core domain 3.1e-26
231 | 135 Pfam PF13333.6 Integrase core domain 1.1e-10
232 | 135 Pfam PF13683.6 Integrase core domain 7.2e-10
233 | 132 Pfam PF12648.7 TcpE family 2.9e-31
234 | 1 Pfam PF07724.14 AAA domain (Cdc48 subfamily) 1e-50
235 | 1 Pfam PF07728.14 AAA domain (dynein-related subfamily) 9.8e-12
236 | 8 Pfam PF03352.13 Methyladenine glycosylase 5.3e-23
237 | 5 Pfam PF03960.15 ArsC family 1e-25
238 | 6 Pfam PF06745.13 KaiC 1.5e-09
239 | 2 Pfam PF09711.10 CRISPR-associated protein (Cas_Csn2) 9.7e-47
240 | 7 Pfam PF02464.17 Competence-damaged protein 8.5e-50
241 | 7 Pfam PF18146.1 Damage-inducible protein CinA KH domain 1.2e-23
242 | 1 Pfam PF10431.9 C-terminal, D2-small domain, of ClpB protein 1.3e-26
243 | 3 Pfam PF09827.9 CRISPR associated protein Cas2 6.8e-21
244 | 11 Pfam PF01119.19 DNA mismatch repair protein, C-terminal domain 1.9e-38
245 | 5 Pfam PF00462.24 Glutaredoxin 2.4e-09
246 | 11 Pfam PF02518.26 Histidine kinase-, DNA gyrase B-, and HSP90-like ATPase 2.3e-10
247 | 11 Pfam PF13589.6 Histidine kinase-, DNA gyrase B-, and HSP90-like ATPase 1.3e-16
248 | 9 Pfam PF14520.6 Helix-hairpin-helix domain 5.5e-15
249 | 7 Pfam PF00994.24 Probable molybdopterin binding domain 1.6e-34
250 | 11 Pfam PF08676.11 MutL C terminal dimerisation domain 1.1e-40
251 | 6 Pfam PF08423.11 Rad51 3.8e-13
252 | 6 Pfam PF00154.21 recA bacterial DNA recombination protein 2.2e-142
253 | 9 Pfam PF07499.13 RuvA, C-terminal domain 3.4e-14
254 | 9 Pfam PF01330.21 RuvA N terminal domain 7.7e-22
255 | 19 Pfam PF10397.9 Adenylosuccinate lyase C-terminus 1.8e-29
256 | 22 Pfam PF00731.20 AIR carboxylase 6.3e-65
257 | 17 Pfam PF01316.21 Arginine repressor, DNA binding domain 1.7e-27
258 | 17 Pfam PF02863.18 Arginine repressor, C-terminal domain 3.8e-23
259 | 18 Pfam PF03485.16 Arginyl tRNA synthetase N terminal domain 3.7e-23
260 | 21 Pfam PF02222.22 ATP-grasp domain 5e-49
261 | 21 Pfam PF02655.14 ATP-grasp domain 2.3e-09
262 | 23 Pfam PF02655.14 ATP-grasp domain 3.5e-08
263 | 16 Pfam PF06133.11 Control of competence regulator ComK, YlbF/YmcA 6.9e-17
264 | 23 Pfam PF02786.17 Carbamoyl-phosphate synthase L chain, ATP binding domain 3.6e-08
265 | 21 Pfam PF07478.13 D-ala D-ala ligase C-terminus 1.8e-08
266 | 18 Pfam PF05746.15 DALR anticodon binding domain 3.4e-36
267 | 14 Pfam PF11457.8 Protein of unknown function (DUF3021) 2.3e-09
268 | 23 Pfam PF01071.19 Phosphoribosylglycinamide synthetase, ATP-grasp (A) domain 2e-84
269 | 23 Pfam PF02843.16 Phosphoribosylglycinamide synthetase, C domain 3.8e-22
270 | 23 Pfam PF02844.15 Phosphoribosylglycinamide synthetase, N domain 6.4e-35
271 | 19 Pfam PF00206.20 Lyase 6.7e-74
272 | 13 Pfam PF04397.15 LytTr DNA-binding domain 3e-14
273 | 15 Pfam PF01624.20 MutS domain I 1.3e-47
274 | 15 Pfam PF05188.17 MutS domain II 1e-20
275 | 15 Pfam PF05192.18 MutS domain III 2.3e-47
276 | 15 Pfam PF05190.18 MutS family domain IV 1.9e-32
277 | 15 Pfam PF00488.21 MutS domain V 1.6e-84
278 | 21 Pfam PF17769.1 Phosphoribosylaminoimidazole carboxylase C-terminal domain 2.1e-20
279 | 18 Pfam PF00750.19 tRNA synthetases class I (R) 6.5e-103
280 | 47 Pfam PF13561.6 Enoyl-(Acyl carrier protein) reductase 1.2e-10
281 | 41 Pfam PF00006.25 ATP synthase alpha/beta family, nucleotide-binding domain 2.3e-24
282 | 39 Pfam PF01545.21 Cation efflux family 9e-51
283 | 36 Pfam PF00150.18 Cellulase (glycosyl hydrolase family 5) 1.1e-08
284 | 46 Pfam PF02554.14 Carbon starvation protein CstA 5.4e-132
285 | 46 Pfam PF13722.6 5TM C-terminal transporter carbon starvation CstA 9.5e-39
286 | 44 Pfam PF16403.5 Domain of unknown function (DUF5011) 4.4e-19
287 | 40 Pfam PF05913.11 Bacterial protein of unknown function (DUF871) 2e-106
288 | 36 Pfam PF00232.18 Glycosyl hydrolase family 1 2.8e-117
289 | 43 Pfam PF00126.27 Bacterial regulatory helix-turn-helix protein, lysR family 1.3e-25
290 | 43 Pfam PF03466.20 LysR substrate binding domain 1.1e-21
291 | 42 Pfam PF00149.28 Calcineurin-like phosphoesterase 9.5e-17
292 | 42 Pfam PF12850.7 Calcineurin-like phosphoesterase superfamily domain 5.5e-10
293 | 37 Pfam PF02811.19 PHP domain 3.5e-21
294 | 44 Pfam PF01522.21 Polysaccharide deacetylase 5.2e-32
295 | 41 Pfam PF07497.12 Rho termination factor, RNA-binding domain 3.6e-31
296 | 39 Pfam PF16916.5 Dimerisation domain of Zinc Transporter 1.1e-16
297 | 119 Pfam PF13086.6 AAA domain 4.9e-13
298 | 119 Pfam PF13245.6 AAA domain 8.2e-42
299 | 119 Pfam PF13604.6 AAA domain 1.9e-47
300 | 116 Pfam PF02353.20 Mycolic acid cyclopropane synthetase 2.3e-09
301 | 116 Pfam PF05219.12 DREV methyltransferase 1.5e-07
302 | 113 Pfam PF01996.16 F420-0:Gamma-glutamyl ligase 7.6e-83
303 | 115 Pfam PF02663.14 FmdE, Molybdenum formylmethanofuran dehydrogenase operon 2.3e-08
304 | 119 Pfam PF05127.14 Helicase 5.3e-11
305 | 110 Pfam PF12323.8 Helix-turn-helix domain 2.5e-23
306 | 118 Pfam PF00356.21 Bacterial regulatory proteins, lacI family 3.6e-15
307 | 116 Pfam PF08241.12 Methyltransferase domain 6.6e-14
308 | 116 Pfam PF08242.12 Methyltransferase domain 9.7e-14
309 | 116 Pfam PF13489.6 Methyltransferase domain 4.7e-12
310 | 116 Pfam PF13649.6 Methyltransferase domain 1.7e-18
311 | 116 Pfam PF13847.6 Methyltransferase domain 6e-23
312 | 116 Pfam PF02390.17 Putative methyltransferase 8.1e-09
313 | 116 Pfam PF05175.14 Methyltransferase small domain 9.7e-09
314 | 110 Pfam PF01385.19 Probable transposase 6.6e-17
315 | 110 Pfam PF07282.11 Putative transposase DNA-binding domain 1.4e-24
316 | 116 Pfam PF01135.19 Protein-L-isoaspartate(D-aspartate) O-methyltransferase (PCMT) 1e-08
317 | 118 Pfam PF13377.6 Periplasmic binding protein-like domain 2.1e-26
318 | 119 Pfam PF02562.16 PhoH-like protein 1.1e-07
319 | 119 Pfam PF05970.14 PIF1-like helicase 9.8e-12
320 | 116 Pfam PF06325.13 Ribosomal protein L11 methyltransferase (PrmA) 7.3e-08
321 | 114 Pfam PF00581.20 Rhodanese-like domain 1.4e-17
322 | 109 Pfam PF00572.18 Ribosomal protein L13 3.2e-61
323 | 108 Pfam PF00380.19 Ribosomal protein S9/S16 4.5e-51
324 | 119 Pfam PF18335.1 ATP-dependent RecD-like DNA helicase SH3 domain 1.1e-26
325 | 119 Pfam PF00437.20 Type II/IV secretion system protein 4.5e-09
326 | 116 Pfam PF03848.14 Tellurite resistance protein TehB 1e-09
327 | 116 Pfam PF05724.11 Thiopurine S-methyltransferase (TPMT) 6.3e-08
328 | 116 Pfam PF05958.11 tRNA (Uracil-5-)-methyltransferase 1e-08
329 | 116 Pfam PF01209.18 ubiE/COQ5 methyltransferase family 2.6e-08
330 | 119 Pfam PF13538.6 UvrD-like helicase C-terminal domain 2.9e-20
331 | 119 Pfam PF01443.18 Viral (Superfamily 1) RNA helicase 4.8e-18
332 | 111 Pfam PF01797.16 Transposase IS200 like 6.4e-43
333 | 24 Pfam PF05257.16 CHAP domain 6.1e-17
334 | 34 Pfam PF01207.17 Dihydrouridine synthase (Dus) 4.2e-12
335 | 33 Pfam PF01207.17 Dihydrouridine synthase (Dus) 2.3e-10
336 | 27 Pfam PF00208.21 Glutamate/Leucine/Phenylalanine/Valine dehydrogenase 9.7e-87
337 | 27 Pfam PF02812.18 Glu/Leu/Phe/Val dehydrogenase, dimerisation domain 2.7e-54
338 | 34 Pfam PF04309.12 Glycerol-3-phosphate responsive antiterminator 3.9e-08
339 | 32 Pfam PF00117.28 Glutamine amidotransferase class-I 1.2e-24
340 | 32 Pfam PF07685.14 CobB/CobQ-like glutamine amidotransferase domain 1.1e-10
341 | 29 Pfam PF01634.18 ATP phosphoribosyltransferase 6.4e-51
342 | 30 Pfam PF00815.20 Histidinol dehydrogenase 2.4e-173
343 | 34 Pfam PF00977.21 Histidine biosynthesis protein 4.7e-91
344 | 33 Pfam PF00977.21 Histidine biosynthesis protein 5.7e-80
345 | 31 Pfam PF00475.18 Imidazoleglycerol-phosphate dehydratase 5.2e-65
346 | 35 Pfam PF03819.17 MazG nucleotide pyrophosphohydrolase domain 3.2e-08
347 | 34 Pfam PF03060.15 Nitronate monooxygenase 4e-10
348 | 32 Pfam PF07722.13 Peptidase C26 9.8e-09
349 | 35 Pfam PF01502.18 Phosphoribosyl-AMP cyclohydrolase 3.4e-35
350 | 35 Pfam PF01503.17 Phosphoribosyl-ATP pyrophosphohydrolase 1.2e-19
351 | 32 Pfam PF01174.19 SNO glutamine amidotransferase family 3.4e-11
352 | 34 Pfam PF02581.17 Thiamine monophosphate synthase 3.3e-08
353 | 28 Pfam PF13393.6 Histidyl-tRNA synthetase 4e-62
354 | 71 Pfam PF02826.19 D-isomer specific 2-hydroxyacid dehydrogenase, NAD binding domain 1.5e-10
355 | 61 Pfam PF00155.21 Aminotransferase class I and II 8.9e-14
356 | 61 Pfam PF00266.19 Aminotransferase class-V 2.5e-08
357 | 61 Pfam PF01212.21 Beta-eliminating lyase 9.9e-15
358 | 68 Pfam PF06133.11 Control of competence regulator ComK, YlbF/YmcA 1.5e-16
359 | 66 Pfam PF01119.19 DNA mismatch repair protein, C-terminal domain 8.6e-41
360 | 71 Pfam PF16924.5 Dipicolinate synthase subunit A N-terminal domain 2.9e-24
361 | 66 Pfam PF02518.26 Histidine kinase-, DNA gyrase B-, and HSP90-like ATPase 5.2e-13
362 | 66 Pfam PF13589.6 Histidine kinase-, DNA gyrase B-, and HSP90-like ATPase 5.5e-17
363 | 70 Pfam PF14501.6 GHKL domain 3.6e-24
364 | 69 Pfam PF04397.15 LytTr DNA-binding domain 1.4e-19
365 | 66 Pfam PF08676.11 MutL C terminal dimerisation domain 3e-43
366 | 67 Pfam PF01624.20 MutS domain I 2.6e-42
367 | 67 Pfam PF05188.17 MutS domain II 5.6e-30
368 | 67 Pfam PF05192.18 MutS domain III 9.1e-46
369 | 67 Pfam PF05190.18 MutS family domain IV 2.8e-32
370 | 67 Pfam PF00488.21 MutS domain V 1.1e-91
371 | 69 Pfam PF00072.24 Response regulator receiver domain 1.7e-19
372 | 61 Pfam PF00464.19 Serine hydroxymethyltransferase 5.6e-179
373 | 64 Pfam PF02616.14 Segregation and condensation protein ScpA 1.5e-41
374 | 63 Pfam PF04079.16 Segregation and condensation complex subunit ScpB 3.5e-57
375 | 187 Pfam PF07275.11 Antirestriction protein (ArdA) 2.9e-42
376 | 194 Pfam PF02368.18 Bacterial Ig-like domain (group 2) 3.2e-10
377 | 192 Pfam PF02796.15 Helix-turn-helix domain of resolvase 1.8e-08
378 | 182 Pfam PF05713.11 Bacterial mobilisation protein (MobC) 2.6e-09
379 | 180 Pfam PF02195.18 ParB-like nuclease domain 1.8e-13
380 | 189 Pfam PF00589.22 Phage integrase family 1.6e-36
381 | 185 Pfam PF00589.22 Phage integrase family 3.1e-30
382 | 185 Pfam PF02899.17 Phage integrase, N-terminal SAM-like domain 6.3e-11
383 | 189 Pfam PF02899.17 Phage integrase, N-terminal SAM-like domain 7.6e-08
384 | 185 Pfam PF13495.6 Phage integrase, N-terminal SAM-like domain 4e-13
385 | 183 Pfam PF03432.14 Relaxase/Mobilisation nuclease domain 4.9e-49
386 | 192 Pfam PF00239.21 Resolvase, N terminal domain 9.2e-39
387 | 193 Pfam PF00239.21 Resolvase, N terminal domain 9.7e-24
388 |
--------------------------------------------------------------------------------
/test/test-contigs-scores.txt:
--------------------------------------------------------------------------------
1 | contig score
2 | AST0002_000000001053 2.3737687782754214e-08
3 | AST0002_000000001122 2.995346606467998e-07
4 | AST0002_000000001459 6.333592291893041e-06
5 | AST0002_000000001776 0.9592232672966521
6 | AST0002_000000003048 0.5622421419516015
7 | AST0002_000000006389 0.6089640039139832
8 | AST0002_000000006967 0.2730847890122725
9 | AST0002_000000007621 0.6630016070098446
10 | AST0002_000000008287 0.9848824181163179
11 | AST0002_000000008559 0.6922272061143715
12 | AST0002_000000009188 0.08677609423939228
13 | AST0002_000000009356 0.6017368745782006
14 | AST0002_000000009623 0.0005011547147176656
15 | AST0002_000000010497 0.8184493894843837
16 | AST0002_000000013910 0.2158264978382691
17 | AST0002_000000014102 0.3665903537154766
18 | AST0002_000000014415 0.8092365343525647
19 | AST0002_000000016511 0.63095854433962
20 | AST0002_000000017053 0.19178789564881102
21 | AST0002_000000019310 0.9816820974373326
22 | AST0002_000000019451 0.10176724105233066
23 | AST0002_000000021545 0.1584396615145509
24 | AST0002_000000021556 0.6156845801283908
25 | AST0002_000000022789 0.8754299733981479
26 | AST0002_000000022820 0.7887913422161553
27 | AST0002_000000025164 0.46724720324976454
28 | AST0002_000000026117 0.28805850711167974
29 | AST0002_000000026458 0.10109493045618598
30 | AST0002_000000026510 0.8460962866813632
31 | AST0002_000000026922 0.3754288678276302
32 | AST0002_000000026981 0.9991085539524566
33 | AST0002_000000027192 0.3693991119363712
34 | AST0002_000000027508 0.5793880001141013
35 | AST0002_000000028382 0.04262389369446989
36 | AST0002_000000030250 0.9111389709317061
37 | AST0002_000000030651 0.656089394122623
38 | AST0002_000000031660 0.26506229399295966
39 | AST0002_000000032592 0.06117738877636595
40 | AST0002_000000033911 0.4209535150696362
41 |
--------------------------------------------------------------------------------
/test/test-contigs.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/michaelkyu/PlasX/5c9acfd00a597da27ef5261acf72dbaf2117b645/test/test-contigs.db
--------------------------------------------------------------------------------