├── .github
└── workflows
│ └── ci.yml
├── .gitignore
├── LICENSE
├── README.md
├── environment.yml
├── pyproject.toml
├── src
└── scarap
│ ├── README.md
│ ├── __init__.py
│ ├── __main__.py
│ ├── callers.py
│ ├── checkers.py
│ ├── computers.py
│ ├── helpers.py
│ ├── module_wrappers.py
│ ├── modules.py
│ ├── pan.py
│ ├── readerswriters.py
│ └── utils.py
└── test
├── 01_pan.bats
├── 02_pan_hierarchical.bats
├── 03_build.bats
├── 04_search.bats
├── 05_check.bats
├── 06_concatenate.bats
├── 07_sample.bats
├── 08_core.bats
└── README.md
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 |
8 | strategy:
9 | matrix:
10 | python-version: ["3.7.1", "3.8.1", "3.10.1"]
11 |
12 | name: build-linux
13 | runs-on: ubuntu-20.04
14 | steps:
15 | - uses: actions/checkout@v3
16 | - name: Checkout test data
17 | uses: actions/checkout@v3
18 | with:
19 | repository: LebeerLab/SCARAP-testdata
20 | path: testdata
21 | - name: Set up Python
22 | uses: actions/setup-python@v3
23 | with:
24 | python-version: ${{ matrix.python-version }}
25 |
26 | - name: Setup BATS
27 | uses: mig4/setup-bats@v1
28 | with:
29 | bats-version: 1.2.1
30 | - uses: brokenpip3/setup-bats-libs@0.0.2
31 | with:
32 | support-path: ${{ github.workspace }}/test/test_helper/bats-support
33 | assert-path: ${{ github.workspace }}/test/test_helper/bats-assert
34 |
35 | - name: Add conda to system path
36 | run: |
37 | # $CONDA is an environment variable pointing to the root of the miniconda directory
38 | echo $CONDA/bin >> $GITHUB_PATH
39 | - name: Install dependencies
40 | run: |
41 | conda env update --file environment.yml --name base
42 | - name: Test with bats
43 | run: |
44 | bats -r .
45 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | data
2 | prev
3 | results
4 | src/tests
5 | src/scarap/__pycache__
6 | src/scarap/testfams
7 | src/scarap/tests
8 | build/
9 | dist/
10 | *egg-info/
11 | __pycache__
12 | bats/
13 | test_helper/
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SCARAP: pangenome inference and comparative genomics of prokaryotes
2 |
3 | SCARAP is a toolkit with modules for various tasks related to comparative genomics of prokaryotes. SCARAP has been designed to be fast and scalable. Its main feature is pangenome inference, but it also has modules for direct core genome inference (without inferring the full pangenome), subsampling representatives from a (large) set of genomes and constructing a concatenated core gene alignment ("supermatrix") that can later be used for phylogeny inference. SCARAP has been designed for prokaryotes but should work for eukaryotic genomes as well. It can handle large genome datasets on a range of taxonomic levels; it has been tested on datasets with prokaryotic genomes from the species to the order level.
4 |
5 |
6 |
7 |
8 |
9 | ## Installation
10 |
11 | The easiest way to get started is to install SCARAP using conda.
12 |
13 | ### Conda
14 |
15 | First, create and activate a new conda environment:
16 |
17 | conda create -n scarap python=3.11
18 | conda activate scarap
19 |
20 | Then install from the recipe on bioconda:
21 |
22 | conda install bioconda::scarap
23 |
24 |
25 | ### Pip
26 |
27 | First make sure that MAFFT and MMseqs2 are properly installed. Then install SCARAP with pip:
28 |
29 | pip install scarap
30 |
31 | ### Manual install
32 |
33 | You can also install SCARAP manually by cloning it and installing the following dependencies:
34 |
35 | * [Python3](https://www.python.org/) version >= 3.6.7 and < 3.13
36 | * Python packages:
37 | * [biopython](https://biopython.org/) version >= 1.67
38 | * [ete3](http://etetoolkit.org/) version >= 3.1.1
39 | * [numpy](https://numpy.org/) version >=1.16.5
40 | * [scipy](https://www.scipy.org/) version >= 1.4.1
41 | * [pandas](https://pandas.pydata.org/) version >= 1.5.3
42 | * [MAFFT](https://mafft.cbrc.jp/alignment/software/) version >= 7.407
43 | * [MMseqs2](https://github.com/soedinglab/MMseqs2) release 11, 12 or 13
44 |
45 | ## Quick start
46 |
47 | ### Obtaining data
48 |
49 | SCARAP works mainly with faa files: amino acid sequences of all (predicted) genes in a genome assembly. You can obtain faa files in at least three ways:
50 |
51 | * You can run a gene prediction tool like [Prodigal](https://github.com/hyattpd/Prodigal) on genome assemblies of your favorite strains, or a complete annotation pipeline such as [Prokka](https://github.com/tseemann/prokka) or [Bakta](https://github.com/oschwengers/bakta).
52 | * You can search your favorite taxon on [NCBI genome](https://www.ncbi.nlm.nih.gov/datasets/genome/) and manually download assemblies in the following way: click on an assembly, click "Download", select "Protein (FASTA)" as file type and click "Download" again.
53 | * Given a list of assembly accession numbers (i.e. starting with GCA/GCF), you can use [ncbi-genome-download](https://github.com/kblin/ncbi-genome-download/) to download the corresponding faa files.
54 |
55 | Given a list of accessions in a file called `accessions.txt`, you can use ncbi-genome-download to download faa files as follows:
56 |
57 | ncbi-genome-download -P \
58 | --assembly-accessions accessions.txt \
59 | --section genbank \
60 | --formats protein-fasta \
61 | bacteria
62 |
63 | ### Inferring a pangenome
64 |
65 | If you want to infer the pangenome of a set of genomes, you only need their faa files (fasta files with protein sequences) as input. If the faa files are stored in a folder `faas`, you can infer the pangenome using 16 threads by running:
66 |
67 | scarap pan ./faas ./pan -t 16
68 |
69 | The pangenome will be stored in `pan/pangenome.tsv`.
70 |
71 | The pangenome is stored in a "long format": a table with the columns gene, genome and orthogroup.
72 |
73 | ### Inferring a core genome
74 |
75 | If you want to infer the core genome of a set of genomes directly, without inferring the full pangenome first, you can also do this with SCARAP. The reason you might want to do this, is because it is faster and because you sometimes don't need more than the core genome (e.g. when you are planning to infer a phylogeny).
76 |
77 | You can infer the core genome, given a set of faa files in a folder `faas`, in the following way:
78 |
79 | scarap core ./faas ./core -t 16
80 |
81 | The core genome will be stored in `core/genes.tsv`.
82 |
83 | ### Subsampling a set of genomes
84 |
85 | If you have a (large) dataset of genomes that you wish to subsample in a representative way, you can do this using the `sample` module. You will need to precompute the pangenome or core genome to do this; SCARAP calculates average amino acid identity (AAI) or core amino acid identity (cAAI) values in the subsampling process, and it uses the single-copy orthogroups from a pan- or core genome to do this.
86 |
87 | For example, if you want to sample 100 genomes given a set of faa files in a folder `faas`:
88 |
89 | scarap core ./faas ./core -t 16
90 | scarap sample ./faas ./core/genes.tsv ./representatives -m 100 -t 16
91 |
92 | The representative genomes will be stored in `representatives/seeds.txt`.
93 |
94 | Important remark: by default, the per-gene amino acid identity values are estimated from alignment scores per column by MMseqs ([alignment mode 1](https://github.com/soedinglab/MMseqs2/wiki#how-does-mmseqs2-compute-the-sequence-identity)). For AAI values > 90%, these estimations are on average smaller than the exact values. It is possible to calculate exact AAI values by adding the `--exact` option to the sample module, but this will be slower.
95 |
96 | You can also sample genomes based on average nucleotide identity (ANI) or core nucleotide identity (cANI) values. In that case, you need to supply nucleotide sequences of predicted genes, e.g. in a folder `ffns`:
97 |
98 | scarap core ./faas ./core -t 16
99 | scarap sample ./ffns ./core/genes.tsv ./representatives -m 100 -t 16
100 |
101 | ### Building a "supermatrix" for a set of genomes
102 |
103 | You can build a concatenated alignment of core genes ("supermatrix") for a set of genomes using the `concat` module.
104 |
105 | Let's say you want to build a supermatrix of 100 core genes for a set of genomes, with faa files given in a folder `faas`:
106 |
107 | scarap core ./faas ./core -m 100 -t 16
108 | scarap concat ./faas ./core/genes.tsv ./supermatrix -t 16
109 |
110 | The amino acid supermatrix will be saved in `supermatrix/supermatrix_aas.fasta`.
111 |
112 | If you want to produce a nucleotide-level supermatrix, this can be achieved by giving a folder with ffn files (nucleotide sequences of predicted genes) as an additional argument:
113 |
114 | scarap concat ./faas ./core/genes.tsv ./supermatrix -n ./ffns -t 16
115 |
116 | The nucleotide-level supermatrix will be saved in `supermatrix/supermatrix_nucs.fasta`.
117 |
118 | ## Modules
119 |
120 | SCARAP is able to perform a number of specific tasks related to prokaryotic comparative genomics (see also `scarap -h`).
121 |
122 | The most useful modules of SCARAP are probably the following:
123 |
124 | * `pan`: infer a pangenome from a set of faa files
125 | * `core`: infer a core genome from a set of faa files
126 | * `sample`: sample a subset of representative genomes
127 |
128 | Modules for other useful tasks are also available:
129 |
130 | * `build`: build a profile database for a core/pangenome
131 | * `search`: search query genes in a profile database
132 | * `checkgenomes`: assess the genomes in a core genome
133 | * `checkgroups`: assess the orthogroups in a core genome
134 | * `filter`: filter the genomes/orthogroups in a pangenome
135 | * `concat`: construct a concatenated core orthogroup alignment from a core genome
136 | * `fetch`: fetch sequences and store in fasta per orthogroup
137 |
138 | ## License
139 |
140 | SCARAP is free software, licensed under [GPLv3](https://github.com/SWittouck/scarap/blob/master/LICENSE).
141 |
142 | ## Feedback
143 |
144 | All feedback and suggestions very welcome at stijn.wittouck[at]uantwerpen.be. You are of course also welcome to file [issues](https://github.com/SWittouck/scarap/issues).
145 |
146 | ## Citation
147 |
148 | If you've found SCARAP useful in your own work, please cite the following manuscript:
149 |
150 | Wittouck et al. (2025) "SCARAP: scalable cross-species comparative genomics of prokaryotes", Bioinformatics, Volume 41, Issue 1, January 2025, btae735, https://doi.org/10.1093/bioinformatics/btae735
151 |
--------------------------------------------------------------------------------
/environment.yml:
--------------------------------------------------------------------------------
1 | # this file is used by the GitHub actions tests
2 | name: scarap
3 | dependencies:
4 | - bioconda::mafft
5 | - bioconda::mmseqs2
6 | - python>=3.6.7,<3.13
7 | - pip
8 | - pip:
9 | - .
10 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools", "setuptools-scm"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "scarap"
7 | version = "1.0.0"
8 | authors = [
9 | { name = "Stijn Wittouck", email = "stijn.wittouck@uantwerpen.be" }
10 | ]
11 | maintainers = [
12 | { name = "Stijn Wittouck", email = "stijn.wittouck@uantwerpen.be" },
13 | { name = "Tim Van Rillaer", email = "tim.vanrillaer@uantwerpen.be" }
14 | ]
15 | description = "A toolkit for prokaryotic comparative genomics"
16 | readme = "README.md"
17 | requires-python = ">=3.6.7,<3.13"
18 | classifiers = [
19 | "Programming Language :: Python :: 3",
20 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
21 | "Operating System :: OS Independent"
22 | ]
23 | dependencies = [
24 | "wheel",
25 | "biopython>=1.67",
26 | "ete3>=3.1.1",
27 | "numpy>=1.16.5",
28 | "scipy>=1.4.1",
29 | "pandas"
30 | ]
31 |
32 | [project.urls]
33 | Homepage = "https://github.com/SWittouck/SCARAP"
34 | Issues = "https://github.com/SWittouck/SCARAP/issues"
35 |
36 | [project.scripts]
37 | scarap = "scarap.__main__:main"
38 |
39 | [tools.setuptools.packages.find]
40 | where = "src"
41 |
42 | [tool.pytest.ini_options]
43 | addopts = "--import-mode=importlib"
44 | pythonpath = "src"
45 |
--------------------------------------------------------------------------------
/src/scarap/README.md:
--------------------------------------------------------------------------------
1 | # Architecture of scripts and functions
2 |
3 | ## Script architecture
4 |
5 | Remark: all scripts import utils
6 |
7 | * __main__.py:
8 | * commandline interface
9 | * imports module_wrappers
10 | * module_wrappers.py:
11 | * wrappers for all tasks that check commandline arguments and dependencies
12 | * imports modules, checkers
13 | * checkers.py:
14 | * functions that check commandline arguments and dependencies
15 | * modules.py:
16 | * top-level code for all modules
17 | * imports helpers, readerswriters, computers, callers, pan
18 | * helpers.py:
19 | * helper functions for non-pan modules
20 | * imports readerswriters, computers, callers
21 | * pan.py
22 | * code for the various builtin pangenome inference methods
23 | * imports readerswriters, computers, callers
24 | * computers.py:
25 | * functions that perform more complex computations
26 | * readerswriters.py:
27 | * functions that perform simple reading/writing operations
28 | * callers.py:
29 | * functions that call other software (e.g. hmmer tasks, mmseqs2 tasks, mafft)
30 | * utils.py:
31 | * simple utility functions that are used by multiple scripts
32 |
33 | ## Architecture of pan.py
34 |
35 | The script pan.py implements various pangenome inference strategies. Its functions are structured as follows:
36 |
37 | * The top-level pangenome inference function is **infer_pangeome**. Its main arguments are a list of faa files and the pangenome inference strategy. It calls the function infer_superfamilies and then applies the function split_superfamily to all superfamilies in parallel.
38 | * The function **split_superfamily** initializes the necessary data structures depending on the requested strategy and calls a strategy-specific function with the name split_family_recursive_STR (where STR is the strategy name, e.g. split_family_recursive_LHT).
39 | * The **split_family_recursive_STR** function will split a superfamily in the set of final families, by splitting the family into two subfamilies recursively. Per recursion iteration, it goes through the following steps:
40 | 1) it checks wether splitting if even an option (e.g. families with only one or two genes aren't splittable)
41 | 2) it calls a strategy-specific splitting function to perform the actual split of the family into two subfamilies
42 | 3) it checks if the split should actually happen based on the genome content of the subfamilies
43 | 4) if the split should happen, it finishes the split and calls itself on the subfamilies to start the next iterations
44 | * The functions that perform the actual split of a family into two subfamilies are called **split_family_STR**, where STR is again the name of the strategy.
45 |
46 | Some remarks about the implementation of the various strategies:
47 |
48 | * The pangenome table ("pan" variable) is always passed to the recursive functions as a table that is indexed on the gene column. This makes it faster (I think) to subset it by genes, which is an operation that is frequently needed.
49 | * For consistency, all splitting functions (split_family_STR) return [pan1, pan2]. For some of them, it would be possible to just return [genes1, genes2], which would be simpeler and maybe even a bit faster (because the pan table technically only needs to be split if the splitting criterion tells us that the split will go through). However, I currently prefer to pay that small speed price to retain code consistency.
50 |
51 | ## Family splitting strategies in pan.py
52 |
53 | Four family splitting modules have been implemented in pan.py that can be combined to form a family splitting strategy:
54 |
55 | * linclust (L): fixed-threshold clustering in linear time (mmseqs linclust)
56 | * ficlin (F): clustering in a fixed number of clusters in linear time (own implementation using mmseqs align)
57 | * hclust (H): multiple sequence alignment (MAFFT) followed by hierarchical clustering (scipy.cluster.hierarchy)
58 | * tree (T): multiple sequence alignment (MAFFT) followed by phylogeny inference (IQTREE)
59 |
60 | Three of the modules can be used to propose a binary split of a gene family: F, H and T; at least one of them needs to be part of the strategy. Three modules can be used to select representative sequences for the next module: L, F and H. Taking representatives can speed up the process and/or make it more scalable. An example of a strategy would be FH: selection of a fixed number of clusters by ficlin followed by hierarchical clustering of the representatives to determine the binary split of the family.
61 |
62 | By default, all strategies are lazy: they will attempt to re-use information from the parent, such as an hclust object or tree (however, for some strategies this is impossible). We indicate a non-lazy variant of a strategy with the suffix "-nl", e.g. H-nl (compute the full MSA and hierarchical clustering for each split).
63 |
--------------------------------------------------------------------------------
/src/scarap/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SWittouck/SCARAP/54b690a8ef15948d91a41eb8ac3f87bf2ac265db/src/scarap/__init__.py
--------------------------------------------------------------------------------
/src/scarap/__main__.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python3
2 |
3 | # This is the main script of SCARAP; it only contains the commandline
4 | # interface.
5 |
6 | __author__ = "Stijn Wittouck"
7 | __version__ = "1.0.0"
8 |
9 | import argparse
10 | import logging
11 | import sys
12 |
13 | from scarap.utils import *
14 | from scarap.module_wrappers import *
15 |
16 | def print_help():
17 |
18 | message = '''\
19 | VERSION
20 | {0}
21 | AUTHORS
22 | Stijn Wittouck (development)
23 | Sarah Lebeer (PI)
24 | Vera van Noort (PI)
25 | USAGE
26 | scarap [-h]
27 | MODULES
28 | pan --> infer a pangenome from a set of faa files
29 | core --> infer a core genome from a set of faa files
30 | build --> build a profile database for a core/pangenome
31 | search --> search query genes in a profile database
32 | checkgenomes --> assess the genomes in a core genome
33 | checkgroups --> assess the orthogroups in a core genome
34 | filter --> filter the genomes/orthogroups in a pangenome
35 | concat --> construct a concatenated core orthogroup alignment from a
36 | core genome
37 | sample --> sample a subset of representative genomes
38 | fetch --> fetch sequences and store in fasta per orthogroup
39 | DOCUMENTATION
40 | https://github.com/swittouck/scarap\
41 | '''
42 |
43 | print(message.format(__version__))
44 |
45 | def print_intro():
46 |
47 | message = '''\
48 |
49 | This is SCARAP version {0}
50 | '''
51 |
52 | print(message.format(__version__))
53 |
54 | def parse_arguments():
55 |
56 | parser = argparse.ArgumentParser(
57 | add_help = False
58 | )
59 |
60 | parser.add_argument("-h", "--help", action = 'store_true')
61 |
62 | subparsers = parser.add_subparsers()
63 |
64 | # help messages for positional arguments (alphabetically)
65 | h_coregenome = "input file with a core genome"
66 | h_db = "input database containing alignments and profile score cutoffs"
67 | h_faa_files = "folder with one fasta file with amino acid sequences (faa "\
68 | "file) per genome, or file with paths to faa files"
69 | h_fasta_files = "folder with one fasta file with amino acid sequences "\
70 | "(faa file) or one fasta file with nucleic acid sequences (ffn file) "\
71 | "per genome, or a file with paths to faa/ffn files"
72 | h_outfolder = "output folder"
73 | h_pangenome = "input file with pangenome"
74 |
75 | # help messages for "optional" arguments (alphabetically)
76 | h_core_prefilter = "minimum relative frequency of single-copy presence to "\
77 | "be used for initial database construction"
78 | h_cont = "continue in existing output folder [default False]"
79 | h_core_filter = "minimum relative frequency of single-copy presence to be "\
80 | " used for"
81 | h_exact = "perform full alignments [default False]"
82 | h_ffn_files = "file with paths to or folder with ffn files of genomes; if "\
83 | "given, a nucleotide supermatrix will be constructed in addition "\
84 | "to the amino acid suprmatrix"
85 | h_genomes = "input file with genomes to extract from pangenome"
86 | h_identity = "maximum sequence identity between sampled genomes [default 1]"
87 | h_max_align = "maximum number of sequences to use for multiple sequence "\
88 | "alignment [default MAX_REPS * 16]"
89 | h_max_core_genes = "maximum number of core genes to retrieve (0 = no "\
90 | "maximum) [default 0]"
91 | h_max_genomes = "maximum number of genomes to sample (0 = no maximum) "\
92 | "[default 0]"
93 | h_max_reps = "maximum number of representative sequences to use for "\
94 | "multiple sequence alignment [default MIN_REPS * 1.25]"
95 | h_method = "pangenome inference method [default: FH]"
96 | h_method_sample = "genome-genome comparison method [default: mean]"
97 | h_min_reps = "minimum number of representative sequences to use for "\
98 | "multiple sequence alignment [default 32]"
99 | h_orthogroups = "input file with orthogroups to extract from pangenome"
100 | h_seeds = "number of seed genomes to use [default 100]"
101 | h_species = "input file with species of genomes; if given, a hierarchical "\
102 | "pangenome strategy will be used for final database selection"
103 | h_threads = "number of threads to use"
104 |
105 | # other interface components
106 | method_choices = ["H", "FH", "FT", "H-nl", "T-nl", "P", "O-B", "O-D", "S"]
107 |
108 | parser_pan = subparsers.add_parser('pan')
109 | parser_pan.set_defaults(func = run_pan_withchecks)
110 | parser_pan.add_argument("faa_files", metavar = "faa-files",
111 | help = h_faa_files)
112 | parser_pan.add_argument("outfolder", help = h_outfolder)
113 | parser_pan.add_argument("-d", "--method", default = "FH",
114 | choices = method_choices, help = h_method)
115 | parser_pan.add_argument("-i", "--min-reps", default = 32, type = int,
116 | help = h_min_reps)
117 | parser_pan.add_argument("-a", "--max-reps", default = 0, type = int,
118 | help = h_max_reps)
119 | parser_pan.add_argument("-x", "--max-align", default = 0, type = int,
120 | help = h_max_align)
121 | parser_pan.add_argument("-s", "--species", help = h_species)
122 | parser_pan.add_argument("-t", "--threads", default = 8, type = int,
123 | help = h_threads)
124 | parser_pan.add_argument("-c", "--cont", action = "store_true",
125 | help = h_cont)
126 |
127 | parser_core = subparsers.add_parser('core')
128 | parser_core.set_defaults(func = run_core_withchecks)
129 | parser_core.add_argument("faa_files", metavar = "faa-files",
130 | help = h_faa_files)
131 | parser_core.add_argument("outfolder", help = h_outfolder)
132 | parser_core.add_argument("-d", "--method", default = "FH",
133 | choices = method_choices, help = h_method)
134 | parser_core.add_argument("-i", "--min-reps", default = 32, type = int,
135 | help = h_min_reps)
136 | parser_core.add_argument("-a", "--max-reps", default = 0, type = int,
137 | help = h_max_reps)
138 | parser_core.add_argument("-x", "--max-align", default = 0, type = int,
139 | help = h_max_align)
140 | parser_core.add_argument("-e", "--seeds", default = 100, type = int,
141 | help = h_seeds)
142 | parser_core.add_argument("-p", "--core-prefilter", default = 0.90,
143 | type = float, help = h_core_prefilter + " [default 0.90]")
144 | parser_core.add_argument("-f", "--core-filter", default = 0.95,
145 | type = float, help = h_core_filter + " [default 0.95]")
146 | parser_core.add_argument("-m", "--max-core-genes", default = 0,
147 | type = int, help = h_max_core_genes)
148 | parser_core.add_argument("-t", "--threads", default = 8,
149 | type = int, help = h_threads)
150 | parser_core.add_argument("-c", "--cont", action = "store_true",
151 | help = h_cont)
152 |
153 | parser_build = subparsers.add_parser('build')
154 | parser_build.set_defaults(func = run_build_withchecks)
155 | parser_build.add_argument("faa_files", metavar = "faa-files",
156 | help = h_faa_files)
157 | parser_build.add_argument("pangenome", help = h_pangenome)
158 | parser_build.add_argument("outfolder", help = h_outfolder)
159 | parser_build.add_argument("-p", "--core-prefilter", default = 0,
160 | type = float, help = h_core_prefilter + " [default 0]")
161 | parser_build.add_argument("-f", "--core-filter", default = 0,
162 | type = float, help = h_core_filter + " [default 0]")
163 | parser_build.add_argument("-m", "--max-core-genes", default = 0,
164 | type = int, help = h_max_core_genes)
165 | parser_build.add_argument("-t", "--threads", default = 8,
166 | type = int, help = h_threads)
167 | parser_build.add_argument("-c", "--cont", action = "store_true",
168 | help = h_cont)
169 |
170 | parser_search = subparsers.add_parser('search')
171 | parser_search.set_defaults(func = run_search_withchecks)
172 | parser_search.add_argument("faa_files", metavar = "faa-files",
173 | help = h_faa_files)
174 | parser_search.add_argument("db", help = h_db)
175 | parser_search.add_argument("outfolder", help = h_outfolder)
176 | parser_search.add_argument("-t", "--threads", default = 8,
177 | type = int, help = h_threads)
178 | parser_search.add_argument("-c", "--cont", action = "store_true",
179 | help = h_cont)
180 |
181 | parser_concat = subparsers.add_parser('concat')
182 | parser_concat.set_defaults(func = run_concat_withchecks)
183 | parser_concat.add_argument("faa_files", metavar = "faa-files",
184 | help = h_faa_files)
185 | parser_concat.add_argument("pangenome", help = h_pangenome)
186 | parser_concat.add_argument("outfolder", help = h_outfolder)
187 | parser_concat.add_argument("-f", "--core-filter", default = 0,
188 | type = float, help = h_core_filter + " [default 0]")
189 | parser_concat.add_argument("-m", "--max-core-genes", default = 0,
190 | type = int, help = h_max_core_genes)
191 | parser_concat.add_argument("-n", "--ffn-files", help = h_ffn_files)
192 | parser_concat.add_argument("-t", "--threads", default = 8,
193 | type = int, help = h_threads)
194 | parser_concat.add_argument("-c", "--cont", action = "store_true",
195 | help = h_cont)
196 |
197 | parser_sample = subparsers.add_parser('sample')
198 | parser_sample.set_defaults(func = run_sample_withchecks)
199 | parser_sample.add_argument("fasta_files", metavar = "fasta-files",
200 | help = h_fasta_files)
201 | parser_sample.add_argument("pangenome", help = h_pangenome)
202 | parser_sample.add_argument("outfolder", help = h_outfolder)
203 | parser_sample.add_argument("-m", "--max-genomes", default = 0, type = int,
204 | help = h_max_genomes)
205 | parser_sample.add_argument("-i", "--identity", default = 1, type = float,
206 | help = h_identity)
207 | parser_sample.add_argument("-d", "--method", default = "mean",
208 | help = h_method_sample)
209 | parser_sample.add_argument("-x", "--exact", action = "store_true",
210 | help = h_exact)
211 | parser_sample.add_argument("-t", "--threads", default = 8,
212 | type = int, help = h_threads)
213 | parser_sample.add_argument("-c", "--cont", action = "store_true",
214 | help = h_cont)
215 |
216 | parser_checkgenomes = subparsers.add_parser("checkgenomes")
217 | parser_checkgenomes.set_defaults(func = run_checkgenomes_withchecks)
218 | parser_checkgenomes.add_argument("coregenome", help = h_coregenome)
219 | parser_checkgenomes.add_argument("outfolder", help = h_outfolder)
220 | parser_checkgenomes.add_argument("-c", "--cont", action = "store_true",
221 | help = h_cont)
222 |
223 | parser_checkgroups = subparsers.add_parser("checkgroups")
224 | parser_checkgroups.set_defaults(func = run_checkgroups_withchecks)
225 | parser_checkgroups.add_argument("coregenome", help = h_coregenome)
226 | parser_checkgroups.add_argument("outfolder", help = h_outfolder)
227 | parser_checkgroups.add_argument("-c", "--cont", action = "store_true",
228 | help = h_cont)
229 |
230 | parser_filter = subparsers.add_parser('filter')
231 | parser_filter.set_defaults(func = run_filter_withchecks)
232 | parser_filter.add_argument("pangenome", help = h_pangenome)
233 | parser_filter.add_argument("outfolder", help = h_outfolder)
234 | parser_filter.add_argument("-g", "--genomes", help = h_genomes)
235 | parser_filter.add_argument("-o", "--orthogroups", help = h_orthogroups)
236 | parser_filter.add_argument("-c", "--cont", action = "store_true",
237 | help = h_cont)
238 |
239 | parser_fetch = subparsers.add_parser('fetch')
240 | parser_fetch.set_defaults(func = run_fetch_withchecks)
241 | parser_fetch.add_argument("fasta_files", metavar = "fasta-files",
242 | help = h_fasta_files)
243 | parser_fetch.add_argument("pangenome", help = h_pangenome)
244 | parser_fetch.add_argument("outfolder", help = h_outfolder)
245 | parser_fetch.add_argument("-c", "--cont", action = "store_true",
246 | help = h_cont)
247 |
248 | args = parser.parse_args()
249 |
250 | return(args)
251 |
252 | def main():
253 | args = parse_arguments()
254 |
255 | if not "func" in args:
256 | print_help()
257 | sys.exit()
258 |
259 | print_intro()
260 |
261 | logging.basicConfig(
262 | level = logging.INFO,
263 | format = '[%(asctime)s] %(levelname)s: %(message)s',
264 | datefmt = '%d/%m %H:%M:%S'
265 | )
266 | logging.info("welcome to SCARAP")
267 |
268 | if "cont" in args and args.cont and os.path.exists(args.outfolder):
269 | logging.info("continuing in existing output folder")
270 | check_outfile(os.path.join(args.outfolder, "SCARAP.log"))
271 | else:
272 | logging.info("creating output folder and log file")
273 | check_outdir(args.outfolder)
274 | os.makedirs(args.outfolder, exist_ok = True)
275 | logging.info(f"output folder '{args.outfolder}' created")
276 |
277 | handler = logging.FileHandler(
278 | filename = os.path.join(args.outfolder, "SCARAP.log"),
279 | mode = 'w'
280 | )
281 | handler.setFormatter(logging.getLogger().handlers[0].formatter)
282 | logging.getLogger().addHandler(handler)
283 | logging.info("log file created!")
284 |
285 | args.func(args)
286 |
287 | logging.info("SCARAP out")
288 |
289 | if __name__ == "__main__":
290 | main()
291 |
--------------------------------------------------------------------------------
/src/scarap/callers.py:
--------------------------------------------------------------------------------
1 | import concurrent.futures
2 | import logging
3 | import os
4 | import shutil
5 | import subprocess
6 | import sys
7 |
8 | from pathlib import Path
9 |
10 | from scarap.utils import *
11 |
12 | def run_iqtree(fin_aln, dout_tree, threads, options):
13 | makedirs_smart(dout_tree)
14 | result = subprocess.call(["iqtree", "-s", fin_aln,
15 | "-pre", f"{dout_tree}/tree", "-nt", str(threads)] + options,
16 | stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL)
17 | if result != 0:
18 | logging.error("something went wrong with iqtree; see log file "
19 | f"{dout_tree}/tree.log")
20 | sys.exit(1)
21 |
22 | def run_mmseqs(arguments, logfout, skip_if_exists = "", threads = 1):
23 | if skip_if_exists != "":
24 | if os.path.exists(skip_if_exists):
25 | if os.path.getsize(skip_if_exists) > 0:
26 | logging.info("existing output detected - moving on")
27 | return()
28 | args = ["mmseqs"] + arguments
29 | if not arguments[0] in ["createdb", "convertmsa", "tsv2db"]:
30 | args = args + ["--threads", str(threads)]
31 | with open(logfout, "w") as loghout:
32 | result = subprocess.call(args, stdout = loghout, stderr = loghout)
33 | if result != 0:
34 | logging.error("something went wrong with mmseqs; see log file "
35 | f"{logfout}")
36 | sys.exit(1)
37 |
38 | def run_orthofinder(faafins, dout, logfout, threads, engine = "blast"):
39 | for faafin in faafins:
40 | faaname = os.path.basename(faafin)
41 | shutil.copyfile(faafin, os.path.join(dout, faaname))
42 | with open(logfout, 'w') as loghout:
43 | with open(os.devnull, 'w') as devnull:
44 | result = subprocess.call(["orthofinder", "-og", "-S", engine, "-t",
45 | str(threads), "-f", dout], stdout = loghout, stderr = loghout)
46 | if result != 0:
47 | logging.error("something went wrong with orthofinder; see log file "
48 | "'orthofinder.log'")
49 | sys.exit(1)
50 |
51 | def run_mafft(fin_seqs, fout_aln, threads = 1, options = [], retry=False):
52 | args = ["mafft"] + options + ["--thread", str(threads), fin_seqs]
53 | with open(fout_aln, "w") as hout_aln:
54 | result = subprocess.run(args, stdout = hout_aln,
55 | stderr = subprocess.PIPE)
56 | if result.returncode == 0: return()
57 | if not retry and result.stderr.splitlines()[-1][0:17] == b"Illegal character":
58 | og = filename_from_path(fin_seqs)
59 | logging.warning(f"added --amino and --anysymbol flags to mafft for {og}")
60 | options = options + ["--amino", "--anysymbol"]
61 | run_mafft(fin_seqs, fout_aln, threads, options, retry=True)
62 |
63 | def run_mafft_parallel(fins_aa_seqs, fouts_aa_seqs_aligned):
64 | with concurrent.futures.ProcessPoolExecutor() as executor:
65 | executor.map(run_mafft, fins_aa_seqs, fouts_aa_seqs_aligned)
66 |
67 | def run_hmmbuild(fin_aa_seqs_aligned, fout_hmm):
68 | logging.debug(f"building profile for {Path(fin_aa_seqs_aligned).stem}")
69 | subprocess.run(["hmmbuild", fout_hmm, fin_aa_seqs_aligned],
70 | stdout = subprocess.PIPE)
71 |
72 | def run_hmmbuild_parallel(fins_aa_seqs_aligned, fouts_hmms):
73 | with concurrent.futures.ProcessPoolExecutor() as executor:
74 | executor.map(run_hmmbuild,fins_aa_seqs_aligned, fouts_hmms)
75 |
76 | def run_hmmpress(fins_hmms, dout_hmm_db):
77 | fout_hmm_db = dout_hmm_db + "/hmm_db"
78 | with open(fout_hmm_db, 'w') as hout_hmm_db:
79 | for fin_hmm in fins_hmms:
80 | with open(fin_hmm) as hin_hmm:
81 | hout_hmm_db.write(hin_hmm.read())
82 | subprocess.run(["hmmpress", fout_hmm_db], stdout = subprocess.PIPE)
83 | subprocess.run(["rm", fout_hmm_db])
84 |
85 | def run_hmmsearch(din_hmm_db, fins_genomes, fout_domtbl, threads = 1):
86 | fin_hmm_db = os.path.join(din_hmm_db, "hmm_db")
87 | fout_temp_genomes = din_hmm_db + "/genomes.temp"
88 | with open(fout_temp_genomes, 'w') as hout_temp_genomes:
89 | for fin_genome in fins_genomes:
90 | with open_smart(fin_genome) as hin_genome:
91 | hout_temp_genomes.write(hin_genome.read())
92 | subprocess.run(["hmmsearch", "-o", "/dev/null", "--domtblout", fout_domtbl,
93 | "--cpu", str(threads), fin_hmm_db, fout_temp_genomes])
94 | subprocess.run(["rm", fout_temp_genomes])
95 |
96 | def run_hmmscan(din_hmm_db, fins_genomes, fout_domtbl, threads = 1):
97 | fin_hmm_db = os.path.join(din_hmm_db, "hmm_db")
98 | fout_temp_genomes = din_hmm_db + "/genomes.temp"
99 | with open(fout_temp_genomes, 'w') as hout_temp_genomes:
100 | for fin_genome in fins_genomes:
101 | with open_smart(fin_genome) as hin_genome:
102 | hout_temp_genomes.write(hin_genome.read())
103 | subprocess.run(["hmmscan", "-o", "/dev/null", "--domtblout", fout_domtbl,
104 | "--cpu", str(threads), fin_hmm_db, fout_temp_genomes])
105 | subprocess.run(["rm", fout_temp_genomes])
106 |
--------------------------------------------------------------------------------
/src/scarap/checkers.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import re
4 | import subprocess
5 | import sys
6 | from collections import Counter
7 |
8 | from Bio import SeqIO
9 | from pathlib import Path
10 | from scarap.utils import *
11 |
12 | def check_tool(tool, arguments = []):
13 | devnull = open(os.devnull, 'w')
14 | try:
15 | subprocess.call([tool] + arguments, stdout = devnull, stderr = devnull)
16 | except FileNotFoundError:
17 | logging.error(f"{tool} not found")
18 | sys.exit(1)
19 | logging.info(f"{tool} found")
20 |
21 | def check_mafft():
22 | try:
23 | res = subprocess.run(["mafft", "--version"], stderr = subprocess.PIPE)
24 | except FileNotFoundError:
25 | logging.error(f"MAFFT not found")
26 | sys.exit(1)
27 | r = re.compile("[0-9]+\\.[0-9]+")
28 | version = r.search(res.stderr.decode()).group()
29 | logging.info(f"detected MAFFT v{version}")
30 | if float(version) < 7.310:
31 | logging.warning("SCARAP has been tested with MAFFT v7.310 or newer")
32 |
33 | def check_mmseqs():
34 | try:
35 | res = subprocess.run(["mmseqs", "-h"], stdout = subprocess.PIPE)
36 | except FileNotFoundError:
37 | logging.error(f"MMseqs2 not found")
38 | sys.exit(1)
39 | r = re.compile("MMseqs2 Version: ([a-f0-9.]{5})")
40 | try:
41 | version = r.search(res.stdout.decode()).group(1)
42 | except AttributeError:
43 | version = "unknown"
44 | releases_tested = {"e1a1c": "11", "113e3": "12", "45111": "13"}
45 | if version.split(".")[0] in releases_tested.values():
46 | # new version shows human readable version
47 | release = version.split(".")[0]
48 | else:
49 | # Old version showed the first 5 characters of the commit sha for the version
50 | release = releases_tested.get(version, "unknown")
51 | logging.info(f"detected MMseqs2 version {version} (release {release})")
52 | if not release in releases_tested.values():
53 | logging.warning("SCARAP has only been tested with MMseqs2 "
54 | "releases 11, 12 and 13")
55 |
56 | def check_infile(infile):
57 | if not os.path.isfile(infile):
58 | logging.error(f"input file '{infile}' not found")
59 | sys.exit(1)
60 |
61 | def check_outfile(outfile):
62 | if not os.path.isfile(outfile):
63 | return()
64 | i = 0
65 | outfile_prev = outfile + f".prev{i}"
66 | while os.path.isfile(outfile_prev):
67 | i = i + 1
68 | outfile_prev = outfile + f".prev{i}"
69 | logging.info(f"output file '{outfile}' already exists; moving it to "
70 | f"'{outfile_prev}'")
71 | os.rename(outfile, outfile_prev)
72 |
73 | def check_outdir(outdir, move_existing = True):
74 | if not os.path.exists(outdir):
75 | return()
76 | elif move_existing:
77 | i = 0
78 | outdir_prev = outdir + f".prev{i}"
79 | while os.path.exists(outdir_prev):
80 | i = i + 1
81 | outdir_prev = outdir + f".prev{i}"
82 | logging.info(f"output folder '{outdir}' already exists; moving it to "
83 | f"'{outdir_prev}'")
84 | os.rename(outdir, outdir_prev)
85 | else:
86 | logging.info(f"output folder '{outdir}' already exists")
87 | sys.exit(1)
88 |
89 | def check_fasta(path):
90 | if not os.path.isfile(path):
91 | logging.error("one or more fasta files not found")
92 | sys.exit(1)
93 | with open_smart(path) as handle:
94 | try:
95 | fasta = SeqIO.parse(handle, "fasta")
96 | if not any(fasta):
97 | raise Exception()
98 | except Exception:
99 | logging.error(f"file {path} is not in fasta format")
100 | sys.exit(1)
101 |
102 | # works for dir with fastas or file with fastapaths
103 | def check_fastas(path):
104 | # when path is a file
105 | if os.path.isfile(path):
106 | # error if file with fastapaths is empty
107 | if os.stat(path).st_size == 0:
108 | logging.error("fastapaths file is empty")
109 | sys.exit(1)
110 | # store fastapaths in list
111 | fastapaths = [fp.strip() for fp in open(path)]
112 | # error if fasta filenames not unique
113 | filenames = [filename_from_path(fp) for fp in fastapaths]
114 | if not len(filenames) == len(set(filenames)):
115 | # Check for the culprit
116 | offenders = [x for x,c in Counter(filenames).items() if c > 1]
117 | logging.error(f"names of fasta files are not unique. Offending values are: {offenders}")
118 | sys.exit(1)
119 | # when path is a folder
120 | elif os.path.isdir(path):
121 | # store fastapaths in list
122 | fastapaths = [os.path.join(path, file) for file in os.listdir(path)]
123 | fastapaths = [fp for fp in fastapaths if os.path.isfile(fp)]
124 | extensions = ("fasta", "fa", "faa", "ffn", "fasta.gz", "fa.gz",
125 | "faa.gz", "ffn.gz")
126 | fastapaths = [fp for fp in fastapaths if fp.endswith(extensions)]
127 | if len(fastapaths) == 0:
128 | logging.error(f"No fasta files found in {path}")
129 | sys.exit(1)
130 | # error when path doesn't exist
131 | else:
132 | logging.error(f"input file/folder '{path}' not found")
133 | sys.exit(1)
134 | # check individual fasta files
135 | for fastapath in fastapaths:
136 | check_fasta(fastapath)
137 |
138 | def check_db(path):
139 | din_alis = os.path.join(path, "alignments")
140 | fin_cutoffs = os.path.join(path, "cutoffs.csv")
141 | if not os.path.isdir(din_alis):
142 | logging.error("no folder with alignments found")
143 | sys.exit(1)
144 | if not os.path.isfile(fin_cutoffs):
145 | logging.error("no file with score cutoffs found")
146 | sys.exit(1)
147 |
--------------------------------------------------------------------------------
/src/scarap/computers.py:
--------------------------------------------------------------------------------
1 | import concurrent.futures
2 | import logging
3 | import numpy as np
4 | import os
5 | import pandas as pd
6 |
7 | from Bio import SeqIO, SeqRecord
8 | from random import shuffle
9 | from statistics import mean
10 |
11 | from scarap.readerswriters import *
12 | from scarap.utils import *
13 |
14 | def subset_idmat(matrix, rownames, rownames_sub):
15 | """Subsets an identity matrix.
16 |
17 | Args:
18 | matrix: An identity matrix as a numpy array
19 | rownames: A list of rownames (= colnames)
20 | rownames_sub: A list of rownames to select
21 |
22 | Returns:
23 | A subset of the identity matrix
24 | A subset of the rownames
25 | """
26 | ixs = [ix for ix, gene in enumerate(rownames) if gene in rownames_sub]
27 | ixs = np.array(ixs)
28 | matrix_sub = matrix[ixs[:, None], ixs]
29 | rownames_sub = [rownames[ix] for ix in ixs]
30 | return(matrix_sub, rownames_sub)
31 |
32 | def distmat_from_idmat(idmat):
33 | """Calculates a distance matrix.
34 |
35 | Args:
36 | idmat: An identity matrix as a numpy array
37 |
38 | Returns:
39 | A distance matrix in the format needed by the
40 | cluster.hierarchy.linkage function of scipy.
41 | """
42 | n = np.size(idmat, 0)
43 | dm = []
44 | for r in range(n - 1):
45 | for c in range(r + 1, n):
46 | dm.append(1 - idmat[r, c])
47 | return(dm)
48 |
49 | def identity_matrix(seqrecords):
50 | '''Calculates a pairwise sequence identity matrix.
51 |
52 | Probably approximately as fast as the distmat tool from EMBOSS, but this
53 | function can easily be parallelized on (batches of) columns.
54 |
55 | Args:
56 | seqrecords (list): A list of DNA sequences or SeqRecords.
57 |
58 | Returns:
59 | A matrix with sequence identity values.
60 | '''
61 |
62 | n_seqs = len(seqrecords)
63 | n_cols = len(seqrecords[0].seq)
64 |
65 | # matrix with pairwise counts of alignment positions that are
66 | # identical
67 | identity_counts = np.zeros((n_seqs, n_seqs), np.uint32)
68 | # matrix with pairwise counts of alignment positions that are
69 | # incomparable
70 | comparable_counts = np.zeros((n_seqs, n_seqs), np.uint32)
71 |
72 | for col in range(n_cols):
73 | # print("col ", col, " of ", n_cols)
74 | # dictionary to store for each possible character the indices
75 | # of sequences with that character
76 | chars = {}
77 | for sr_ix, sr in enumerate(seqrecords):
78 | char = sr.seq[col]
79 | if char != "-":
80 | chars.setdefault(char, []).append(sr_ix)
81 | # for letters in the alphabet, add identity counts
82 | ixs_comp = np.array([], np.uint32)
83 | for char in chars.keys():
84 | ixs = np.array(chars[char], np.uint32)
85 | identity_counts[ixs[:, None], ixs] += 1
86 | ixs_comp = np.hstack((ixs_comp, ixs))
87 | # for all sequence combinations that both have a letter in the alphabet
88 | # add that they are comparable
89 | comparable_counts[ixs_comp[:, None], ixs_comp] += 1
90 |
91 | # avoid division by zero
92 | comparable_counts[comparable_counts == 0] += 1
93 |
94 | identity_matrix = identity_counts / comparable_counts
95 |
96 | return(identity_matrix)
97 |
98 | def split_possible(genomes):
99 | """Determines whether splitting the family is an option.
100 |
101 | Args:
102 | genomes (list): For each gene in the family, the genome that it belongs
103 | to.
104 |
105 | Returns:
106 | true/false
107 | """
108 | n_genes = len(genomes)
109 | n_genomes = len(set(genomes))
110 | if n_genes <= 3: return(False)
111 | if n_genomes == 1: return(False)
112 | if n_genes == n_genomes: return(False)
113 | return(True)
114 |
115 | def calc_pgo(genomes_fam1, genomes_fam2):
116 | """Calculates the proportion of genome overlap (pgo).
117 |
118 | Calculates the observed proportion of genomes present in both subfamilies
119 | of a gene family.
120 |
121 | Args:
122 | genomes_fam1 (list): For each gene in family 1, the genome that it
123 | belongs to.
124 | genomes_fam2 (list): For each gene in family 2, the genome that it
125 | belongs to.
126 |
127 | Returns:
128 | The observed pgo.
129 | """
130 | if 0 in [len(genomes_fam1), len(genomes_fam2)]: return 0
131 | n_unique_fam1 = len(set(genomes_fam1))
132 | n_unique_fam2 = len(set(genomes_fam2))
133 | n_unique_tot = len(set(genomes_fam1 + genomes_fam2))
134 | pgo = (n_unique_fam1 + n_unique_fam2 - n_unique_tot) / \
135 | min([n_unique_fam1, n_unique_fam2])
136 | return(pgo)
137 |
138 | def ncat_exp(n, probs):
139 | """Calculates the expected number of distinct categories.
140 |
141 | Calculates the expected number of distinct categories present in a
142 | multinomial sample. See Emigh, 1983, Biometrics.
143 | http://www.jstor.org/stable/2531019
144 |
145 | Args:
146 | n (int): The sample size
147 | probs: A list of probabilities that define the multinomial
148 | distribution.
149 |
150 | Returns:
151 | The expected number of distinct categories.
152 | """
153 | ncat_exp = len(probs) - sum([(1 - prob) ** n for prob in probs])
154 | return(ncat_exp)
155 |
156 | def pred_pgo(genomes_fam1, genomes_fam2):
157 | """Predicts the proportion of genome overlap (pgo).
158 |
159 | Predicts the percentage of unique genomes that are expected to be present
160 | in both subfamilies of a gene family, give a model where genomes are
161 | assigned randomly to the genes in each subfamily.
162 |
163 | Args:
164 | genomes_fam1: A list of genomes that the genes of family 1 belong
165 | to.
166 | genomes_fam2: A list of genomes that the genes of family 2 belong
167 | to.
168 |
169 | Returns:
170 | The predicted pgo.
171 | """
172 | if 0 in [len(genomes_fam1), len(genomes_fam2)]: return 0
173 | genomes = genomes_fam1 + genomes_fam2
174 | freqs = pd.Series(genomes).value_counts().tolist()
175 | tot = sum(freqs)
176 | probs = [freq / tot for freq in freqs]
177 | ncat_exp_tot = ncat_exp(len(genomes), probs)
178 | ncat_exp_fam1 = ncat_exp(len(genomes_fam1), probs)
179 | ncat_exp_fam2 = ncat_exp(len(genomes_fam2), probs)
180 | pgo = (ncat_exp_fam1 + ncat_exp_fam2 - ncat_exp_tot) / \
181 | min([ncat_exp_fam1, ncat_exp_fam2])
182 | if pgo > 1: pgo = 1
183 | return(pgo)
184 |
185 | def train_cutoffs(hits, pangenome):
186 | """Trains a cutoff per profile (orthogroup).
187 |
188 | Args:
189 | hits (DataFrame): A table with the columns gene, profile, score and
190 | positive.
191 | pangenome (DataFrame): A table with the columns gene, genome and
192 | orthogroup.
193 |
194 | Returns:
195 | A table with the columns profile and cutoff.
196 | """
197 | hits = pd.merge(hits, pangenome[["gene", "orthogroup"]], how = "left")
198 | hits["positive"] = hits["profile"] == hits["orthogroup"]
199 | profile_to_cutoff = {}
200 | for profile, profile_hits in hits.groupby("profile"):
201 | scores_positive = profile_hits["score"][profile_hits["positive"]]
202 | scores_negative = profile_hits["score"][~ profile_hits["positive"]]
203 | if scores_negative.empty:
204 | profile_to_cutoff[profile] = mean([0, mean(scores_positive)])
205 | elif scores_positive.empty:
206 | profile_to_cutoff[profile] = 0
207 | else:
208 | profile_to_cutoff[profile] = mean([mean(scores_positive),
209 | mean(scores_negative)])
210 | profiles = pd.DataFrame(profile_to_cutoff.items(), columns = ["profile",
211 | "cutoff"])
212 | return(profiles)
213 |
214 | def process_scores(hits, cutoffs, top_profiles = True):
215 | hits = pd.merge(hits, cutoffs, how = "left")
216 | hits = hits[hits.score >= hits.cutoff]
217 | if top_profiles:
218 | hits = hits.sort_values("score").\
219 | drop_duplicates(["gene"], keep = "last")
220 | hits = hits[["gene", "profile"]]
221 | hits = hits.rename(columns = {"profile": "orthogroup"})
222 | return(hits)
223 |
224 | def determine_corefams(pan, core_filter, max_cores = 0):
225 | fams = checkgroups(pan)
226 | corefams = fams[fams.occurrence_singlecopy >= core_filter]
227 | if (max_cores > 0):
228 | corefams = corefams\
229 | .sort_values("occurrence_singlecopy", ascending = False)\
230 | .head(max_cores)
231 | return(corefams.orthogroup.tolist())
232 |
233 | def checkgenomes(genes_core):
234 | """Computes genome statistics from a core genome table.
235 |
236 | Args:
237 | genes_core (Data Frame): A table with columns gene, genome and
238 | orthogroup.
239 |
240 | Returns:
241 | A pandas Data Frame with the columns genome, completeness and
242 | contamination.
243 | """
244 | n_groups = len(set(genes_core.orthogroup))
245 | genomes = genes_core\
246 | .groupby(["genome", "orthogroup"])\
247 | .agg(n_copies = ("gene", len))\
248 | .reset_index()\
249 | .groupby("genome")\
250 | .agg(completeness = ("n_copies", lambda x: len(x) / n_groups),
251 | contamination = ("n_copies", lambda x: sum(x > 1) / n_groups))\
252 | .reset_index()
253 | return(genomes)
254 |
255 | def checkgroups(genes):
256 | """Computes orthogroup statistics from a pangenome table.
257 |
258 | Args:
259 | genes (Data Frame): A table with columns gene, genome and orthogroup.
260 |
261 | Returns:
262 | A pandas Data Frame with the columns orthogroup, occurrence and
263 | occurrence_singlecopy.
264 | """
265 | n_genomes = len(set(genes.genome))
266 | orthogroups = genes\
267 | .groupby(["genome", "orthogroup"])\
268 | .agg(n_copies = ("gene", len))\
269 | .reset_index()\
270 | .groupby("orthogroup")\
271 | .agg(occurrence = ("n_copies", len),
272 | occurrence_singlecopy = ("n_copies", lambda x: sum(x == 1)))\
273 | .apply(lambda x: x / n_genomes)\
274 | .reset_index()
275 | return(orthogroups)
276 |
277 | def filter_genomes(pangenome, genomes):
278 | pangenome = pangenome[pangenome.genome.isin(genomes)]
279 | return(pangenome)
280 |
281 | def filter_groups(pangenome, orthogroups):
282 | pangenome = pangenome[pangenome.orthogroup.isin(orthogroups)]
283 | return(pangenome)
284 |
285 | def select_representative(records, longest = False):
286 | records = sorted(records, key = lambda x: len(x))
287 | if longest:
288 | return(records[-1])
289 | else:
290 | return(records[len(records) // 2])
291 |
292 |
293 | def reverse_align(og_nucs, og_aas_aligned):
294 | """Aligns a list of nucleotide sequences.
295 |
296 | This function aligns a list of nucleotide sequences, given a list of
297 | aligned amino acid sequences.
298 |
299 | Naming:
300 |
301 | * sr = SeqRecord (Biopython)
302 | * og = orthogroup
303 | * nucs = nucleotides
304 | * aas = amino acids
305 |
306 | Ags:
307 | og_nucs (list): The SeqRecord list of nucleotide sequences to align.
308 | og_aas_aligned (list): The SeqRecord list of amino acid sequences that
309 | are already aligned (reference alignment).
310 |
311 | Returns:
312 | A list with seqrecords of aligned nucleotide sequences.
313 | """
314 | og_aas_aligned = {seq.id: seq.seq for seq in og_aas_aligned}
315 | og_nucs_aligned = []
316 | for nucs_sr in og_nucs:
317 | nucs_id = nucs_sr.id
318 | nucs_seq = nucs_sr.seq
319 | if not nucs_id in og_aas_aligned.keys():
320 | logging.warning(f"no translation found for gene {nucs_id}")
321 | continue
322 | aas_gapped_seq = og_aas_aligned[nucs_id]
323 | nucs_gapped_seq = ""
324 | nucs_pos = 0
325 | for aa in aas_gapped_seq:
326 | if aa == "-":
327 | nucs_gapped_seq += "---"
328 | else:
329 | nucs_gapped_seq += nucs_seq[nucs_pos:(nucs_pos + 3)]
330 | nucs_pos += 3
331 | nucs_gapped_sr = SeqRecord.SeqRecord(id = nucs_id,
332 | seq = nucs_gapped_seq, description = "")
333 | og_nucs_aligned.append(nucs_gapped_sr)
334 | return(og_nucs_aligned)
335 |
336 | def gather_orthogroup_sequences(pangenome, faapaths, dout_orthogroups,
337 | min_genomes = 1):
338 |
339 | # make output folder and empty if already exists
340 | makedirs_smart(dout_orthogroups)
341 |
342 | # filter orthogroups based on number of genomes they occur in
343 | if min_genomes > 1:
344 | pangenome = pangenome\
345 | .groupby("orthogroup")\
346 | .filter(lambda x: len(set(x["genome"])) >= min_genomes)\
347 | .reset_index()
348 |
349 | # make dictionary to store faapaths of genomes
350 | genome_to_faapath = {filename_from_path(faapath): faapath for faapath in
351 | faapaths}
352 |
353 | # gather sequences and store in file per orthogroup
354 | for genome, genes in pangenome.groupby("genome"):
355 | faapath = genome_to_faapath[genome]
356 | gene_to_orthogroup = dict(zip(genes.gene, genes.orthogroup))
357 | with open_smart(faapath) as hin_genome:
358 | for record in SeqIO.parse(hin_genome, "fasta"):
359 | orthogroup = gene_to_orthogroup.get(record.id)
360 | if orthogroup is None:
361 | continue
362 | fout_orthogroup = os.path.join(dout_orthogroups,
363 | orthogroup + ".fasta")
364 | with open(fout_orthogroup, "a+") as hout_orthogroup:
365 | SeqIO.write(record, hout_orthogroup, "fasta")
366 |
367 | def create_pseudogenome(pangenome, faapaths, tmpdio):
368 | "Returns a pseudogenome with one representative gene per orthogroup."
369 | os.makedirs(tmpdio)
370 | gather_orthogroup_sequences(pangenome, faapaths, tmpdio)
371 | genes = [None] * pangenome["orthogroup"].nunique()
372 | for ix, ogfin in enumerate(listpaths(tmpdio)):
373 | seqs = read_fasta(ogfin)
374 | repr = select_representative(seqs)
375 | genes[ix] = repr.id
376 | genetbl = pangenome[pangenome["gene"].isin(genes)]
377 | genetbl = genetbl[["gene", "genome"]]
378 | shutil.rmtree(tmpdio)
379 | return(genetbl)
380 |
381 | def construct_supermatrix(coregenome, alifins, supermatrixfout):
382 | """Constructs a contatenated alignment (= supermatrix).
383 |
384 | Function to construct a supermatrix given alignments of individual single-copy
385 | core orthogroups. If there are two or more copies of an orthogroup in a genome,
386 | all copies will be dropped.
387 |
388 | Args:
389 | coregenome (DataFrame): A table with the columns gene, genome and
390 | orthogroup.
391 | alifins (list): A list of input files containing alignments of
392 | single-copy core orthogroups.
393 | supermatrixfout (str): A path to a fasta file to write the supermatrix
394 | to.
395 | """
396 |
397 | supermatrix = {}
398 | genomes = list(set(coregenome.genome))
399 | n_genomes = len(genomes)
400 | for genome in genomes:
401 | try:
402 | empty_seq = SeqRecord.Seq("")
403 | except AttributeError:
404 | empty_seq = "" # for biopython v1.79
405 | supermatrix[genome] = SeqRecord.SeqRecord(id = genome, seq = empty_seq,
406 | description = "")
407 |
408 | alifindict = {filename_from_path(alifin): alifin for alifin in alifins}
409 |
410 | n_fams_sc = 0
411 |
412 | for orthogroup, rows in coregenome.groupby("orthogroup"):
413 | alifin = alifindict[orthogroup]
414 | sequencedict = {}
415 | for record in SeqIO.parse(alifin, "fasta"):
416 | alilen = len(record.seq)
417 | sequencedict[record.id] = record.seq
418 | rows = rows.drop_duplicates("genome", keep = False)
419 | rows = pd.merge(pd.DataFrame({"genome": genomes}), rows, how = "left")
420 | for ix, row in rows.iterrows():
421 | sequence_to_add = sequencedict.get(row.gene, "-" * alilen)
422 | supermatrix[row.genome] = supermatrix[row.genome] + sequence_to_add
423 |
424 | with open(supermatrixfout, "a") as supermatrixhout:
425 | for genome in supermatrix:
426 | SeqIO.write(supermatrix[genome], supermatrixhout, "fasta")
427 |
428 | """
429 | Function to align a nucleotide fasta using an amino acid fasta as a reference
430 | alignment.
431 | Arguments:
432 | - fin_og_nucs: nucleotide fasta to align (.fasta)
433 | - fin_og_aas_aligned: amino acid fasta that is aligned (.aln)
434 | - fout_og_nucs_aligned: file to store the aligned nucleotide fasta (.aln)
435 | """
436 | def reverse_align_helper(fin_og_nucs, fin_og_aas_aligned, fout_og_nucs_aligned):
437 | og_nucs = list(SeqIO.parse(fin_og_nucs, "fasta"))
438 | og_aas_aligned = list(SeqIO.parse(fin_og_aas_aligned, "fasta"))
439 | og_nucs_aligned = reverse_align(og_nucs, og_aas_aligned)
440 | with open(fout_og_nucs_aligned, "w") as hout_og_nucs_aligned:
441 | SeqIO.write(og_nucs_aligned, hout_og_nucs_aligned, "fasta")
442 |
443 | """
444 | Function to align a set of nucleotide fastas using a set of amino acid fastas
445 | as reference alignments.
446 | """
447 | def reverse_align_parallel(fins_ogs_nucs, fins_ogs_aas_aligned,
448 | fouts_ogs_nucs_aligned):
449 |
450 | with concurrent.futures.ProcessPoolExecutor() as executor:
451 | executor.map(reverse_align_helper, fins_ogs_nucs, fins_ogs_aas_aligned,
452 | fouts_ogs_nucs_aligned)
453 |
--------------------------------------------------------------------------------
/src/scarap/helpers.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import shutil
4 |
5 | from scarap.utils import *
6 | from scarap.readerswriters import *
7 | from scarap.computers import *
8 | from scarap.callers import *
9 |
10 | # used by the build and search modules
11 | def run_profilesearch(fins_faas, fins_alis, fout_hits, dout_tmp, threads):
12 |
13 | # define tmp paths
14 | dout_mmseqs = os.path.join(dout_tmp, "mmseqs2")
15 | dout_logs = os.path.join(dout_tmp, "mmseqs2_logs")
16 | dout_rubbish = os.path.join(dout_tmp, "rubbish")
17 | fout_sto = os.path.join(dout_tmp, "alis.sto")
18 |
19 | # create tmp subfolders
20 | for dir in [dout_mmseqs, dout_logs, dout_rubbish]:
21 | os.makedirs(dir, exist_ok = True)
22 |
23 | logging.info("converting alignments from fasta to stockholm format")
24 | fastas2stockholm(fins_alis, fout_sto)
25 |
26 | logging.info("creating mmseqs2 database from faa files")
27 | run_mmseqs(["createdb"] + fins_faas + [f"{dout_mmseqs}/faadb"],
28 | f"{dout_logs}/create_faadb.log")
29 |
30 | logging.info("creating mmseqs2 database with profiles of orthogroups")
31 | run_mmseqs(["convertmsa", fout_sto, f"{dout_mmseqs}/msadb",
32 | "--identifier-field", "0"], f"{dout_logs}/create_msadb.log")
33 | run_mmseqs(["msa2profile", f"{dout_mmseqs}/msadb",
34 | f"{dout_mmseqs}/profiledb", "--match-mode", "1"],
35 | f"{dout_logs}/create_msadb.log")
36 |
37 | logging.info("searching faas against profiles")
38 | run_mmseqs(["search", f"{dout_mmseqs}/faadb", f"{dout_mmseqs}/profiledb",
39 | f"{dout_mmseqs}/resultdb", f"{dout_rubbish}"],
40 | f"{dout_logs}/search.log", threads = threads)
41 | run_mmseqs(["createtsv", f"{dout_mmseqs}/faadb", f"{dout_mmseqs}/profiledb",
42 | f"{dout_mmseqs}/resultdb", fout_hits, "--full-header"],
43 | f"{dout_logs}/create_tsv.log")
44 |
45 | # remove tmp
46 | shutil.rmtree(dout_tmp)
47 |
--------------------------------------------------------------------------------
/src/scarap/module_wrappers.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import sys
4 |
5 | from scarap.utils import *
6 | from scarap.checkers import *
7 | from scarap.modules import *
8 |
9 | ####################
10 | # helper functions #
11 | ####################
12 |
13 | def correct_freq(freq, name):
14 | if freq > 100:
15 | logging.error(f"{name} should be between 0 and 1")
16 | sys.exit(1)
17 | elif freq > 1:
18 | freq = freq / 100
19 | logging.info(f"corrected {name} value to {str(freq)}")
20 | return(freq)
21 |
22 | def process_reps(args):
23 |
24 | if args.min_reps < 2:
25 | logging.error("at least two representative sequences are needed for "
26 | "family splitting")
27 |
28 | if (args.max_reps == 0):
29 | args.max_reps = round(args.min_reps * 1.25)
30 | logging.info(f"maximum number of representatives set to "
31 | f"{args.max_reps}")
32 |
33 | if (args.max_align == 0):
34 | args.max_align = round(args.max_reps * 16)
35 | logging.info(f"maximum number of sequences to align set to "
36 | f"{args.max_align}")
37 |
38 | if args.min_reps > args.max_reps:
39 | logging.error("the minimum number of representatives must be smaller "
40 | "than or equal to the maximum number")
41 |
42 | if args.max_reps > args.max_align:
43 | logging.error("the maximum number of representatives must be smaller "
44 | "than or equal to the maximum number of sequences to align")
45 |
46 | return(args)
47 |
48 | ###################
49 | # module wrappers #
50 | ###################
51 |
52 | def run_pan_withchecks(args):
53 |
54 | logging.info("welcome to the pan task")
55 |
56 | logging.info("checking arguments other than output folder")
57 | check_fastas(args.faa_files)
58 | if not args.species is None:
59 | check_infile(args.species)
60 |
61 | logging.info("checking dependencies")
62 | if args.method in ["O-B", "O-D"]:
63 | check_tool("orthofinder")
64 | elif args.method == "S":
65 | check_mmseqs()
66 | else:
67 | check_mmseqs()
68 | check_mafft()
69 |
70 | args = process_reps(args)
71 |
72 | run_pan(args)
73 |
74 | def run_build_withchecks(args):
75 |
76 | logging.info("welcome to the build task")
77 |
78 | logging.info("checking arguments other than output folder")
79 | check_fastas(args.faa_files)
80 | check_infile(args.pangenome)
81 | faapaths = read_fastapaths(args.faa_files)
82 | args.core_prefilter = correct_freq(args.core_prefilter, "core prefilter")
83 | args.core_filter = correct_freq(args.core_filter, "core filter")
84 |
85 | # give warning if core filter or max core genes is given without prefilter
86 | if args.core_filter != 0 or args.max_core_genes != 0:
87 | if args.core_prefilter == 0:
88 | logging.warning("a core filter or maximum number of core genes was "
89 | "given without a core prefilter - this can be needlessly slow")
90 |
91 | logging.info("checking dependencies")
92 | check_mmseqs()
93 | check_mafft()
94 |
95 | run_build(args)
96 |
97 | def run_search_withchecks(args):
98 |
99 | logging.info("welcome to the search task")
100 |
101 | logging.info("checking arguments other than output folder")
102 | check_fastas(args.faa_files)
103 | check_db(args.db)
104 |
105 | logging.info("checking dependencies")
106 | check_mmseqs()
107 |
108 | run_search(args)
109 |
110 | def run_checkgenomes_withchecks(args):
111 |
112 | logging.info("welcome to the checkgenomes task")
113 |
114 | logging.info("checking arguments other than output folder")
115 | check_infile(args.coregenome)
116 |
117 | run_checkgenomes(args)
118 |
119 | def run_checkgroups_withchecks(args):
120 |
121 | logging.info("welcome to the checkgroups task")
122 |
123 | logging.info("checking arguments other than output folder")
124 | check_infile(args.coregenome)
125 |
126 | run_checkgroups(args)
127 |
128 | def run_filter_withchecks(args):
129 |
130 | logging.info("welcome to the filter task")
131 |
132 | logging.info("checking arguments other than output folder")
133 | check_infile(args.pangenome)
134 | if not args.genomes is None:
135 | check_infile(args.genomes)
136 | if not args.orthogroups is None:
137 | check_infile(args.orthogroups)
138 |
139 | run_filter(args)
140 |
141 | def run_concat_withchecks(args):
142 |
143 | logging.info("welcome to the concat task")
144 |
145 | logging.info("checking arguments other than output folder")
146 | check_fastas(args.faa_files)
147 | check_infile(args.pangenome)
148 | if not args.ffn_files is None:
149 | check_fastas(args.ffn_files)
150 | args.core_filter = correct_freq(args.core_filter, "core filter")
151 |
152 | logging.info("checking dependencies")
153 | check_mafft()
154 |
155 | run_concat(args)
156 |
157 | def run_sample_withchecks(args):
158 |
159 | logging.info("welcome to the sample task")
160 |
161 | logging.info("checking arguments other than output folder")
162 | check_fastas(args.fasta_files)
163 | fastapaths = read_fastapaths(args.fasta_files)
164 | n_genomes = len(fastapaths)
165 | if args.max_genomes > n_genomes:
166 | args.max_genomes = n_genomes
167 | logging.info(f"max_genomes reduced to {args.max_genomes}, since "
168 | "that's the total number of genomes")
169 | check_infile(args.pangenome)
170 | if args.identity > 100:
171 | logging.error("identity should be between 0 and 1")
172 | sys.exit(1)
173 | elif args.identity > 1:
174 | args.identity = args.identity / 100
175 | logging.info(f"corrected identity value to {str(args.identity)}")
176 | if args.method == "median":
177 | logging.info("whole-genome ANI will be calculated as the median of all "
178 | "per-gene identity values")
179 | elif args.method == "mean":
180 | logging.info("whole-genome ANI will be calculated as the mean of all "
181 | "per-gene identity values")
182 | elif args.method[:4] == "mean":
183 | p = args.method[4:]
184 | try:
185 | p = int(p)
186 | if p > 100 or p <= 0: raise ValueError
187 | except ValueError:
188 | logging.error("method unknown")
189 | sys.exit(1)
190 | logging.info(f"whole-genome ANI will be calculated as the mean of the "
191 | f"middle {p}% of per-gene identity values")
192 | else:
193 | logging.error("method unknown")
194 | sys.exit(1)
195 |
196 | logging.info("checking dependencies")
197 | check_mmseqs()
198 |
199 | run_sample(args)
200 |
201 | def run_fetch_withchecks(args):
202 |
203 | logging.info("welcome to the fetch task")
204 |
205 | logging.info("checking arguments other than output folder")
206 | check_fastas(args.fasta_files)
207 | check_infile(args.pangenome)
208 |
209 | run_fetch(args)
210 |
211 | def run_core_withchecks(args):
212 |
213 | logging.info("welcome to the core pipeline")
214 |
215 | logging.info("checking arguments other than output folder")
216 | check_fastas(args.faa_files)
217 | fastapaths = read_fastapaths(args.faa_files)
218 | n_genomes = len(fastapaths)
219 | if args.seeds > n_genomes:
220 | args.seeds = n_genomes
221 | logging.info(f"number of seeds reduced to {args.seeds}, since that's "
222 | "the number of genomes")
223 | args.core_prefilter = correct_freq(args.core_prefilter, "core prefilter")
224 | args.core_filter = correct_freq(args.core_filter, "core filter")
225 |
226 | logging.info("checking dependencies")
227 | if args.method in ["O-B", "O-D"]:
228 | check_tool("orthofinder")
229 | else:
230 | check_mmseqs()
231 | check_mafft()
232 |
233 | args = process_reps(args)
234 |
235 | run_core(args)
236 |
--------------------------------------------------------------------------------
/src/scarap/modules.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import numpy as np
3 | import os
4 | import pandas as pd
5 | import shutil
6 |
7 | from argparse import Namespace
8 | from concurrent.futures import ProcessPoolExecutor
9 | from statistics import median, mean
10 | from random import sample
11 |
12 | from scarap.callers import *
13 | from scarap.computers import *
14 | from scarap.helpers import *
15 | from scarap.pan import *
16 | from scarap.readerswriters import *
17 | from scarap.utils import *
18 |
19 | def run_pan(args):
20 | if "species" in args and not args.species is None:
21 | run_pan_hier(args)
22 | else:
23 | run_pan_nonhier(args)
24 |
25 | def run_pan_nonhier(args):
26 |
27 | pangenomefout = os.path.join(args.outfolder, "pangenome.tsv")
28 | if os.path.isfile(pangenomefout):
29 | logging.info("existing pangenome detected - moving on")
30 | return()
31 |
32 | faafins = read_fastapaths(args.faa_files)
33 |
34 | if args.method in ["O-B", "O-D"]:
35 |
36 | logging.info("creating orthofinder directory")
37 | dir_orthofinder = os.path.join(args.outfolder, "orthofinder")
38 | os.makedirs(dir_orthofinder, exist_ok = True)
39 |
40 | logging.info("running orthofinder")
41 | logfile = os.path.join(args.outfolder, "orthofinder.log")
42 |
43 | if args.method == "O-B":
44 | engine = "blast"
45 | else:
46 | engine = "diamond"
47 | run_orthofinder(faafins, dir_orthofinder, logfile, args.threads,
48 | engine)
49 |
50 | logging.info("creating tidy pangenome file")
51 | pangenome = read_pangenome_orthofinder(dir_orthofinder)
52 | write_tsv(pangenome, pangenomefout)
53 |
54 | else:
55 |
56 | logging.info(f"pangenome will be constructed with the {args.method} "
57 | "strategy")
58 | logging.info(f"for alignments of more than {args.max_align} sequences, "
59 | f"{args.min_reps} to {args.max_reps} representative sequences will "
60 | "be used")
61 | infer_pangenome(faafins, args.method, args.min_reps, args.max_reps,
62 | args.max_align, args.outfolder, args.threads)
63 |
64 | def run_pan_hier(args):
65 |
66 | logging.info("creating genome table with species and faa paths")
67 | genometbl1 = read_species(args.species)
68 | genometbl1.species = [sp.replace(" ", "_") for sp in genometbl1.species]
69 | faapaths = read_fastapaths(args.faa_files)
70 | genomes = [filename_from_path(path) for path in faapaths]
71 | genometbl2 = pd.DataFrame({"faapath": faapaths, "genome": genomes})
72 | genometbl = pd.merge(genometbl1, genometbl2)
73 |
74 | logging.info("creating the necessary subfolders")
75 | speciespansdio = os.path.join(args.outfolder, "speciespangenomes")
76 | pseudogenomesdio = os.path.join(args.outfolder, "pseudogenomes")
77 | pseudogenomesfio = os.path.join(args.outfolder, "pseudogenomes.tsv")
78 | pseudopandio = os.path.join(args.outfolder, "pseudopangenome")
79 | pseudopanfio = os.path.join(args.outfolder, "pseudopangenome.tsv")
80 | pangenomefout = os.path.join(args.outfolder, "pangenome.tsv")
81 | os.makedirs(speciespansdio, exist_ok = True)
82 | os.makedirs(pseudogenomesdio, exist_ok = True)
83 | os.makedirs(pseudopandio, exist_ok = True)
84 |
85 | nonhier_args = dict(
86 | threads=args.threads,
87 | method=args.method,
88 | max_align=args.max_align,
89 | max_reps=args.max_reps,
90 | min_reps=args.min_reps
91 | )
92 |
93 | logging.info("PHASE 1: inferring species-level pangenomes")
94 | for species, genomesubtbl in genometbl.groupby("species"):
95 | speciespanfio = os.path.join(speciespansdio, species + ".tsv")
96 | if os.path.exists(speciespanfio):
97 | logging.info(f"existing pangenome found for {species}")
98 | continue
99 | logging.info(f"started inferring pangenome of {species}")
100 | dout = os.path.join(speciespansdio, species)
101 | os.makedirs(dout, exist_ok = True)
102 | faapaths_sub = genomesubtbl["faapath"].values.tolist()
103 | faapathsfio = os.path.join(dout, "faapaths.txt")
104 | write_lines(faapaths_sub, faapathsfio)
105 | run_pan_nonhier(Namespace(faa_files = faapathsfio, outfolder = dout,
106 | **nonhier_args))
107 | shutil.move(os.path.join(dout, "pangenome.tsv"), speciespanfio)
108 | shutil.rmtree(dout)
109 |
110 | logging.info("PHASE 2: constructing pseudogenome per species")
111 | n_species = genometbl["species"].nunique()
112 | pseudogenomes = [None] * n_species
113 | for ix, speciespanfio in enumerate(listpaths(speciespansdio)):
114 | species = filename_from_path(speciespanfio)
115 | logging.info(f"constructing pseudogenome for {species}")
116 | speciespan = read_genes(speciespanfio)
117 | tmpdio = os.path.join(args.outfolder, "temp")
118 | pseudogenomes[ix] = create_pseudogenome(speciespan, faapaths, tmpdio)
119 | pseudogenomes[ix]["species"] = species
120 | pseudogenomes = pd.concat(pseudogenomes)
121 | write_tsv(pseudogenomes, pseudogenomesfio)
122 |
123 | logging.info("PHASE 3: inferring pseudopangenome")
124 | pseudogenomes = pseudogenomes.rename(columns = {"species": "orthogroup"})
125 | gather_orthogroup_sequences(pseudogenomes, faapaths, pseudogenomesdio)
126 | run_pan_nonhier(Namespace(faa_files = pseudogenomesdio,
127 | outfolder = pseudopandio, **nonhier_args))
128 | shutil.move(os.path.join(pseudopandio, "pangenome.tsv"), pseudopanfio)
129 | shutil.rmtree(pseudogenomesdio)
130 | shutil.rmtree(pseudopandio)
131 |
132 | logging.info("PHASE 4: inflating pseudopangenome with species pangenomes")
133 | pangenomes = [None] * len(os.listdir(speciespansdio))
134 | for ix, speciespanfio in enumerate(listpaths(speciespansdio)):
135 | pangenomes[ix] = read_genes(speciespanfio)
136 | pangenomes[ix]["species"] = filename_from_path(speciespanfio)
137 | pangenomes = pd.concat(pangenomes)
138 | pangenomes = pangenomes.rename(columns = {"orthogroup": "speciesfam"})
139 | pseudopan = read_genes(pseudopanfio)
140 | pseudopan = pseudopan.rename(columns = {"genome": "species"})
141 | speciesfamtbl = pd.merge(pseudopan, pangenomes, on = ["gene", "species"],
142 | how = "left")
143 | speciesfamtbl = speciesfamtbl[["speciesfam", "species", "orthogroup"]]
144 | pangenome = pd.merge(pangenomes, speciesfamtbl,
145 | on = ["speciesfam", "species"])
146 | pangenome = pangenome[["gene", "genome", "orthogroup"]]
147 | write_tsv(pangenome, pangenomefout)
148 |
149 | def run_build(args):
150 |
151 | fin_faapaths = args.faa_files
152 | fin_pangenome = args.pangenome
153 | dout = args.outfolder
154 | core_prefilter = args.core_prefilter
155 | core_filter = args.core_filter
156 | max_cores = args.max_core_genes
157 | threads = args.threads
158 |
159 | # define output paths/folders
160 | dout_ogseqs = os.path.join(dout, "orthogroups")
161 | dout_alis = os.path.join(dout, "alignments")
162 | dout_tmp = os.path.join(dout, "tmp")
163 | fout_cutoffs = os.path.join(dout, "cutoffs.csv")
164 | fout_hits = os.path.join(dout, "hits.tsv")
165 | fout_genes = os.path.join(dout, "genes.tsv")
166 |
167 | if os.path.isfile(fout_cutoffs):
168 | logging.info("existing database detected - moving on")
169 | return()
170 |
171 | logging.info("creating output subfolders")
172 | for dir in [dout_ogseqs, dout_alis]:
173 | os.makedirs(dir, exist_ok = True)
174 |
175 | logging.info("reading pangenome")
176 | pangenome = read_genes(fin_pangenome)
177 | # read separate table with genomes of all genes, in case the pangenome
178 | # table is not complete or core genes get selected
179 | fins_faas = read_fastapaths(fin_faapaths)
180 | genes_genomes = extract_genes(fins_faas)
181 |
182 | if core_prefilter != 0:
183 | logging.info(f"applying core prefilter of {core_prefilter}")
184 | corefams = determine_corefams(pangenome, core_prefilter)
185 | pangenome = filter_groups(pangenome, corefams)
186 |
187 | logging.info("gathering sequences of orthogroups")
188 | gather_orthogroup_sequences(pangenome, fins_faas, dout_ogseqs, 1)
189 | logging.info(f"gathered sequences for {len(os.listdir(dout_ogseqs))} "
190 | f"orthogroups")
191 |
192 | logging.info("aligning orthogroups")
193 | orthogroups = [os.path.splitext(f)[0] for f in os.listdir(dout_ogseqs)]
194 | fouts_ogseqs = make_paths(orthogroups, dout_ogseqs, ".fasta")
195 | fouts_alis = make_paths(orthogroups, dout_alis, ".aln")
196 | run_mafft_parallel(fouts_ogseqs, fouts_alis)
197 |
198 | # run profile search (function does its own logging)
199 | run_profilesearch(fins_faas, fouts_alis, fout_hits, dout_tmp, threads)
200 |
201 | logging.info("training score cutoffs for profiles")
202 | colnames = ["gene", "profile", "score"]
203 | hits = pd.read_csv(fout_hits, sep = "\t", names = colnames,
204 | usecols = [0, 1, 2])
205 | hits[["gene", "profile"]] = hits[["gene", "profile"]].\
206 | applymap(lambda x: x.split(" ")[0])
207 | cutoffs = train_cutoffs(hits, pangenome)
208 |
209 | if core_filter != 0 or max_cores != 0:
210 | logging.info(f"applying core filter of {core_filter} and maximum "
211 | f"number of core genes of {max_cores}")
212 | genes = process_scores(hits, cutoffs, top_profiles = False)
213 | genes = pd.merge(genes_genomes, genes, how = "right")
214 | corefams = determine_corefams(genes, core_filter = core_filter,
215 | max_cores = max_cores)
216 | hits = hits[hits["profile"].isin(corefams)]
217 | cutoffs = cutoffs[cutoffs["profile"].isin(corefams)]
218 | for file in os.listdir(dout_alis):
219 | if not os.path.splitext(file)[0] in corefams:
220 | os.remove(os.path.join(dout_alis, file))
221 | logging.info(f"{len(corefams)} core genes were identified")
222 |
223 | logging.info("applying score cutoffs to pangenome")
224 | genes = process_scores(hits, cutoffs)
225 | genes = pd.merge(genes_genomes, genes, how = "right")
226 |
227 | logging.info("writing output files")
228 | write_tsv(genes, fout_genes)
229 | write_tsv(cutoffs, fout_cutoffs)
230 |
231 | logging.info("removing temporary files and folders")
232 | shutil.rmtree(dout_ogseqs)
233 | os.remove(fout_hits)
234 |
235 | def run_search(args):
236 |
237 | fin_qpaths = args.faa_files
238 | din_db = args.db
239 | dout = args.outfolder
240 | threads = args.threads
241 |
242 | # define output paths/folders
243 | dout_tmp = os.path.join(dout, "tmp")
244 | din_alis = os.path.join(din_db, "alignments")
245 | fin_cutoffs = os.path.join(din_db, "cutoffs.csv")
246 | fout_hits = os.path.join(dout, "hits.tsv")
247 | fout_genes = os.path.join(dout, "genes.tsv")
248 |
249 | if os.path.isfile(fout_genes):
250 | logging.info("existing search results detected - moving on")
251 | return()
252 |
253 | # run profile search (function does its own logging)
254 | fins_alis = [os.path.join(din_alis, f) for f in os.listdir(din_alis)]
255 | fins_queries = read_fastapaths(fin_qpaths)
256 | if os.path.isfile(fout_hits):
257 | logging.info("existing mmseqs2 hits detected - moving on")
258 | else:
259 | run_profilesearch(fins_queries, fins_alis, fout_hits, dout_tmp, threads)
260 |
261 | logging.info("reading hits and score cutoffs")
262 | colnames = ["gene", "profile", "score"]
263 | hits = pd.read_csv(fout_hits, sep = "\t", names = colnames,
264 | usecols = [0, 1, 2])
265 | hits[["gene", "profile"]] = hits[["gene", "profile"]].\
266 | applymap(lambda x: x.split(" ")[0])
267 | colnames = ["profile", "cutoff"]
268 | cutoffs = pd.read_csv(fin_cutoffs, sep = "\t", names = colnames)
269 |
270 | logging.info("applying score cutoffs to hits")
271 | genes = process_scores(hits, cutoffs)
272 | logging.info("extracting genome names from faa files")
273 | genes_genomes = extract_genes(fins_queries, threads = threads)
274 | logging.info("merging search results and genome names")
275 | genes = pd.merge(genes_genomes, genes, how = "right")
276 |
277 | logging.info("writing output files")
278 | write_tsv(genes, fout_genes)
279 |
280 | logging.info("removing temporary files and folders")
281 | os.remove(fout_hits)
282 |
283 | def run_checkgenomes(args):
284 |
285 | logging.info("checking genomes")
286 | coregenome = read_genes(args.coregenome)
287 | genomes = checkgenomes(coregenome)
288 | write_tsv(genomes, os.path.join(args.outfolder, "genomes.tsv"))
289 |
290 | def run_checkgroups(args):
291 |
292 | logging.info("checking core orthogroups")
293 | coregenome = read_genes(args.coregenome)
294 | orthogroups = checkgroups(coregenome)
295 | write_tsv(orthogroups, os.path.join(args.outfolder, "orthogroups.tsv"))
296 |
297 | def run_filter(args):
298 |
299 | logging.info("reading pangenome")
300 | pangenome = read_genes(args.pangenome)
301 | if not args.genomes is None:
302 | logging.info("filtering genomes")
303 | genomes = read_lines(args.genomes)
304 | pangenome = filter_genomes(pangenome, genomes)
305 | if not args.orthogroups is None:
306 | logging.info("filtering orthogroups")
307 | orthogroups = read_lines(args.orthogroups)
308 | pangenome = filter_groups(pangenome, orthogroups)
309 | write_tsv(pangenome, os.path.join(args.outfolder, "pangenome.tsv"))
310 |
311 | def run_concat(args):
312 |
313 | fin_faapaths = args.faa_files
314 | fin_pangenome = args.pangenome
315 | dout = args.outfolder
316 | core_filter = args.core_filter
317 | max_cores = args.max_core_genes
318 | fin_ffnpaths = args.ffn_files
319 |
320 | sm_aas_fout = os.path.join(dout, "supermatrix_aas.fasta")
321 | sm_nucs_fout = os.path.join(dout, "supermatrix_nucs.fasta")
322 | seqs_aas_dio = os.path.join(dout, "seqs_aas")
323 | seqs_nucs_dio = os.path.join(dout, "seqs_nucs")
324 | alis_aas_dio = os.path.join(dout, "alis_aas")
325 | alis_nucs_dio = os.path.join(dout, "alis_nucs")
326 |
327 | # exit if requested supermatrices already exist
328 | if os.path.isfile(sm_aas_fout) and (fin_ffnpaths is None or \
329 | os.path.isfile(sm_nucs_fout)):
330 | logging.info("requested supermatrices already exist - moving on")
331 | return()
332 |
333 | logging.info("reading core genome")
334 | coregenome = read_genes(fin_pangenome)
335 | orthogroups = coregenome["orthogroup"].unique()
336 | genomes = coregenome["genome"].unique()
337 | logging.info(f"detected {len(orthogroups)} orthogroups in "
338 | f"{len(genomes)} genomes")
339 |
340 | if core_filter != 0 or max_cores != 0:
341 | logging.info(f"applying core filter of {core_filter} and maximum "
342 | f"number of core genes of {max_cores}")
343 | corefams = determine_corefams(coregenome, core_filter, max_cores)
344 | coregenome = filter_groups(coregenome, corefams)
345 | orthogroups = coregenome["orthogroup"].unique()
346 |
347 | logging.info("removing same-genome copies of core genes")
348 | coregenome = coregenome.drop_duplicates(["genome", "orthogroup"],
349 | keep = False)
350 |
351 | seqs_aas_fios = make_paths(orthogroups, seqs_aas_dio, ".fasta")
352 | alis_aas_fios = make_paths(orthogroups, alis_aas_dio, ".aln")
353 |
354 | # move on if dir already exists and is not empty
355 | if os.path.isdir(seqs_aas_dio) and os.listdir(seqs_aas_dio):
356 |
357 | logging.info("existing amino acid sequences detected - moving on")
358 |
359 | else:
360 |
361 | logging.info("gathering amino acid sequences of orthogroups")
362 | faa_fins = read_fastapaths(fin_faapaths)
363 | os.makedirs(seqs_aas_dio, exist_ok = True)
364 | gather_orthogroup_sequences(coregenome, faa_fins, seqs_aas_dio)
365 |
366 | if os.path.isdir(alis_aas_dio) and os.listdir(alis_aas_dio):
367 |
368 | logging.info("existing amino acid alignments detected - moving on")
369 |
370 | else:
371 |
372 | logging.info("aligning orthogroups on the amino acid level")
373 | os.makedirs(alis_aas_dio, exist_ok = True)
374 | run_mafft_parallel(seqs_aas_fios, alis_aas_fios)
375 |
376 | logging.info("concatenating amino acid alignments")
377 | construct_supermatrix(coregenome, alis_aas_fios, sm_aas_fout)
378 |
379 | if not fin_ffnpaths is None:
380 |
381 | seqs_nucs_fios = make_paths(orthogroups, seqs_nucs_dio, ".fasta")
382 | alis_aas_fios = make_paths(orthogroups, alis_aas_dio, ".aln")
383 | alis_nucs_fios = make_paths(orthogroups, alis_nucs_dio, ".aln")
384 |
385 | if os.path.isdir(seqs_nucs_dio) and os.listdir(seqs_nucs_dio):
386 |
387 | logging.info("existing nucleotide sequences detected - moving on")
388 |
389 | else:
390 |
391 | logging.info("gathering nucleotide sequences of orthogroups")
392 | ffn_fins = read_fastapaths(fin_ffnpaths)
393 | os.makedirs(seqs_nucs_dio, exist_ok = True)
394 | gather_orthogroup_sequences(coregenome, ffn_fins, seqs_nucs_dio)
395 |
396 | if os.path.isdir(alis_nucs_dio) and os.listdir(alis_nucs_dio):
397 |
398 | logging.info("existing nucleotide alignments detected - moving on")
399 |
400 | else:
401 |
402 | logging.info("aligning orthogroups on the nucleotide level")
403 | os.makedirs(alis_nucs_dio, exist_ok = True)
404 | reverse_align_parallel(seqs_nucs_fios, alis_aas_fios,
405 | alis_nucs_fios)
406 |
407 | logging.info("concatenating nucleotide alignments")
408 | construct_supermatrix(coregenome, alis_nucs_fios, sm_nucs_fout)
409 |
410 | logging.info("removing temporary folders")
411 | shutil.rmtree(seqs_aas_dio)
412 | shutil.rmtree(alis_aas_dio)
413 | try:
414 | shutil.rmtree(seqs_nucs_dio)
415 | shutil.rmtree(alis_nucs_dio)
416 | except FileNotFoundError:
417 | pass
418 |
419 | def run_sample(args):
420 |
421 | if "exact" in args and args.exact:
422 | ali_mode = 3
423 | logging.info("identity calculation set to exact")
424 | else:
425 | ali_mode = 1
426 | logging.info("identity calculation set to approximate")
427 |
428 | logging.info("creating output subfolders")
429 | dio_seqs = os.path.join(args.outfolder, "tmp_seqs")
430 | dio_alis = os.path.join(args.outfolder, "tmp_alis")
431 | os.makedirs(dio_seqs, exist_ok = True)
432 | os.makedirs(dio_alis, exist_ok = True)
433 |
434 | fout_clusters = os.path.join(args.outfolder, "clusters.tsv")
435 | fout_seeds = os.path.join(args.outfolder, "seeds.txt")
436 | fout_identities = os.path.join(args.outfolder, "identities.tsv")
437 |
438 | if os.path.isfile(fout_clusters):
439 | logging.info("existing results detected - moving on")
440 | return()
441 |
442 | logging.info("reading core genome")
443 | core = read_genes(args.pangenome)
444 | fams = core["orthogroup"].unique()
445 | genomes = core["genome"].unique()
446 | logging.info(f"detected {len(fams)} orthogroups in "
447 | f"{len(genomes)} genomes")
448 |
449 | if args.max_genomes == 0:
450 | args.max_genomes = len(genomes)
451 | logging.info(f"max_genomes set to {args.max_genomes}")
452 |
453 | logging.info("removing same-genome copies of core genes")
454 | core = core.drop_duplicates(["genome", "orthogroup"], keep = False)
455 | fams = core["orthogroup"].unique() # in case some fams were fully removed
456 |
457 | if os.path.isdir(dio_seqs) and os.listdir(dio_seqs):
458 |
459 | logging.info("existing sequences detected - moving on")
460 |
461 | else:
462 |
463 | logging.info("gathering sequences of orthogroups")
464 | fins_faas = read_fastapaths(args.fasta_files)
465 | gather_orthogroup_sequences(core, fins_faas, dio_seqs)
466 |
467 | logging.info("creating database for alignments")
468 | for dir in ["sequenceDB", "logs"]:
469 | makedirs_smart(f"{dio_alis}/{dir}")
470 | fio_seqs = f"{dio_alis}/seqs.fasta"
471 | open(fio_seqs, "w").close()
472 | for fam in fams:
473 | with open(f"{dio_seqs}/{fam}.fasta", "r") as hin_fam:
474 | with open(fio_seqs, "a+") as hout_seqs:
475 | hout_seqs.write(hin_fam.read())
476 | run_mmseqs(["createdb", fio_seqs, f"{dio_alis}/sequenceDB/db"],
477 | f"{dio_alis}/logs/createdb.log", threads = args.threads)
478 | os.remove(fio_seqs)
479 |
480 | logging.info("initializing empty identity matrix")
481 | id_m = np.zeros([len(genomes), 0])
482 |
483 | logging.info("adding genomes until max_genomes or identity threshold is "
484 | "reached")
485 | core_grouped = core.copy().groupby("orthogroup")
486 | core_grouped = [core_fam for fam, core_fam in core_grouped]
487 | seeds = []
488 | while True:
489 |
490 | print("|", end = "", flush = True)
491 |
492 | # add column of zeros to identity matrix
493 | id_m = np.hstack((id_m, np.zeros([id_m.shape[0], 1])))
494 |
495 | # select seed
496 | max_ids = np.amax(id_m, 1) # max of each row = max along columns
497 | for seed in seeds: max_ids[seed] = 1.1 # avoid seeds being reused
498 | s = np.argmin(max_ids)
499 | seeds.append(s)
500 | min_max_ids = max_ids[s]
501 | seed_genome = genomes[s]
502 |
503 | # if sampled genomes close enough to each other: break the loop
504 | if min_max_ids > args.identity:
505 | print("")
506 | logging.info("identity threshold reached")
507 | # remove last column from identity matrix
508 | id_m = np.delete(id_m, -1, 1)
509 | seeds = seeds[:-1]
510 | break
511 |
512 | # prepare prefilter database
513 | for dir in ["prefDB", "alignmentDB"]:
514 | makedirs_smart(f"{dio_alis}/{dir}")
515 | pref = core_grouped.copy()
516 | for p, fam in enumerate(pref):
517 | if not seed_genome in fam.genome.tolist():
518 | pref[p] = None
519 | continue
520 | fam["query"] = fam[fam.genome == seed_genome].iloc[0]["gene"]
521 | pref = pd.concat(pref)
522 | pref = pref.rename(columns = {"gene": "target"})
523 | lookup = pd.read_csv(f"{dio_alis}/sequenceDB/db.lookup", sep = "\t",
524 | usecols = [0, 1], names = ["id", "sequence"])
525 | lookup = dict(zip(lookup["sequence"].tolist(), lookup["id"].tolist()))
526 | pref["query_id"] = [lookup[q] for q in pref["query"].tolist()]
527 | pref["target_id"] = [lookup[t] for t in pref["target"].tolist()]
528 | pref = pref[["query_id", "target_id"]]
529 | write_tsv(pref, f"{dio_alis}/pref.tsv")
530 | run_mmseqs(["tsv2db", f"{dio_alis}/pref.tsv", f"{dio_alis}/prefDB/db",
531 | "--output-dbtype", "7"], f"{dio_alis}/logs/tsv2db.log")
532 |
533 | # perform alignments
534 | run_mmseqs(["align", f"{dio_alis}/sequenceDB/db",
535 | f"{dio_alis}/sequenceDB/db", f"{dio_alis}/prefDB/db",
536 | f"{dio_alis}/alignmentDB/db", "--alignment-mode", str(ali_mode)],
537 | f"{dio_alis}/logs/align.log", threads = args.threads)
538 | run_mmseqs(["createtsv", f"{dio_alis}/sequenceDB/db",
539 | f"{dio_alis}/sequenceDB/db", f"{dio_alis}/alignmentDB/db",
540 | f"{dio_alis}/hits.tsv"], f"{dio_alis}/logs/createtsv.log")
541 |
542 | # parse alignment results
543 | hits = pd.read_csv(f"{dio_alis}/hits.tsv", sep = "\t",
544 | usecols = [1, 3], names = ["gene", "identity"])
545 | hits = core.merge(hits, on = "gene", how = "right")
546 | hits = hits.drop(["gene", "orthogroup"], axis = 1)
547 |
548 | # calculate mean/median identity with seed per genome
549 | if args.method == "median":
550 | ids = hits.groupby("genome").aggregate(median)
551 | elif args.method[:4] == "mean":
552 | p = args.method[4:]
553 | if (p == ""): p = "100"
554 | p = int(p) / 100
555 | def meanp(l, p):
556 | start = int(round(((1 - p) / 2) * len(l)))
557 | stop = int(round((1 - (1 - p) / 2) * len(l)))
558 | if start == stop: return(median(l))
559 | return(mean(sorted(l)[start:stop]))
560 | ids = hits.groupby("genome").aggregate(lambda l: meanp(l, p))
561 |
562 | # add mean/median identity to identity matrix
563 | for g, genome in enumerate(genomes):
564 | id_m[g, -1] = ids.loc[genome, "identity"]
565 |
566 | # if enough sampled genomes: break the loop
567 | if np.size(id_m, 1) == args.max_genomes:
568 | print("")
569 | logging.info("max number of genomes sampled")
570 | break
571 |
572 | logging.info("writing seeds.txt")
573 | with open(fout_seeds, "a") as hout_seeds:
574 | for s in seeds: hout_seeds.write(genomes[s] + "\n")
575 |
576 | logging.info("writing identities.tsv")
577 | id_df = pd.DataFrame(id_m)
578 | id_df.columns = [genomes[s] for s in seeds]
579 | id_df["genome"] = genomes
580 | cols = id_df.columns.tolist()
581 | cols = [cols[-1]] + cols[:-1]
582 | id_df = id_df[cols]
583 | id_df.to_csv(fout_identities, sep = "\t", index = False, header = True)
584 |
585 | logging.info("clustering the genomes")
586 | clusters = np.argmax(id_m, 1)
587 | genomes_clusters = pd.DataFrame({"genome": genomes, "cluster": clusters})
588 | logging.info(f"{len(set(clusters))} clusters found")
589 |
590 | logging.info("writing clusters.tsv")
591 | write_tsv(genomes_clusters, fout_clusters)
592 |
593 | logging.info("removing temporary folders")
594 | shutil.rmtree(dio_seqs)
595 | shutil.rmtree(dio_alis)
596 |
597 | def run_fetch(args):
598 |
599 | logging.info("creating subfolder for fastas")
600 | dout_seqs = os.path.join(args.outfolder, "fastas")
601 | os.makedirs(dout_seqs, exist_ok = True)
602 |
603 | logging.info("reading genes")
604 | genes = read_genes(args.pangenome)
605 | fams = genes["orthogroup"].unique()
606 | genomes = genes["genome"].unique()
607 | logging.info(f"detected {len(fams)} orthogroups in "
608 | f"{len(genomes)} genomes")
609 |
610 | logging.info("gathering sequences of orthogroups")
611 | fins_fastas = read_fastapaths(args.fasta_files)
612 | gather_orthogroup_sequences(genes, fins_fastas, dout_seqs)
613 |
614 | def run_core(args):
615 |
616 | fin_faapaths = args.faa_files
617 | dout = args.outfolder
618 | method = args.method
619 | min_reps = args.min_reps
620 | max_reps = args.max_reps
621 | max_align = args.max_align
622 | seeds = args.seeds
623 | core_prefilter = args.core_prefilter
624 | core_filter = args.core_filter
625 | max_cores = args.max_core_genes
626 | threads = args.threads
627 |
628 | # define paths
629 | dout_seedpan = os.path.join(dout, "seedpan")
630 | dout_seedcore = os.path.join(dout, "seedcore")
631 | fout_seedpaths = os.path.join(dout, "seedpaths.txt")
632 | fout_nonseedpaths = os.path.join(dout, "nonseedpaths.txt")
633 | fout_seedpan = os.path.join(dout_seedpan, "pangenome.tsv")
634 | fout_genes_core = os.path.join(dout_seedcore, "genes.tsv")
635 | fout_genes = os.path.join(dout, "genes.tsv")
636 |
637 | # make output subfolders
638 | for dir in [dout_seedpan, dout_seedcore]:
639 | os.makedirs(dir, exist_ok = True)
640 |
641 | logging.info("selecting random seed genomes")
642 | fins_faas = read_fastapaths(fin_faapaths)
643 | if not os.path.isfile(fout_seedpaths):
644 | fins_seeds = sample(fins_faas, seeds)
645 | fins_nonseeds = [fin for fin in fins_faas if not fin in fins_seeds]
646 | write_tsv(pd.DataFrame({"path": fins_seeds}), fout_seedpaths)
647 | write_tsv(pd.DataFrame({"path": fins_nonseeds}), fout_nonseedpaths)
648 |
649 | logging.info("STEP 1 - inferring pangenome of seed genomes")
650 | args_pan = Namespace(faa_files = fout_seedpaths, outfolder = dout_seedpan,
651 | method = method, min_reps = min_reps, max_reps = max_reps,
652 | max_align = max_align, threads = threads)
653 | run_pan(args_pan)
654 |
655 | logging.info("STEP 2 - building database of seed core genes and searching "
656 | "in seed faas")
657 | args_build = Namespace(faa_files = fout_seedpaths, pangenome = fout_seedpan,
658 | outfolder = dout_seedcore, core_prefilter = core_prefilter,
659 | core_filter = core_filter, max_core_genes = max_cores,
660 | threads = threads)
661 | run_build(args_build)
662 |
663 | if os.stat(fout_nonseedpaths).st_size == 0:
664 | logging.info("all faa files are seeds - skipping search in non-seeds")
665 | shutil.copy(fout_genes_core, fout_genes)
666 | return()
667 |
668 | logging.info("STEP 3 - identifying core orthogroups in non-seed genomes")
669 | args_search = Namespace(faa_files = fout_nonseedpaths, db = dout_seedcore,
670 | outfolder = dout, threads = threads)
671 | run_search(args_search)
672 |
673 | logging.info("adding search results in seeds to search results of "
674 | "non-seeds")
675 | with open(fout_genes, "a") as hout_genes:
676 | with open(fout_genes_core) as hout_genes_core:
677 | for line in hout_genes_core:
678 | hout_genes.write(line)
679 |
680 |
--------------------------------------------------------------------------------
/src/scarap/pan.py:
--------------------------------------------------------------------------------
1 | import collections
2 | import logging
3 | import numpy as np
4 | import os
5 | import shutil
6 | import sys
7 |
8 | from Bio import AlignIO, Align
9 | from copy import copy
10 | from ete3 import Tree
11 | from concurrent.futures import ProcessPoolExecutor
12 | from scipy import cluster
13 |
14 | from scarap.utils import *
15 | from scarap.readerswriters import *
16 | from scarap.computers import *
17 | from scarap.callers import *
18 |
19 | ## helpers - ficlin module (F)
20 |
21 | def update_seedmatrix(seedmatrix, sequences, dout_tmp, threads):
22 | """Updates the identity values in a seedmatrix.
23 |
24 | A seed matrix is a matrix where the rows represent genes, while the
25 | columns represent a subset of these genes ("seeds"). The cells contain
26 | sequence identity values of the genes to the seeds. This function will
27 | identify seeds that are no longer present in the set of genes (= seeds
28 | that don't have an identity value of one to at least one of the genes),
29 | and replace them with new seeds.
30 |
31 | Args:
32 | seedmatrix (np.array): An array of identity values of genes to seeds.
33 | sequences (list): A list of SeqRecords in the same order as the rows
34 | of the seedmatrix.
35 | dout_tmp (str): The path to a folder to store temporary files.
36 | threads (int): The number of threads to use.
37 |
38 | Returns:
39 | An updated seedmatrix.
40 | """
41 |
42 | # construct target and prefilter dbs
43 | makedirs_smart(f"{dout_tmp}")
44 | for dir in ["sequenceDB", "prefDB", "logs", "tmp"]:
45 | makedirs_smart(f"{dout_tmp}/{dir}")
46 | write_fasta(sequences, f"{dout_tmp}/seqs.fasta")
47 | run_mmseqs(["createdb", f"{dout_tmp}/seqs.fasta",
48 | f"{dout_tmp}/sequenceDB/db"], f"{dout_tmp}/logs/createdb.log",
49 | threads = threads)
50 | create_prefdb("../sequenceDB/db", f"{dout_tmp}/prefDB/db")
51 |
52 | # identify seeds (= columns) to replace
53 | replace = np.apply_along_axis(lambda l: all(l != 1), 0, seedmatrix)
54 | seedstoreplace = [i for i, r in enumerate(replace) if r]
55 | # logging.info(f"adding {len(seedstoreplace)} seeds")
56 |
57 | # update seed matrix with identity values
58 | genes = [seq.id for seq in sequences]
59 | lengths = [len(seq) for seq in sequences]
60 | for c in seedstoreplace:
61 |
62 | for dir in ["seedDB", "alignmentDB"]:
63 | makedirs_smart(f"{dout_tmp}/{dir}")
64 |
65 | # select longest next seed
66 | max_ids = np.amax(seedmatrix, 1) # max of each row = max along columns
67 | min_max_ids = np.amin(max_ids)
68 | cand_length = 0
69 | for i, s in enumerate(sequences):
70 | if max_ids[i] == min_max_ids and lengths[i] > cand_length:
71 | cand_length = lengths[i]
72 | seed = s
73 | seed_ix = i
74 |
75 | # create seed db
76 | write_fasta([seed], f"{dout_tmp}/seed.fasta")
77 | run_mmseqs(["createdb", f"{dout_tmp}/seed.fasta",
78 | f"{dout_tmp}/seedDB/db"], f"{dout_tmp}/logs/createseeddb.log",
79 | threads = threads)
80 |
81 | # run mmseqs align
82 | update_prefdb(f"{dout_tmp}/seedDB/db", f"{dout_tmp}/sequenceDB/db",
83 | f"{dout_tmp}/prefDB/db")
84 | run_mmseqs(["align", f"{dout_tmp}/seedDB/db",
85 | f"{dout_tmp}/sequenceDB/db", f"{dout_tmp}/prefDB/db",
86 | f"{dout_tmp}/alignmentDB/db", "--alignment-mode", "1"],
87 | f"{dout_tmp}/logs/search.log", threads = threads)
88 | run_mmseqs(["createtsv", f"{dout_tmp}/seedDB/db",
89 | f"{dout_tmp}/sequenceDB/db", f"{dout_tmp}/alignmentDB/db",
90 | f"{dout_tmp}/hits.tsv", "--full-header"],
91 | f"{dout_tmp}/logs/createtsv.log")
92 | hits_new = pd.read_csv(f"{dout_tmp}/hits.tsv", sep = "\t",
93 | usecols = [1, 3], names = ["gene", "identity"])
94 | hits_new["gene"] = hits_new["gene"].apply(lambda x: x.split(" ")[0])
95 |
96 | # put the identity values in the seed matrix
97 | for index, row in hits_new.iterrows():
98 | gene_ix = genes.index(row["gene"])
99 | seedmatrix[gene_ix, c] = row["identity"]
100 |
101 | # set identity of seed to itself to one
102 | # (mmseqs align estimates the identity values from the scores)
103 | seedmatrix[seed_ix, c] = 1
104 |
105 | # give warning if some sequences don't align to their cluster seed
106 | ids_to_seed = np.amax(seedmatrix, 1)
107 | if np.any(ids_to_seed == 0):
108 | logging.warning("ficlin: one or more sequences do not align to any "
109 | "seed")
110 |
111 | # remove temporary output folder
112 | shutil.rmtree(dout_tmp)
113 |
114 | return(seedmatrix)
115 |
116 | def run_ficlin(sequences, n_clusters, dout_tmp, threads):
117 | """Partitions sequences in a fixed number of clusters.
118 |
119 | Clusters a set of sequences into a fixed number of clusters in linear time
120 | and memory.
121 |
122 | Remark: this function hasn't been tested yet with multiple threads; I'm
123 | not sure if it can use them efficiently.
124 |
125 | Args:
126 | sequences (list): A list of SeqRecords to cluster.
127 | n_clusters (int): The number of clusters requested.
128 | dout_tmp (str): The path to a folder to store temporary files.
129 | threads (int): The number of threads to use.
130 |
131 | Returns:
132 | A list containing the cluster number for each sequence in sequences.
133 | """
134 |
135 | # initialize a seed matrix
136 | seedmatrix = np.zeros([len(sequences), n_clusters])
137 |
138 | # update the seedmatrix
139 | seedmatrix = update_seedmatrix(seedmatrix, sequences, dout_tmp, threads)
140 |
141 | # determine the cluster of each gene
142 | clusters = np.argmax(seedmatrix, 1)
143 |
144 | return(clusters)
145 |
146 | ## helpers - hierarchical clustering module (H)
147 |
148 | def hclusts(distmat, n_clusters):
149 |
150 | hclust = cluster.hierarchy.linkage(distmat, method = "average")
151 | clusters = cluster.hierarchy.cut_tree(hclust, n_clusters = n_clusters)
152 | clusters = [el[0] for el in clusters]
153 |
154 | return(clusters)
155 |
156 | ## helpers - tree inference module (T)
157 |
158 | def split_pan(pan, tree):
159 | """Split pan into pan1 and pan2 based on a tree and an outgroup node.
160 |
161 | Args:
162 | pan (DataFrame): A gene table with at least the columns reprf and
163 | orthogroup.
164 | tree: An ete3 tree (= the root node of a tree)
165 |
166 | Returns:
167 | [pan1, pan2, tree1, tree2]
168 | """
169 |
170 | # midpoint root the tree
171 | midoutgr = tree.get_midpoint_outgroup()
172 | if midoutgr != tree:
173 | tree.set_outgroup(midoutgr)
174 |
175 | # split tree at root
176 | tree1 = tree.children[0].copy()
177 | tree2 = tree.children[1].copy()
178 |
179 | # split pan
180 | reps_subfam1 = tree1.get_leaf_names()
181 | reps_subfam2 = tree2.get_leaf_names()
182 | pan1 = pan[pan["rep"].isin(reps_subfam1)].copy()
183 | pan2 = pan[pan["rep"].isin(reps_subfam2)].copy()
184 |
185 | # set subfamily names
186 | family = pan.orthogroup.tolist()[0]
187 | pan1.loc[:, "orthogroup"] = family + "_1"
188 | pan2.loc[:, "orthogroup"] = family + "_2"
189 |
190 | return([pan1, pan2, tree1, tree2])
191 |
192 | def lowest_cn_roots(tree, pan):
193 | """Determine the set of lowest copy-number roots.
194 |
195 | Args:
196 | tree: ete3 tree object where the leaf names correspond to the values of
197 | the reprf column in pan.
198 | pan (DataFrame): Table with at least the columns reprf and genome.
199 |
200 | Returns:
201 | A list with references to the nodes that would be minimal copy number
202 | roots.
203 | """
204 |
205 | # initialize list with reprfs and corresponding genomes
206 | reprfs_genomes = {}
207 | for index, row in pan.iterrows():
208 | reprfs_genomes.setdefault(row["reprf"], []).append(row["genome"])
209 | reprfs_genomes = list(map(list, reprfs_genomes.items()))
210 |
211 | roots = []
212 | min_av_cn = 100000000
213 |
214 | # loop over all nodes except the root
215 | for node in tree.iter_descendants():
216 | # initialize empty genome lists for partition 1 and 2
217 | genomes1 = []
218 | genomes2 = []
219 | # loop over list with reprfs and corresponding genomes
220 | for element in reprfs_genomes:
221 | reprf = element[0]
222 | genomes = element[1]
223 | # append genomes of reprf to correct partition
224 | if reprf in node:
225 | genomes1.extend(genomes)
226 | else:
227 | genomes2.extend(genomes)
228 | cn1 = collections.Counter(genomes1).values()
229 | cn2 = collections.Counter(genomes2).values()
230 | av_cn = (sum(cn1) + sum(cn2)) / (len(cn1) + len(cn2))
231 | if av_cn < min_av_cn:
232 | roots = [node]
233 | min_av_cn = av_cn
234 | elif av_cn == min_av_cn:
235 | roots.append(node)
236 |
237 | return(roots)
238 |
239 | def partition_genomes(reprfs_genomes, node):
240 | """Split genomes into two partitions using a tree.
241 |
242 | Split genomes into two partitions based on their presence/absence in a
243 | phylogenetic tree.
244 |
245 | Args:
246 | reprfs_genomes (list): List where each element is a list with two
247 | elements: a representative gene (reprf) and a list with the
248 | genomes of all genes represented by reprf.
249 | node: An ete3 node (= tree) object.
250 |
251 | Returns:
252 | A list with the genomes of the genes in the first partition.
253 | A list with the gneomes of the genes in the second partition.
254 | """
255 | # initialize empty genome lists for partition 1 and 2
256 | genomes1 = []
257 | genomes2 = []
258 | # loop over list with reprfs and corresponding genomes
259 | for element in reprfs_genomes:
260 | reprf = element[0]
261 | genomes = element[1]
262 | # append genomes of reprf to correct partition
263 | if reprf in node:
264 | genomes1.extend(genomes)
265 | else:
266 | genomes2.extend(genomes)
267 | return(genomes1, genomes2)
268 |
269 | def correct_root(root, tree, pan):
270 | """Correct the root of a phylogenetic tree.
271 |
272 | Correct the root of a tree by selecting the root that shows the lowest
273 | average copy number across both sides of the corresponding bipartion,
274 | while satisfying the restriction that all genomes present in both sides of
275 | the original bipartion (= genome overlap) are also in the genome overlap
276 | of the selected node.
277 |
278 | Args:
279 | root: An ete3 node (= tree) that is present in tree.
280 | tree: An ete3 node (= tree).
281 | pan: A table with at least the columns reprf (corresponding to the tips
282 | of tree) and genome.
283 |
284 | Returns:
285 | An ete3 node representing an outgroup to the corrected root.
286 | """
287 |
288 | # initialize list with reprfs and corresponding genomes
289 | reprfs_genomes = {}
290 | for index, row in pan.iterrows():
291 | reprfs_genomes.setdefault(row["reprf"], []).append(row["genome"])
292 | reprfs_genomes = list(map(list, reprfs_genomes.items()))
293 |
294 | genomes1, genomes2 = partition_genomes(reprfs_genomes, root)
295 | midpoint_overlap = set(genomes1) & set(genomes2) # intersection
296 |
297 | roots = []
298 | min_av_cn = 100000000
299 |
300 | # loop over all nodes except the root
301 | for node in tree.iter_descendants():
302 | genomes1, genomes2 = partition_genomes(reprfs_genomes, node)
303 | overlap = set(genomes1) & set(genomes2) # intersection
304 | # if genomes that overlap in the midpoint bipartition do not all
305 | # overlap in this partition --> split
306 | if not midpoint_overlap.issubset(overlap):
307 | continue
308 | cn1 = collections.Counter(genomes1).values()
309 | cn2 = collections.Counter(genomes2).values()
310 | av_cn = (sum(cn1) + sum(cn2)) / (len(cn1) + len(cn2))
311 | if av_cn < min_av_cn:
312 | roots = [node]
313 | min_av_cn = av_cn
314 | # logging.info(f"new min av cn: {min_av_cn}")
315 | elif av_cn == min_av_cn:
316 | roots.append(node)
317 |
318 | fam = pan.orthogroup[0]
319 |
320 | if root in roots:
321 | cnoutgr = root
322 | # logging.info(f"{fam}: cn root is midpoint root")
323 | else:
324 | cnoutgr = roots[0]
325 | # logging.info(f"{fam}: cn root is not midpoint root")
326 |
327 | return(cnoutgr)
328 |
329 | ## general helpers
330 |
331 | def select_reps(genes, clusters, sequences):
332 | """Select representative sequences for a set of clusters.
333 |
334 | For each cluster, selects a sequence with median length as its
335 | representative.
336 |
337 | Args:
338 | genes (list): A list of gene names.
339 | clusters (list): A list of cluster ids in the same order as genes.
340 | sequences (list): A list of SeqRecords containing at least the
341 | sequences of all genes; the order doesn't matter.
342 |
343 | Returns:
344 | A DataFrame with the columns gene and rep.
345 | """
346 | genes = pd.DataFrame({"gene": genes, "cluster": clusters})
347 | n_genes = len(genes.index)
348 | # add sequences to gene table without changing order
349 | genes_seqs = pd.DataFrame({"gene": [s.id for s in sequences],
350 | "sequence": sequences})
351 | genes = genes.merge(genes_seqs, on = "gene", how = "left")
352 | if (genes.sequence.isnull().values.any()):
353 | logging.error("select_reps: not all sequences were given")
354 | # the following doesn't change the order of the rows
355 | genes["rep"] = genes.groupby("cluster")["sequence"].\
356 | transform(lambda x: select_representative(x.tolist()).id)
357 | return(genes.rep.tolist())
358 |
359 | def assess_split(pan1, pan2, family):
360 | """Assess whether a family should be split into two subfamilies.
361 |
362 | Remark: technically, this function only needs [genomes1, genomes2].
363 | However, extracting these from [pan1, pan2] is included here to avoid
364 | repeating this code in each split_family_recursive_STR function. The family
365 | argument is needed for logging.
366 |
367 | Args:
368 | pan1 (DataFrame): Gene table for the first subfamily, with the column
369 | genome.
370 | pan2 (DataFrame): Gene table for the second subfamily, with the column
371 | genome.
372 | family (str): Name of the gene family.
373 |
374 | Returns:
375 | True/False value indicating whether the split should happen.
376 | """
377 | genomes1 = pan1["genome"].tolist()
378 | genomes2 = pan2["genome"].tolist()
379 | pgo_obs = calc_pgo(genomes1, genomes2)
380 | pgo_exp = pred_pgo(genomes1, genomes2)
381 | split = pgo_obs >= pgo_exp and not pgo_exp == 0
382 | genomes = genomes1 + genomes2
383 | cns = pd.Series(genomes).value_counts().tolist()
384 | if all([cn > 10 for cn in cns]) and not split:
385 | logging.warning(f"{family}: all copy-numbers > 10 but no split")
386 | # logging.info(f"subfam1: {pan1.index.tolist()}")
387 | # logging.info(f"subfam2: {pan2.index.tolist()}")
388 | # n = len(set(genomes))
389 | # logging.info(f"{family}: {n} genomes; copy-number {min(cns)} - "
390 | # f"{max(cns)}; pgo_obs = {pgo_obs:.3f}; pgo_exp = {pgo_exp:.3f}; "
391 | # f"split = {split}")
392 | return(split)
393 |
394 | ## family splitting functions
395 |
396 | def split_family_H_nl(pan, sequences, threads, dio_tmp):
397 | """Splits a family in two subfamilies.
398 |
399 | See split_family_recursive_H_nl.
400 | """
401 | write_fasta(sequences, f"{dio_tmp}/seqs.fasta")
402 | run_mafft(f"{dio_tmp}/seqs.fasta", f"{dio_tmp}/seqs.aln", threads)
403 | with open(f"{dio_tmp}/seqs.aln", "r") as fin:
404 | aln = AlignIO.read(fin, "fasta")
405 | n = len(aln)
406 | im = identity_matrix(aln)
407 | dm = []
408 | for r in range(n - 1):
409 | for c in range(r + 1, n):
410 | dm.append(1 - im[r, c])
411 | link = cluster.hierarchy.linkage(dm, method = "average")
412 | clusters = cluster.hierarchy.cut_tree(link, n_clusters = 2)
413 | genes_subfam1 = [seq.id for seq, cl in zip(aln, clusters) if cl[0] == 0]
414 | genes_subfam2 = [seq.id for seq, cl in zip(aln, clusters) if cl[0] == 1]
415 | pan1 = pan.loc[genes_subfam1].copy()
416 | pan2 = pan.loc[genes_subfam2].copy()
417 | family = pan.orthogroup.tolist()[0]
418 | pan1.loc[:, "orthogroup"] = family + "_1"
419 | pan2.loc[:, "orthogroup"] = family + "_2"
420 | return([pan1, pan2])
421 |
422 | def split_family_T_nl(pan, sequences, threads, dio_tmp):
423 | """Splits a family in two subfamilies.
424 |
425 | See split_family_recursive_T_nl.
426 | """
427 | write_fasta(sequences, f"{dio_tmp}/seqs.fasta")
428 | run_mafft(f"{dio_tmp}/seqs.fasta", f"{dio_tmp}/seqs.aln", threads)
429 | run_iqtree(f"{dio_tmp}/seqs.aln", f"{dio_tmp}/tree", threads,
430 | ["-m", "LG+F+G4"])
431 | tree = Tree(f"{dio_tmp}/tree/tree.treefile")
432 | midoutgr = tree.get_midpoint_outgroup()
433 | genes_subfam1 = midoutgr.get_leaf_names()
434 | midoutgr.detach()
435 | genes_subfam2 = tree.get_leaf_names()
436 | pan1 = pan.loc[genes_subfam1].copy()
437 | pan2 = pan.loc[genes_subfam2].copy()
438 | family = pan.orthogroup.tolist()[0]
439 | pan1.loc[:, "orthogroup"] = family + "_1"
440 | pan2.loc[:, "orthogroup"] = family + "_2"
441 | return([pan1, pan2])
442 |
443 | def split_family_FH(pan, sequences, hclust, ficlin, min_reps, max_reps,
444 | max_align, seedmatrix, threads, dio_tmp):
445 | """Splits a family in two subfamilies.
446 |
447 | See split_family_recursive_FH.
448 | """
449 |
450 | # determine necessary steps
451 | n_seqs = len(pan.index)
452 | n_reps = 0 if hclust is None else hclust.get_count()
453 | if ficlin and (n_reps >= min_reps or n_reps == n_seqs):
454 | update_reps = False
455 | cluster_reps = False
456 | elif ficlin and n_seqs > max_align:
457 | update_reps = True
458 | cluster_reps = True
459 | else:
460 | pan["rep"] = pan.index # all seqs become reps
461 | update_reps = False
462 | cluster_reps = True
463 |
464 | # STEP 1: UPDATE REPRESENTATIVES
465 |
466 | if update_reps:
467 |
468 | seedmatrix = update_seedmatrix(seedmatrix, sequences,
469 | f"{dio_tmp}/ficlin", threads)
470 | linclusters = np.argmax(seedmatrix, 1)
471 | # return emptiness if all sequences map to the same seed
472 | if (len(set(linclusters))) == 1:
473 | return([None] * 8)
474 | pan["rep"] = select_reps(pan.index.tolist(), linclusters, sequences)
475 |
476 | # STEP 2: CLUSTER REPRESENTATIVES
477 |
478 | if cluster_reps:
479 |
480 | repseqs = [s for s in sequences if s.id in pan["rep"].unique()]
481 | reps = [s.id for s in repseqs]
482 | # logging.info(f"aligning {len(reps)} sequences")
483 | write_fasta(repseqs, f"{dio_tmp}/repseqs.fasta")
484 | run_mafft(f"{dio_tmp}/repseqs.fasta", f"{dio_tmp}/repseqs.aln",
485 | threads, ["--amino", "--anysymbol"])
486 | aln = read_fasta(f"{dio_tmp}/repseqs.aln")
487 | idmat = identity_matrix(aln)
488 | distmat = distmat_from_idmat(idmat)
489 | hclust = cluster.hierarchy.linkage(distmat, method = "average")
490 | hclust = cluster.hierarchy.to_tree(hclust)
491 | for leaf in hclust.pre_order(lambda x: x):
492 | leaf.id = reps[leaf.id]
493 |
494 | # STEP 3: SPLIT DATA IN SUBFAMILIES
495 |
496 | # split hclust
497 | hclust1 = hclust.get_left()
498 | hclust2 = hclust.get_right()
499 |
500 | # split pan
501 | reps1 = hclust1.pre_order(lambda x: x.id)
502 | reps2 = hclust2.pre_order(lambda x: x.id)
503 | pan1 = pan[pan["rep"].isin(reps1)].copy()
504 | pan2 = pan[pan["rep"].isin(reps2)].copy()
505 | family = pan.orthogroup.tolist()[0]
506 | pan1.loc[:, "orthogroup"] = family + "_1"
507 | pan2.loc[:, "orthogroup"] = family + "_2"
508 |
509 | # split sequences
510 | sequences1 = [s for s in sequences if s.id in pan1.index]
511 | sequences2 = [s for s in sequences if s.id in pan2.index]
512 |
513 | # split seedmatrix
514 | if ficlin:
515 | seedmatrix1 = seedmatrix[pan["rep"].isin(reps1).tolist(), :]
516 | seedmatrix2 = seedmatrix[pan["rep"].isin(reps2).tolist(), :]
517 | else:
518 | seedmatrix1 = None
519 | seedmatrix2 = None
520 |
521 | return([pan1, pan2, sequences1, sequences2, hclust1, hclust2, seedmatrix1,
522 | seedmatrix2])
523 |
524 | def split_family_FT(pan, sequences, tree, ficlin, min_reps, max_reps,
525 | seedmatrix, threads, dio_tmp):
526 | """Splits a family in two subfamilies.
527 |
528 | See split_family_recursive_FT.
529 | """
530 |
531 | update_tree = False
532 | # if reps not necessary, for the first time: ...
533 | if not ficlin or len(pan.index) <= max_reps:
534 | if tree is None or len(tree) != len(pan.index):
535 | pan["rep"] = pan.index
536 | update_tree = True
537 | # if parent reps are too few to re-use: ...
538 | else:
539 | n_reps = len(pan["rep"].unique())
540 | if n_reps < min_reps:
541 | seedmatrix = update_seedmatrix(seedmatrix, sequences,
542 | f"{dio_tmp}/ficlin", threads)
543 | linclusters = np.argmax(seedmatrix, 1)
544 | # return emptiness if all sequences map to the same seed
545 | if (len(set(linclusters))) == 1:
546 | return([None] * 8)
547 | pan["rep"] = select_reps(pan.index.tolist(), linclusters, sequences)
548 | update_tree = True
549 |
550 | # update tree if requested, otherwise use parent tree
551 | if update_tree:
552 | repseqs = [s for s in sequences if s.id in pan["rep"].unique()]
553 | reps = [s.id for s in repseqs]
554 | # logging.info(f"aligning {len(reps)} sequences")
555 | write_fasta(repseqs, f"{dio_tmp}/repseqs.fasta")
556 | run_mafft(f"{dio_tmp}/repseqs.fasta", f"{dio_tmp}/repseqs.aln",
557 | threads, ["--amino"])
558 | run_iqtree(f"{dio_tmp}/repseqs.aln", f"{dio_tmp}/tree", threads,
559 | ["-m", "LG"])
560 | tree = Tree(f"{dio_tmp}/tree/tree.treefile")
561 |
562 | # split pan based on midpoint root
563 | pan1, pan2, tree1, tree2 = split_pan(pan, tree)
564 | sequences1 = [s for s in sequences if s.id in pan1.index]
565 | sequences2 = [s for s in sequences if s.id in pan2.index]
566 | if ficlin:
567 | seedmatrix1 = seedmatrix[pan.index.isin(pan1.index).tolist(), :]
568 | seedmatrix2 = seedmatrix[pan.index.isin(pan2.index).tolist(), :]
569 | else:
570 | seedmatrix1 = None
571 | seedmatrix2 = None
572 |
573 | # # split pan based on minimal copy number root
574 | # cnoutgr = correct_root(midoutgr, tree, pan)
575 | # pan_cn1, pan_cn2 = split_pan(pan, tree, cnoutgr)
576 |
577 | # give the subfamilies names
578 | family = pan.orthogroup.tolist()[0]
579 | pan1.loc[:, "orthogroup"] = family + "_1"
580 | pan2.loc[:, "orthogroup"] = family + "_2"
581 |
582 | return([pan1, pan2, sequences1, sequences2, tree1, tree2, seedmatrix1,
583 | seedmatrix2])
584 |
585 | def split_family_P(pan, sequences, threads, dio_tmp):
586 | """Splits a family in two subfamilies.
587 |
588 | See split_family_recursive_P.
589 | """
590 |
591 | report = False
592 |
593 | # align sequences
594 | write_fasta(sequences, f"{dio_tmp}/seqs.fasta")
595 | run_mafft(f"{dio_tmp}/seqs.fasta", f"{dio_tmp}/seqs.aln", threads)
596 |
597 | # create sequence database
598 | for dir in ["sequenceDB", "tmp", "resultDB", "logs"]:
599 | makedirs_smart(f"{dio_tmp}/{dir}")
600 | run_mmseqs(["createdb", f"{dio_tmp}/seqs.fasta",
601 | f"{dio_tmp}/sequenceDB/db"], f"{dio_tmp}/logs/createdb.log")
602 |
603 | # initialize subfamilies
604 | with open(f"{dio_tmp}/seqs.aln", "r") as fin:
605 | aln = AlignIO.read(fin, "fasta")
606 | genes = pd.DataFrame({"gene": [seq.id for seq in aln],
607 | "profile": ["profile2"] * len(aln)})
608 | repr = select_representative(aln)
609 | if report: print(repr.id)
610 | genes.loc[genes.gene == repr.id, "profile"] = "profile1"
611 | genes_profile1 = genes.loc[genes["profile"] == "profile1", "gene"].tolist()
612 |
613 | # update profiles
614 | for i in range(5):
615 | if report: print(f"iteration {i}")
616 | for dir in ["msaDB", "profileDB", "searchDB", "tmp"]:
617 | makedirs_smart(f"{dio_tmp}/{dir}")
618 | open(f"{dio_tmp}/profiles.sto", "w").close()
619 | for profile, profilegenes in genes.groupby("profile"):
620 | records = [copy(rec) for rec in aln if rec.id in \
621 | profilegenes.gene.tolist()]
622 | # mmseqs takes id of first sequence in alignment as profile name
623 | records[0].id = profile
624 | aln_sub = Align.MultipleSeqAlignment(records)
625 | with open(f"{dio_tmp}/profiles.sto", "a") as hout:
626 | AlignIO.write(aln_sub, hout, "stockholm")
627 | run_mmseqs(["convertmsa", f"{dio_tmp}/profiles.sto",
628 | f"{dio_tmp}/msaDB/db"], f"{dio_tmp}/logs/convertmsa.log")
629 | run_mmseqs(["msa2profile", f"{dio_tmp}/msaDB/db",
630 | f"{dio_tmp}/profileDB/db", "--match-mode", "1",
631 | "--filter-msa", "1", "--diff", "1000", "--qsc", "-50",
632 | "--match-ratio", "0.5"], f"{dio_tmp}/logs/msa2profile.log")
633 | run_mmseqs(["search", f"{dio_tmp}/profileDB/db",
634 | f"{dio_tmp}/sequenceDB/db", f"{dio_tmp}/searchDB/db",
635 | f"{dio_tmp}/tmp", "--max-seqs", "1000000", "-s", "7.5"],
636 | f"{dio_tmp}/logs/search.log")
637 | run_mmseqs(["convertalis", f"{dio_tmp}/profileDB/db",
638 | f"{dio_tmp}/sequenceDB/db", f"{dio_tmp}/searchDB/db",
639 | f"{dio_tmp}/results.tsv"], f"{dio_tmp}/logs/convertalis.log")
640 | hits = read_mmseqs_table(f"{dio_tmp}/results.tsv")
641 | hits = hits.sort_values("pident", ascending = False)
642 | hits = hits.reset_index(drop = True)
643 | hits = hits.drop_duplicates(["target"])
644 | genes = hits.iloc[:, [0, 1]].copy()
645 | genes = genes.rename(columns = {"query": "profile", "target": "gene"})
646 | genes_profile1_new = \
647 | genes.loc[genes["profile"] == "profile1", "gene"].tolist()
648 | n_diff = len(set(genes_profile1) ^ set(genes_profile1_new))
649 | if report: print(f"difference in profile1: {n_diff}")
650 | genes_profile1 = genes_profile1_new
651 | if report: print(f"number of genes in profile1: {len(genes_profile1)}")
652 | if n_diff == 0: break
653 | if len(genes_profile1) in [len(genes.index), 0]: break
654 |
655 | genes_profile2 = [seq.id for seq in aln if not seq.id in genes_profile1]
656 | pan1 = pan.loc[genes_profile1].copy()
657 | pan2 = pan.loc[genes_profile2].copy()
658 | family = pan.orthogroup.tolist()[0]
659 | pan1.loc[:, "orthogroup"] = family + "_1"
660 | pan2.loc[:, "orthogroup"] = family + "_2"
661 |
662 | return([pan1, pan2])
663 |
664 | ## recursive family splitting functions
665 |
666 | def split_family_recursive_H_nl(pan, sequences, threads, dio_tmp):
667 | """Splits up a gene family using the H_nl strategy.
668 |
669 | Args:
670 | pan (DataFrame): A gene table for a single gene family, with the
671 | columns gene, genome and orthogroup.
672 | sequences (list): A list with one SeqRecord object per row in pan.
673 | threads (int): The number of threads to use.
674 | dio_tmp (str): Folder to store temporary files.
675 |
676 | Returns:
677 | An pan object where the orthogroup column has been updated.
678 | """
679 |
680 | family = pan.orthogroup.tolist()[0]
681 |
682 | if not split_possible(pan.genome.tolist()):
683 | # logging.info(f"{family}: {len(pan.index)} genes - split not an option")
684 | return(pan)
685 |
686 | pan1, pan2 = split_family_H_nl(pan, sequences, threads, dio_tmp)
687 | split = assess_split(pan1, pan2, family)
688 |
689 | if split:
690 |
691 | genes1 = pan1.index.tolist()
692 | genes2 = pan2.index.tolist()
693 | sequences1 = [seq for seq in sequences if seq.id in genes1]
694 | sequences2 = [seq for seq in sequences if seq.id in genes2]
695 | pan1 = split_family_recursive_H_nl(pan1, sequences1, threads, dio_tmp)
696 | pan2 = split_family_recursive_H_nl(pan2, sequences2, threads, dio_tmp)
697 | pan = pd.concat([pan1, pan2])
698 |
699 | return(pan)
700 |
701 | def split_family_recursive_T_nl(pan, sequences, threads, dio_tmp):
702 | """Splits up a gene family using the T-nl strategy.
703 |
704 | Args:
705 | pan (DataFrame): A gene table for a single gene family, with the
706 | columns gene, genome and orthogroup.
707 | sequences (list): A list with one SeqRecord object per row in pan.
708 | threads (int): The number of threads to use.
709 | dio_tmp (str): Folder to store temporary files.
710 |
711 | Returns:
712 | An pan object where the orthogroup column has been updated.
713 | """
714 |
715 | family = pan.orthogroup.tolist()[0]
716 |
717 | if not split_possible(pan.genome.tolist()):
718 | # logging.info(f"{family}: {len(pan.index)} genes - split not an option")
719 | return(pan)
720 |
721 | pan1, pan2 = split_family_T_nl(pan, sequences, threads, dio_tmp)
722 | split = assess_split(pan1, pan2, family)
723 |
724 | if split:
725 |
726 | genes1 = pan1.index.tolist()
727 | genes2 = pan2.index.tolist()
728 | sequences1 = [seq for seq in sequences if seq.id in genes1]
729 | sequences2 = [seq for seq in sequences if seq.id in genes2]
730 | pan1 = split_family_recursive_T_nl(pan1, sequences1, threads, dio_tmp)
731 | pan2 = split_family_recursive_T_nl(pan2, sequences2, threads, dio_tmp)
732 | pan = pd.concat([pan1, pan2])
733 |
734 | return(pan)
735 |
736 | def split_family_recursive_FH(pan, sequences, hclust, ficlin, min_reps,
737 | max_reps, max_align, seedmatrix, threads, dio_tmp):
738 | """Splits up a gene family using the H or FH strategy.
739 |
740 | See [https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.\
741 | hierarchy.to_tree.html#scipy.cluster.hierarchy.to_tree].
742 |
743 | Args:
744 | pan (DataFrame): A gene table for a single gene family, with the
745 | columns gene, genome and orthogroup.
746 | sequences (list): A list with one SeqRecord object per row in pan, in
747 | the same order.
748 | hclust: An hclust object from scipy.hierarchy.cluster in the form of a
749 | tree; the tip ids should be gene names.
750 | finclin (bool): Should ficlin be used to pick representatives?
751 | min_reps (int): The minimum number of representatives to use.
752 | max_reps (int): The maximum number of representatives to use.
753 | seedmatrix (np.array): An array of identity values of genes to seeds.
754 | threads (int): The number of threads to use.
755 | dio_tmp (str): Folder to store temporary files.
756 |
757 | Returns:
758 | An pan object where the orthogroup column has been updated.
759 | """
760 |
761 | family = pan.orthogroup.tolist()[0]
762 |
763 | if not split_possible(pan.genome.tolist()):
764 | # logging.info(f"{family}: {len(pan.index)} genes - split not an option")
765 | return(pan)
766 |
767 | pan1, pan2, sequences1, sequences2, hclust1, hclust2, seedmatrix1, \
768 | seedmatrix2 = split_family_FH(pan, sequences, hclust, ficlin, min_reps,
769 | max_reps, max_align, seedmatrix, threads, dio_tmp)
770 | if pan1 is None:
771 | split = False # don't split if all sequences are identical
772 | else:
773 | split = assess_split(pan1, pan2, family)
774 |
775 | if split:
776 |
777 | pan1 = split_family_recursive_FH(pan1, sequences1, hclust1, ficlin,
778 | min_reps, max_reps, max_align, seedmatrix1, threads, dio_tmp)
779 | pan2 = split_family_recursive_FH(pan2, sequences2, hclust2, ficlin,
780 | min_reps, max_reps, max_align, seedmatrix2, threads, dio_tmp)
781 | pan = pd.concat([pan1, pan2])
782 |
783 | return(pan)
784 |
785 | def split_family_recursive_FT(pan, sequences, tree, ficlin, min_reps,
786 | max_reps, seedmatrix, threads, dio_tmp):
787 | """Splits up a gene family using the T or FT strategy.
788 |
789 | Args:
790 | pan (DataFrame): A gene table for a single gene family, with the
791 | columns gene, genome and orthogroup.
792 | sequences (list): A list with one SeqRecord object per row in pan, in
793 | the same order.
794 | tree: An ete3 tree object.
795 | finclin (bool): Should ficlin be used to pick representatives?
796 | min_reps (int): The minimum number of representatives to use.
797 | max_reps (int): The maximum number of representatives to use.
798 | seedmatrix (np.array): An array of identity values of genes to seeds.
799 | threads (int): The number of threads to use.
800 | dio_tmp (str): Folder to store temporary files.
801 |
802 | Returns:
803 | An pan object where the orthogroup column has been updated.
804 | """
805 |
806 | family = pan.orthogroup.tolist()[0]
807 |
808 | if not split_possible(pan.genome.tolist()):
809 | # logging.info(f"{family}: {len(pan.index)} genes - split not an option")
810 | return(pan)
811 |
812 | pan1, pan2, sequences1, sequences2, tree1, tree2, seedmatrix1, \
813 | seedmatrix2 = split_family_FT(pan, sequences, tree, ficlin, min_reps,
814 | max_reps, seedmatrix, threads, dio_tmp)
815 | if pan1 is None:
816 | split = False # don't split if all sequences are identical
817 | else:
818 | split = assess_split(pan1, pan2, family)
819 |
820 | if split:
821 |
822 | pan1 = split_family_recursive_FT(pan1, sequences1, tree1, ficlin,
823 | min_reps, max_reps, seedmatrix1, threads, dio_tmp)
824 | pan2 = split_family_recursive_FT(pan2, sequences2, tree2, ficlin,
825 | min_reps, max_reps, seedmatrix2, threads, dio_tmp)
826 | pan = pd.concat([pan1, pan2])
827 |
828 | return(pan)
829 |
830 | def split_family_recursive_P(pan, sequences, threads, dio_tmp):
831 | """Splits up a gene family using the P strategy.
832 |
833 | Args:
834 | pan (DataFrame): A gene table for a single gene family, with the
835 | columns gene, genome and orthogroup.
836 | sequences (list): A list with one SeqRecord object per row in pan.
837 | threads (int): The number of threads to use.
838 | dio_tmp (str): Folder to store temporary files.
839 |
840 | Returns:
841 | An pan object where the orthogroup column has been updated.
842 | """
843 |
844 | family = pan.orthogroup.tolist()[0]
845 |
846 | if not split_possible(pan.genome.tolist()):
847 | # logging.info(f"{family}: {len(pan.index)} genes - split not an option")
848 | return(pan)
849 |
850 | pan1, pan2 = split_family_P(pan, sequences, threads, dio_tmp)
851 | split = assess_split(pan1, pan2, family)
852 |
853 | if split:
854 |
855 | genes1 = pan1.index.tolist()
856 | genes2 = pan2.index.tolist()
857 | sequences1 = [seq for seq in sequences if seq.id in genes1]
858 | sequences2 = [seq for seq in sequences if seq.id in genes2]
859 | pan1 = split_family_recursive_P(pan1, sequences1, threads, dio_tmp)
860 | pan2 = split_family_recursive_P(pan2, sequences2, threads, dio_tmp)
861 | pan = pd.concat([pan1, pan2])
862 |
863 | return(pan)
864 |
865 | ## top-level functions
866 |
867 | def split_superfamily(pan, strategy, din_fastas, min_reps, max_reps, max_align,
868 | threads, dio_tmp):
869 | """Splits a gene superfamily in a set of gene families.
870 |
871 | Args:
872 | pan (Data Frame): Table with columns gene, genome and orthogroup
873 | for the genes or a single gene family.
874 | strategy (str): Splitting strategy. [H-nl, T-nl, H, LH, HT, LHT, P]
875 | din_fastas (str): Input folder with fasta file of gene family.
876 | threads (int): Number of threads to use.
877 | dio_tmp (str): Folder to store temporary files.
878 |
879 | Returns:
880 | A pandas Data Frame with the pangenome, where the orthogroup column has
881 | been updated to reflect the gene families.
882 | """
883 |
884 | superfam = pan.orthogroup.tolist()[0]
885 | pan = pan.set_index("gene")
886 | dio_tmp = f"{dio_tmp}/{superfam}"
887 | makedirs_smart(dio_tmp)
888 |
889 | if strategy == "H-nl":
890 | sequences = read_fasta(f"{din_fastas}/{superfam}.fasta")
891 | pan = split_family_recursive_H_nl(pan, sequences, threads, dio_tmp)
892 | elif strategy == "T-nl":
893 | sequences = read_fasta(f"{din_fastas}/{superfam}.fasta")
894 | pan = split_family_recursive_T_nl(pan, sequences, threads, dio_tmp)
895 | elif strategy in ["H", "FH", "T", "FT"]:
896 | ficlin = "F" in strategy
897 | sequences = read_fasta(f"{din_fastas}/{superfam}.fasta")
898 | genes = pan.index.tolist()
899 | sequences.sort(key = lambda s: genes.index(s.id))
900 | pan["rep"] = "c"
901 | if "F" in strategy:
902 | seedmatrix = np.zeros([len(sequences), max_reps])
903 | else:
904 | seedmatrix = None
905 | if "H" in strategy:
906 | pan = split_family_recursive_FH(pan, sequences, None, ficlin,
907 | min_reps, max_reps, max_align, seedmatrix, threads, dio_tmp)
908 | else:
909 | pan = split_family_recursive_FT(pan, sequences, None, ficlin,
910 | min_reps, max_reps, seedmatrix, threads, dio_tmp)
911 | pan = pan[["genome", "orthogroup"]] # remark: "gene" is the index
912 | elif strategy == "P":
913 | sequences = read_fasta(f"{din_fastas}/{superfam}.fasta")
914 | pan = split_family_recursive_P(pan, sequences, threads, dio_tmp)
915 | else:
916 | logging.error("pangenome strategy unknown")
917 |
918 | pan = pan.reset_index()
919 | shutil.rmtree(dio_tmp)
920 |
921 | print("|", end = "", flush = True)
922 | return(pan)
923 |
924 | def infer_superfamilies(faafins, dout, threads):
925 | """Infers superfamilies of a set of faa files.
926 |
927 | Remarks: the pangenome with the superfamilies is written out to
928 | f"{dout}/pangenome.tsv".
929 |
930 | Args:
931 | faafins (list): Paths to .faa fasta files, one per genome.
932 | dout (str): Output folder for the pangenome with the superfamilies.
933 | threads (int): Number of threads to use.
934 | """
935 |
936 | threads = str(threads)
937 |
938 | # create output subfolders
939 | logging.info("creating subfolders for superfamily inference steps")
940 | for folder in ["logs", "sequenceDB", "preclusterDB", "profileDB",
941 | "alignmentDB", "clusterDB", "tmp"]:
942 | os.makedirs(f"{dout}/{folder}", exist_ok = True)
943 |
944 | # create mmseqs sequence database
945 | logging.info("creating mmseqs sequence database")
946 | run_mmseqs(["createdb"] + faafins + [f"{dout}/sequenceDB/db"],
947 | f"{dout}/logs/createdb.log")
948 |
949 | # create preclusters with mmseqs cluster module (includes mmseqs linclust)
950 | logging.info("creating preclusters")
951 | run_mmseqs(["cluster", f"{dout}/sequenceDB/db", f"{dout}/preclusterDB/db",
952 | f"{dout}/tmp", "--max-seqs", "1000000", "-c", "0.5", "--cov-mode", "0",
953 | "-e", "inf", "--min-seq-id", "0.2", "--cluster-mode", "0"],
954 | f"{dout}/logs/cluster.log",
955 | skip_if_exists = f"{dout}/preclusterDB/db.index", threads = threads)
956 |
957 | # cluster the preclusters into the final clusters
958 | logging.info("clustering the preclusters using profiles")
959 | run_mmseqs(["result2profile", f"{dout}/sequenceDB/db",
960 | f"{dout}/sequenceDB/db", f"{dout}/preclusterDB/db",
961 | f"{dout}/profileDB/db"], f"{dout}/logs/result2profile.log",
962 | skip_if_exists = f"{dout}/profileDB/db.index", threads = threads)
963 | run_mmseqs(["profile2consensus", f"{dout}/profileDB/db",
964 | f"{dout}/profileDB/db_consensus"],
965 | f"{dout}/logs/profile2consensus.log")
966 | run_mmseqs(["search", f"{dout}/profileDB/db",
967 | f"{dout}/profileDB/db_consensus", f"{dout}/alignmentDB/db",
968 | f"{dout}/tmp", "-c", "0.5", "--cov-mode", "1"],
969 | f"{dout}/logs/search.log",
970 | skip_if_exists = f"{dout}/alignmentDB/db.index", threads = threads)
971 | run_mmseqs(["clust", f"{dout}/profileDB/db", f"{dout}/alignmentDB/db",
972 | f"{dout}/clusterDB/db", "--cluster-mode", "2"],
973 | f"{dout}/logs/clust.log",
974 | skip_if_exists = f"{dout}/clusterDB/db.index", threads = threads)
975 |
976 | # create the pangenome file
977 | logging.info("compiling pangenome file with superfamilies")
978 | # why --full-header option? --> to avoid MMseqs2 extracting the
979 | # UniqueIdentifier part of sequences in UniProtKB format
980 | # (see https://www.uniprot.org/help/fasta-headers)
981 | run_mmseqs(["createtsv", f"{dout}/sequenceDB/db", f"{dout}/sequenceDB/db",
982 | f"{dout}/preclusterDB/db", f"{dout}/preclusters.tsv", "--full-header"],
983 | f"{dout}/logs/createtsv_preclusters.log")
984 | run_mmseqs(["createtsv", f"{dout}/sequenceDB/db", f"{dout}/sequenceDB/db",
985 | f"{dout}/clusterDB/db", f"{dout}/clusters.tsv", "--full-header"],
986 | f"{dout}/logs/createtsv_clusters.log")
987 | preclustertable = pd.read_csv(f"{dout}/preclusters.tsv", sep = "\t",
988 | names = ["precluster", "gene"])
989 | preclustertable = preclustertable.applymap(lambda x: x.split(" ")[0])
990 | clustertable = pd.read_csv(f"{dout}/clusters.tsv", sep = "\t",
991 | names = ["cluster", "precluster"])
992 | clustertable = clustertable.applymap(lambda x: x.split(" ")[0])
993 | genes = pd.merge(preclustertable, clustertable, on = "precluster")
994 | genes = genes.rename(columns = {"cluster": "orthogroup"})
995 | genes = genes.drop(["precluster"], axis = 1)
996 |
997 | # rename the superfamilies
998 | famnames_old = genes["orthogroup"].unique()
999 | famnames_new = [f"F{c}" for c in padded_counts(len(famnames_old))]
1000 | namedict = dict(zip(famnames_old, famnames_new))
1001 | genes["orthogroup"] = [namedict[f] for f in genes["orthogroup"]]
1002 |
1003 | # write pangenome file
1004 | write_tsv(genes, f"{dout}/genes.tsv")
1005 |
1006 | def infer_pangenome(faafins, splitstrategy, min_reps, max_reps, max_align, dout,
1007 | threads):
1008 | """Infers the pangenome of a set of genomes and writes it to disk.
1009 |
1010 | Args:
1011 | faafins (list): Paths to .faa fasta files, one per genome.
1012 | splitstrategy (str): Splitting strategy.
1013 | dout (str): Output folder for the pangenome.
1014 | threads (int): Number of threads to use.
1015 | """
1016 |
1017 | # threads per process
1018 | tpp = 1
1019 |
1020 | logging.info(f"{len(faafins)} genomes were supplied")
1021 |
1022 | logging.info("constructing gene table")
1023 | genes = extract_genes(faafins)
1024 | logging.info("checking if gene names are unique")
1025 | if not genes.gene.is_unique:
1026 | logging.error("gene names are not unique")
1027 | sys.exit(1)
1028 |
1029 | if (len(faafins)) == 1:
1030 |
1031 | logging.info("only one genome supplied - each gene will be its own "
1032 | "orthogroup")
1033 |
1034 | logging.info("assiging names to gene families")
1035 | pangenome = genes
1036 | pangenome["orthogroup"] = [f"F{c}" for c in \
1037 | padded_counts(len(pangenome.index))]
1038 |
1039 | logging.info("writing pangenome file")
1040 | write_tsv(pangenome, f"{dout}/pangenome.tsv")
1041 |
1042 | return()
1043 |
1044 | logging.info("STAGE 1: creation of superfamilies")
1045 | os.makedirs(f"{dout}/superfamilies", exist_ok = True)
1046 | infer_superfamilies(faafins, f"{dout}/superfamilies", threads)
1047 | genes_superfams = pd.read_csv(f"{dout}/superfamilies/genes.tsv",
1048 | sep = "\t", names = ["gene", "orthogroup"])
1049 | pangenome = pd.merge(genes, genes_superfams, on = "gene")
1050 |
1051 | if splitstrategy == "S":
1052 |
1053 | logging.info("writing pangenome file")
1054 | write_tsv(pangenome, f"{dout}/pangenome.tsv")
1055 | logging.info("removing temporary folders")
1056 | shutil.rmtree(f"{dout}/superfamilies")
1057 | return()
1058 |
1059 | logging.info("STAGE 2: splitting of superfamilies")
1060 |
1061 | logging.info("gathering sequences of superfamilies")
1062 | os.makedirs(f"{dout}/superfamilies/superfamilies", exist_ok = True)
1063 | dio_fastas = f"{dout}/superfamilies/fastas"
1064 | gather_orthogroup_sequences(pangenome, faafins, dio_fastas)
1065 |
1066 | logging.info("counting splitable superfamilies")
1067 | os.makedirs(f"{dout}/tmp", exist_ok = True)
1068 | pangenome = pangenome.groupby("orthogroup")
1069 | orthogroups = pangenome.aggregate({"genome": split_possible})
1070 | splitable = orthogroups[orthogroups.genome].index.tolist()
1071 | pangenome_splitable = [pan for name, pan in pangenome if name in splitable]
1072 | pangenome_splitable.sort(key = lambda pan: len(pan.index), reverse = True)
1073 | n = len(pangenome_splitable)
1074 | logging.info(f"found {n} splitable superfamilies")
1075 |
1076 | if n == 0:
1077 |
1078 | logging.info("writing pangenome file")
1079 | pangenome = pangenome.obj # to "ungroup"
1080 | write_tsv(pangenome, f"{dout}/pangenome.tsv")
1081 | logging.info("removing temporary folders")
1082 | shutil.rmtree(f"{dout}/superfamilies")
1083 | shutil.rmtree(f"{dout}/tmp")
1084 | return()
1085 |
1086 | logging.info("splitting superfamilies")
1087 | with ProcessPoolExecutor(max_workers = threads // tpp) as executor:
1088 | pangenome_splitable = executor.map(split_superfamily,
1089 | pangenome_splitable, [splitstrategy] * n, [dio_fastas] * n,
1090 | [min_reps] * n, [max_reps] * n, [max_align] * n, [tpp] * n,
1091 | [f"{dout}/tmp"] * n)
1092 | print("")
1093 | pangenome = pd.concat(list(pangenome_splitable) +
1094 | [pan for name, pan in pangenome if not name in splitable])
1095 |
1096 | logging.info("assigning names to the gene families")
1097 | nametable = pd.DataFrame({"old": pangenome["orthogroup"].unique()})
1098 | nametable["sf"] = [f.split("_")[0] for f in nametable["old"]]
1099 | nametable["new"] = nametable.groupby("sf")["sf"].transform(lambda sfs: \
1100 | [f"{sfs.tolist()[0]}_{c}" for c in padded_counts(len(sfs))])
1101 | namedict = dict(zip(nametable["old"], nametable["new"]))
1102 | pangenome["orthogroup"] = [namedict[f] for f in pangenome["orthogroup"]]
1103 |
1104 | logging.info("writing pangenome file")
1105 | write_tsv(pangenome, f"{dout}/pangenome.tsv")
1106 |
1107 | logging.info("removing temporary folders")
1108 | shutil.rmtree(f"{dout}/superfamilies")
1109 | shutil.rmtree(f"{dout}/tmp")
1110 |
--------------------------------------------------------------------------------
/src/scarap/readerswriters.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import gzip
3 | import os
4 | import re
5 | import pandas as pd
6 |
7 | from Bio import SeqIO, AlignIO
8 | from concurrent.futures import ProcessPoolExecutor
9 | from io import StringIO
10 |
11 | from scarap.utils import *
12 |
13 | def read_fastapaths(path):
14 | # when path is a file
15 | if os.path.isfile(path):
16 | # store fastapaths in list
17 | fastapaths = [fp.strip() for fp in open(path)]
18 | # when path is a folder
19 | elif os.path.isdir(path):
20 | # store fastapaths in list
21 | fastapaths = [os.path.join(path, file) for file in os.listdir(path)]
22 | fastapaths = [fp for fp in fastapaths if os.path.isfile(fp)]
23 | extensions = ("fasta", "fa", "faa", "ffn", "fasta.gz", "fa.gz",
24 | "faa.gz", "ffn.gz")
25 | fastapaths = [fp for fp in fastapaths if fp.endswith(extensions)]
26 | return(fastapaths)
27 |
28 | def read_mmseqs_table(fin):
29 | names = ["query", "target", "pident", "alnlen", "mismatch", "gapopen",
30 | "qstart", "qend", "tstart", "tend", "evalue", "bits"]
31 | table = pd.read_csv(fin, sep = "\t", names = names)
32 | return(table)
33 |
34 | def read_fasta(fin):
35 | with open_smart(fin) as hin:
36 | seqs = list(SeqIO.parse(hin, "fasta"))
37 | return(seqs)
38 |
39 | def write_fasta(seqs, fout):
40 | open(fout, "w").close()
41 | with open(fout, "a") as hout:
42 | for seq in seqs:
43 | SeqIO.write(seq, hout, "fasta")
44 |
45 | def read_domtbl(fin_domtbl):
46 | domtbl = pd.read_csv(fin_domtbl, delim_whitespace = True, comment = '#',
47 | usecols = [0, 3, 13, 15, 16],
48 | names = ['gene', 'profile', 'score', 'hmm_from', 'hmm_to'],
49 | dtype = {'gene': str, 'profile': str, 'score': float, 'hmm_from': int,
50 | 'hmm_to': int},
51 | engine = 'c'
52 | )
53 | return(domtbl)
54 |
55 | def read_genes(fin):
56 | genes = pd.read_csv(fin, sep = "\t",
57 | names = ["gene", "genome", "orthogroup"])
58 | return(genes)
59 |
60 | def read_orthogroups(fin):
61 | orthogroups = pd.read_csv(fin, sep = "\t", names = ["orthogroup", "cutoff"])
62 | return(orthogroups)
63 |
64 | def read_species(fin):
65 | genomes = pd.read_csv(fin, sep = "\t", names = ["genome", "species"])
66 | return(genomes)
67 |
68 | def read_orthogroups_orthofinder(fin_orthogroups):
69 | with open(fin_orthogroups, 'r') as hin_orthogroups:
70 | pangenome = {"gene": [], "genome": [], "orthogroup": []}
71 | header = hin_orthogroups.readline().strip()
72 | genomes = header.split("\t")[1:]
73 | for line in hin_orthogroups.readlines():
74 | line = line.strip().split("\t")
75 | orthogroup = line[0]
76 | for genome_ix, copies in enumerate(line[1:]):
77 | if copies != "":
78 | for copy in copies.split(", "):
79 | pangenome["gene"].append(copy)
80 | pangenome["genome"].append(genomes[genome_ix])
81 | pangenome["orthogroup"].append(orthogroup)
82 | pangenome = pd.DataFrame.from_dict(pangenome)
83 | return(pangenome)
84 |
85 | def read_pangenome_orthofinder(din_orthofinder):
86 | din_pangenome = os.path.join(din_orthofinder,
87 | "OrthoFinder/Results_*/Orthogroups")
88 | din_pangenome = glob.glob(din_pangenome)[0]
89 | fin_genes_1 = os.path.join(din_pangenome, "Orthogroups.tsv")
90 | genes_assigned = read_orthogroups_orthofinder(fin_genes_1)
91 | fin_genes_2 = os.path.join(din_pangenome,
92 | "Orthogroups_UnassignedGenes.tsv")
93 | genes_unassigned = read_orthogroups_orthofinder(fin_genes_2)
94 | pangenome = genes_assigned.append(genes_unassigned)
95 | return(pangenome)
96 |
97 | def extract_genetable(fin_genome):
98 | "Extracts a gene table from an ffn/faa file."
99 |
100 | genome = filename_from_path(fin_genome)
101 | with open_smart(fin_genome) as hin:
102 | fasta = hin.read()
103 | regex = re.compile("^>([^\n\t ]+)", re.MULTILINE)
104 | genes_genome = regex.findall(fasta)
105 | genes_genome = pd.DataFrame({"gene": genes_genome})
106 | genes_genome.loc[:, "genome"] = genome
107 | return(genes_genome)
108 |
109 | def extract_genes(fins_genomes, threads = 1):
110 | "Extracts a gene table from multiple ffn/faa files"
111 |
112 | with ProcessPoolExecutor(max_workers = threads) as executor:
113 | genes = executor.map(extract_genetable, fins_genomes)
114 | genes = pd.concat(genes)
115 | return(genes)
116 |
117 | def fastas2stockholm(fins_alis, fout_sto):
118 | with open(fout_sto, "a") as hout_sto:
119 | for fin_ali in fins_alis:
120 | orthogroup = os.path.splitext(os.path.basename(fin_ali))[0]
121 | with open(fin_ali) as hin_ali:
122 | ali = AlignIO.read(hin_ali, "fasta")
123 | with StringIO() as vf:
124 | AlignIO.write(ali, vf, "stockholm")
125 | sto = vf.getvalue().splitlines()
126 | sto.insert(1, "#=GF ID " + orthogroup)
127 | for line in sto:
128 | hout_sto.write(line + "\n")
129 |
--------------------------------------------------------------------------------
/src/scarap/utils.py:
--------------------------------------------------------------------------------
1 | import gzip
2 | import os
3 | import pandas as pd
4 | import shutil
5 |
6 | def create_prefdb(TDB, PDB):
7 | """Initialize a fake prefilter database.
8 |
9 | Create a fake prefilter database to be used for searching all queries
10 | against all targets.
11 |
12 | See https://github.com/soedinglab/MMseqs2/wiki#how-to-create-a-fake-prefiltering-for-all-vs-all-alignments
13 |
14 | Args:
15 | TDB (str): The path to the target database, but relative to the prefilter
16 | database!!
17 | PDB (str): The path to the prefilter database.
18 | """
19 | os.symlink(f"{TDB}.index", PDB)
20 | with open(f"{PDB}.dbtype", "w") as hout_PDB:
21 | chars = [chr(7)] + [chr(0)] * 3
22 | for char in chars:
23 | hout_PDB.write(char)
24 |
25 | def update_prefdb(QDB, TDB, PDB):
26 | """Setup the queries for a fake prefilter database.
27 |
28 | Set the queries of a fake prefilter database to be used for searching all
29 | queries against all targets.
30 |
31 | See https://github.com/soedinglab/MMseqs2/wiki#how-to-create-a-fake-prefiltering-for-all-vs-all-alignments
32 |
33 | Args:
34 | QDB (str): The path to the query database.
35 | TDB (str): The path to the target database.
36 | PDB (str): The path to the prefilter database.
37 | """
38 | index_size = os.path.getsize(f"{TDB}.index")
39 | open(f"{PDB}.index", "w").close()
40 | with open(f"{QDB}.index", "r") as hin_QDB:
41 | with open(f"{PDB}.index", "a") as hout_PDB:
42 | for query_line in hin_QDB:
43 | values = query_line.strip().split("\t")
44 | towrite = "\t".join([values[0], "0", str(index_size)])
45 | hout_PDB.write(f"{towrite}\n")
46 |
47 | def padded_counts(n):
48 | d = len(str(n))
49 | counts = [f"{str(i + 1).zfill(d)}" for i in range(n)]
50 | return(counts)
51 |
52 | def makedirs_smart(dout):
53 | if os.path.exists(dout):
54 | shutil.rmtree(dout)
55 | os.makedirs(dout, exist_ok = True)
56 |
57 | def open_smart(filename, mode = "rt"):
58 | if filename.endswith(".gz"):
59 | return(gzip.open(filename, mode))
60 | else:
61 | return(open(filename, mode))
62 |
63 | def make_paths(filenames, folder, extension):
64 | paths = [os.path.join(folder, filename + extension) for filename in
65 | filenames]
66 | return(paths)
67 |
68 | def filename_from_path(path):
69 | if (path.endswith(".gz")):
70 | path = path[:-3]
71 | filename = os.path.basename(path)
72 | filename = os.path.splitext(filename)[0]
73 | return(filename)
74 |
75 | def write_tsv(genes, fout):
76 | genes.to_csv(fout, sep = "\t", index = False, header = False)
77 |
78 | def write_lines(lines, fout):
79 | lines = pd.DataFrame({"line": lines})
80 | lines.to_csv(fout, index = False, header = False)
81 |
82 | def read_lines(fin):
83 | with open(fin) as hin:
84 | lines = [line.strip() for line in hin.readlines()]
85 | return(lines)
86 |
87 | def listpaths(folder):
88 | paths = [os.path.join(folder, f) for f in os.listdir(folder)]
89 | return(paths)
90 |
--------------------------------------------------------------------------------
/test/01_pan.bats:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bats
2 |
3 | setup() {
4 | load 'test_helper/bats-support/load'
5 | load 'test_helper/bats-assert/load'
6 | din=testdata/data/01_pan/faas
7 | dout=testresults
8 | # Prepare data
9 | mkdir -p $dout
10 | ls $din/*.faa.gz | head -3 > $dout/faapaths.txt
11 | }
12 |
13 | @test "Can run with faapaths" {
14 | scarap pan $dout/faapaths.txt $dout/pan -t 16 # with faapaths
15 | }
16 |
17 | @test "Can run with faafolder" {
18 | scarap pan $din $dout/pan -t 16 # with faafolder
19 | }
20 |
21 | @test "Running with redundant genes should give error" {
22 | ls $din/{extra,redundant}/*.faa.gz >> $dout/faapaths.txt
23 | redundant_run() {
24 | scarap pan $dout/faapaths.txt $dout/pan -t 16
25 | }
26 | run redundant_run
27 | assert_failure
28 | }
29 |
30 | teardown() {
31 | rm -r $dout
32 | }
33 |
--------------------------------------------------------------------------------
/test/02_pan_hierarchical.bats:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bats
2 |
3 | setup() {
4 | load 'test_helper/bats-support/load'
5 | load 'test_helper/bats-assert/load'
6 | din=testdata/data/02_hierarchical
7 | dout=testresults # Prepare data
8 | mkdir -p $dout
9 | ls $din/faas_hiertest/*.faa.gz > $dout/faapaths_hiertest.txt
10 | }
11 |
12 | @test "Can run hierarchical with faapaths" {
13 | scarap pan $dout/faapaths_hiertest.txt $dout/pan_hierarchical \
14 | -s $din/species_hiertest.tsv -t 16
15 | [ -s $dout/pan_hierarchical/pangenome.tsv ]
16 | }
17 |
18 | @test "Can run hierarchical with faafolder" {
19 | scarap pan $din/faas_hiertest $dout/pan_hierarchical \
20 | -s $din/species_hiertest.tsv -t 16
21 | [ -s $dout/pan_hierarchical/pangenome.tsv ]
22 | }
23 |
24 | teardown() {
25 | rm -r $dout
26 | }
--------------------------------------------------------------------------------
/test/03_build.bats:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bats
2 |
3 | setup() {
4 | din=testdata/data/01_pan/faas
5 | din_build=testdata/data/03_build
6 | dout=testresults
7 | mkdir -p $dout
8 | ls $din/*.faa.gz | head -3 > $dout/faapaths.txt
9 | }
10 |
11 | @test "Build" {
12 | scarap build $dout/faapaths.txt $din_build/pangenome.tsv $dout/build \
13 | -p 90 -f 95 -m 100
14 | [ -s $dout/build/cutoffs.csv ]
15 | }
16 |
17 | teardown() {
18 | rm -r $dout
19 | }
20 |
--------------------------------------------------------------------------------
/test/04_search.bats:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bats
2 |
3 | setup() {
4 | din=testdata/data
5 | dout=testresults
6 | mkdir -p $dout
7 | ls $din/01_pan/faas/*.faa.gz | head -3 > $dout/faapaths.txt
8 | cat $dout/faapaths.txt | head -4 | tail -1 > $dout/qpath.txt
9 | }
10 |
11 | @test "Can run a search" {
12 | scarap search $dout/faapaths.txt $din/04_search $dout/search
13 | [ -s $dout/search/genes.tsv ]
14 | }
15 |
16 | teardown() {
17 | rm -r $dout
18 | }
19 |
--------------------------------------------------------------------------------
/test/05_check.bats:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bats
2 |
3 | setup() {
4 | din=testdata/data/03_build
5 | dout=testresults
6 | dgenomes=$dout/checkgenomes
7 | dgroups=$dout/checkgroups
8 | mkdir -p $dout
9 | }
10 |
11 | @test "Can run check genomes" {
12 | scarap checkgenomes $din/pangenome.tsv $dgenomes
13 | [ -s $dgenomes/genomes.tsv ]
14 | }
15 |
16 | @test "Can run check groups" {
17 | scarap checkgroups $din/pangenome.tsv $dgroups
18 | [ -s $dgroups/orthogroups.tsv ]
19 | }
20 |
21 | @test "Can filter" {
22 | scarap checkgroups $din/pangenome.tsv $dgroups
23 | awk '$2 == 1.0 {print $1}' $dgroups/orthogroups.tsv \
24 | > $dout/orthogroups_core.txt
25 |
26 | cat $dout/orthogroups_core.txt | head -n 10 > $dout/orthogroups_core_sub.txt
27 |
28 | scarap filter -c -o $dout/orthogroups_core_sub.txt \
29 | $din/pangenome.tsv $dout
30 | [ -s $dout/pangenome.tsv ]
31 | }
32 |
33 | teardown() {
34 | rm -r $dout
35 | }
36 |
--------------------------------------------------------------------------------
/test/06_concatenate.bats:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bats
2 |
3 | setup() {
4 | load 'test_helper/bats-support/load'
5 | load 'test_helper/bats-assert/load'
6 | din_concat=testdata/data/06_concatenate
7 | din_faas=testdata/data/01_pan/faas
8 | din_faapath=tempdir
9 | dout=testresults
10 | mkdir -p $din_faapath
11 | fin_faas=$din_faapath/faapaths.txt
12 | ls $din_faas/*.faa.gz | head -3 > $din_faapath/faapaths.txt
13 | }
14 |
15 | @test "Can concatenate" {
16 | scarap concat $fin_faas $din_concat/pangenome.tsv $dout
17 | [ -s $dout/supermatrix_aas.fasta ]
18 | }
19 |
20 | teardown() {
21 | rm -r $dout
22 | rm -r $din_faapath
23 | }
--------------------------------------------------------------------------------
/test/07_sample.bats:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bats
2 |
3 | setup() {
4 | load 'test_helper/bats-support/load'
5 | load 'test_helper/bats-assert/load'
6 | din_faas=testdata/data/01_pan/faas
7 | din_concat=testdata/data/07_sample
8 | din_faapath=tempdir
9 | dout=testresults
10 | mkdir -p $din_faapath
11 | fin_faas=$din_faapath/faapaths.txt
12 | ls $din_faas/*.faa.gz | head -3 > $din_faapath/faapaths.txt
13 | ls $din_faas/extra/*.faa.gz >> $din_faapath/faapaths.txt
14 | }
15 |
16 | @test "Can sample results" {
17 | scarap sample $fin_faas $din_concat/pangenome.tsv $dout \
18 | --max-genomes 5 --method mean50
19 | #[ -s $dout/clusters.tsv ]
20 | [ "$(wc -l < $dout/seeds.txt)" -eq 5 ]
21 | }
22 |
23 | teardown() {
24 | rm -r $dout
25 | rm -r $din_faapath
26 | }
--------------------------------------------------------------------------------
/test/08_core.bats:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bats
2 |
3 | setup() {
4 | load 'test_helper/bats-support/load'
5 | load 'test_helper/bats-assert/load'
6 | din=testdata/data/01_pan/faas
7 | dout=testresults
8 | # Prepare data
9 | mkdir -p $dout
10 | ls $din/*.faa.gz | head -5 > $dout/faapaths_coretest.txt
11 | }
12 |
13 | @test "Can run core module" {
14 | scarap core $dout/faapaths_coretest.txt $dout/core -t 16
15 | }
16 |
17 | teardown() {
18 | rm -r $dout
19 | }
--------------------------------------------------------------------------------
/test/README.md:
--------------------------------------------------------------------------------
1 | # CI tests written with Bats
2 |
3 | The following files are part of the SCARAP test suite, written with the [:bat: Bats framework](https://github.com/bats-core/bats-core).
4 | The test suite is run when there are new pushes to the repository, using a [github-actions workflow]().
5 | It collects the input testdata needed for the scripts from [a repository containing the testdata](https://github.com/LebeerLab/SCARAP-testdata).
6 |
7 | ## Running the test suite locally
8 |
9 | Some preparation is needed to run the suite locally however. In short, bats-core needs to be installed and the testdata needs to be cloned into the right folder.
10 |
11 | - Installing bats-core: the easiest way to install bats localy is by adding it as a git submodule. [Follow the instructions in the manual](https://bats-core.readthedocs.io/en/stable/tutorial.html#quick-installation) to do this.
12 | - Fetching the testdata: for the scripts to work, the [data folder from the external repo](https://github.com/LebeerLab/SCARAP-testdata) needs to be moved into a new directory in the root called "testdata". The easiest way to do this would be executing the following code in the root of this project:
13 |
14 | ```
15 | git clone https://github.com/LebeerLab/SCARAP-testdata.git
16 | mv SCARAP-testdata testdata
17 | ```
18 |
--------------------------------------------------------------------------------