├── .gitignore ├── Brapa.kaksks.R.result.png ├── Dauc_caro.ks.R.result.pdf ├── Dauc_caro.ks.R.result.png ├── Esalsugineum.ks.plot.html ├── LICENSE ├── MANIFEST.in ├── NEW ├── README.rst ├── SVM.R ├── SVM_sample_01.jpg ├── Tree2GD.result.pdf ├── Tree2GD.result_00.png ├── html_out_example.gif ├── setup.py ├── tree2gd ├── __init__.py ├── blastp.py ├── dollop.py ├── example_data │ ├── Alyrata.cds │ ├── Alyrata.pep │ ├── Alyrata.pep.dmnd │ ├── Athaliana.cds │ ├── Athaliana.pep │ ├── Athaliana.pep.dmnd │ ├── Brapa.cds │ ├── Brapa.pep │ ├── Brapa.pep.dmnd │ ├── Cpapaya.cds │ ├── Cpapaya.pep │ ├── Cpapaya.pep.dmnd │ ├── Crubella.cds │ ├── Crubella.pep │ ├── Crubella.pep.dmnd │ ├── Esalsugineum.cds │ ├── Esalsugineum.pep │ ├── Esalsugineum.pep.dmnd │ ├── SVM_testdata.csv │ ├── Tparvula.cds │ ├── Tparvula.pep │ ├── Tparvula.pep.dmnd │ ├── config.ini │ ├── example.tree │ └── full_config.ini ├── kaks.py ├── mcl.py ├── plot.py ├── seq.py ├── seq.pyc ├── software │ ├── Epal2nal.pl │ ├── KaKs_Calculator │ ├── PhyloMCL │ ├── SVM.R │ ├── Tree2GD │ ├── Tree2GD_draw.R │ ├── calculate_4DTV_correction.pl │ ├── diamond │ ├── dolloparsimony │ ├── iqtree │ ├── muscle │ ├── seqkit │ └── trimal ├── synteny.py └── wgd.py └── tree2gd_main.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /Brapa.kaksks.R.result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/Brapa.kaksks.R.result.png -------------------------------------------------------------------------------- /Dauc_caro.ks.R.result.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/Dauc_caro.ks.R.result.pdf -------------------------------------------------------------------------------- /Dauc_caro.ks.R.result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/Dauc_caro.ks.R.result.png -------------------------------------------------------------------------------- /Esalsugineum.ks.plot.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Esalsugineum-ks.htmlpolt 6 | 7 | 8 | 9 | 10 |
11 | 1618 | 1619 | 1620 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include tree2gd/example_data *.pep *.cds *.tree *.ini 2 | recursive-include tree2gd/software * 3 | -------------------------------------------------------------------------------- /NEW: -------------------------------------------------------------------------------- 1 | 2 | <2020-8-18> 3 | -The need for species list files is cancelled, the species list can be obtained directly from the species tree.nwk 4 | -Optimized drawing script 5 | -Organize and add sample data sets 6 | -Optimize the software packaging structure, automatically include the required software and call it by default 7 | <2020-8-24> 8 | -Modify part of the source code of ParaAT.pl calculated by kaks, and adjust the settings of this step at the same time, so that it can support the four software "clustalw2", "t_coffee", "mafft", "muscle" for comparison, the default mafft 9 | -Enriched the setting options of iqtree and tree2gd, can set the bootstrap value and the tree model 10 | <2020-8-26> 11 | -Can choose to use cds sequence for gene tree construction 12 | -Optimized the result of html drawing 13 | -Optimized the error handling of the program 14 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: https://img.shields.io/pypi/v/Tree2gd.svg 2 | :alt: Tree2gd on the Python Package Index (PyPI) 3 | :target: https://pypi.python.org/pypi/Tree2gd 4 | .. image:: https://img.shields.io/pypi/pyversions/Tree2gd.svg?colorB=brightgreen 5 | :alt: Tree2gd Python Version (PyPI) 6 | :target: https://pypi.python.org/pypi/Tree2gd 7 | 8 | Tree2gd 9 | ===================== 10 | Tree2GD provides an integrated pipeline to identify WGD events, with friendful commands in one-step or multiple steps, 11 | with smart quality control in custom dataset, with multithreading design costing low time, with well performance in detect WGD signals, 12 | and with advanced visualization of GDs and Ks peaks. 13 | 14 | 15 | Python Requirements 16 | =================== 17 | We currently recommend using Python 3.8 from http://www.python.org 18 | Tree2GD is currently supported and tested on the following Python 19 | implementations: 20 | 21 | - Python 3.6, 3.7, 3.8 -- see http://www.python.org 22 | 23 | - Pip3.6>=v19.2.3 -- see https://pypi.org/project/pip 24 | 25 | Installing by ``sudo apt-get install python3-pip`` 26 | or with get-pip.py using :: 27 | 28 | curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py 29 | python3 get-pip.py 30 | 31 | R Requirements 32 | =================== 33 | In order to complete the final drawing result display,We currently recommend using R>=v4.0.0 34 | from https://www.r-project.org 35 | 36 | Installation 37 | =================== 38 | Installation From Pypi 39 | ------------------------------------- 40 | You can quickly install Tree2gd through the following command, 41 | and automatically install the python packages it depends on by run:: 42 | 43 | pip3 install Tree2gd [--user] #You may need the --user parameter if you do not have administrator rights 44 | 45 | If you need to use a specific python3 path to install and use Tree2gd, you can replace the above ``pip3`` with ``/THE/PATH/OF/YOUR/PYTHON3 -m pip`` 46 | 47 | Installation From Source 48 | ------------------------------------ 49 | You can download and decompress our source code, or fetch it using git. 50 | Now change directory to the Tree2gd source code folder and run:: 51 | 52 | python3 setup.py build 53 | python3 setup.py test 54 | python3 setup.py install [--user] #You may need the --user parameter if you do not have administrator rights 55 | 56 | 57 | 58 | Testing 59 | =================== 60 | After the installation is successful, the main program command ``Tree2gd`` and test command ``Tree2gd_test`` will be added to your system. 61 | You can first check whether Tree2gd is installed successfully by running the following command:: 62 | 63 | $ Tree2gd -h 64 | 65 | If the system feeds back its corresponding parameter description, congratulations on the correct installation of Tree2gd to your system! 66 | Next, we **strongly recommend** that you run ``Tree2gd_test`` to use the data we have prepared for a quick and complete Tree2gd test, because you can get the following benefits: 67 | 68 | 1.Check whether the pre-compiled version of the software we use by default is suitable for your system, and replace the unavailable ones with the configuration file (see the following instructions for configuration). 69 | 70 | 2.When using for the first time, in the final drawing part, we will spend a few minutes to install several dependent packages in R. After that, the formal use will be faster and more convenient. 71 | 72 | 3.After the user modifies the configuration file, you can add own new settings through the ``-config`` parameter of the command to test, and quickly detect that the new configuration can run successfully. 73 | 74 | The ``Tree2gd_test`` command will run the complete analysis process with the fastest parameter settings. 75 | It only contains two optional parameters command:: 76 | 77 | $ Tree2gd_test [-t] [--config] 78 | -t [int] sets the number of threads for testing (default: 1) 79 | --config [str] uses the configuration given by the user File for testing (verify availability of custom configuration) 80 | 81 | In the case of 4 cpus, it takes about 5 minutes to complete a round of testing (the first run will take some extra time to download and install the R package). After successful operation, 82 | it will generate a folder in the current directory``./Tree2gd_test_out``, You can check it (especially the final drawing result ``Tree2GD.result.pdf`` in step6) to fully verify the running effect of the software. 83 | 84 | Running 85 | =================== 86 | You can complete all WGD analysis only with the simplest commands below 87 | and get a perfect drawing display:: 88 | 89 | $ Tree2gd -i input_dir -tree phytree.nwk 90 | 91 | Among them, ``phytree.nwk`` is the species evolution tree in newick format. 92 | 93 | The ``input_dir`` folder contains all the corresponding protein sequences (default postfix .pep) and cds sequences (default postfix .cds) of each species contained in phytree.nwk by fasta format. 94 | 95 | In addition, you can add the following optional parameters to make the program run faster and better (especially when using multi-core operation): 96 | 97 | -t t Thread num.default:1 98 | -o outputdir The output dir.default:./output 99 | --step step_num_str Which steps you need.default:123456(Choose from 100 | numbers: such as '234') 101 | --log logfile log file name,or log will print on stdout 102 | --config config_file config.ini configuration file, leave it blank to run 103 | with default parameters and the program's own software 104 | version. 105 | --debug The log file will contain the output of each software 106 | itself, which is convenient for finding errors (-log is 107 | required) 108 | --only_script Only generate scripts, not run automatically. 109 | --cds2tree Use cds sequence to construct gene tree. 110 | --synteny Using the results of the covariance analysis, the GD ratio and Ks distribution were optimized. **Gene annotations information for each species need to be provided in the input folder as *.bed files 111 | 112 | 113 | Detailed parameter configuration file : config.ini 114 | ============================================================= 115 | There are many softwares in the Tree2gd process. The pre-compiled versions of the programs are already used by default. At the same time, these softwares have many parameters that can be adjusted to achieve the best results. 116 | 117 | So we used the config.ini file to summarize these settings, input it to the program through the ``-config`` parameter, and call the configuration in the corresponding program. 118 | 119 | **! note! Any item in this file is optional, users only need to add the lines they need in the corresponding section** 120 | :: 121 | 122 | [software] 123 | #The path of all software used by Tree2gd.If one is not set or set to empty,the program will use its own pre-compiled software version (location at /THE/PATH/OF/python/site-packages/software/) 124 | diamond =/THE/PATH/OF/python/site-packages/software/diamond 125 | muscle=/THE/PATH/OF/python/site-packages/software/muscle 126 | iqtree=/THE/PATH/OF/python/site-packages/software/iqtree 127 | tree2gd=/THE/PATH/OF/python/site-packages/software/Tree2GD 128 | phymcl=/THE/PATH/OF/python/site-packages/software/PhyloMCL 129 | KaKs_Calculator=/THE/PATH/OF/python/site-packages/software/KaKs_Calculator 130 | calculate_4DTV=/THE/PATH/OF/python/site-packages/software/calculate_4DTV_correction.pl 131 | Epal2nal=/THE/PATH/OF/python/site-packages/software/Epal2nal.pl 132 | dolloparsimony=/THE/PATH/OF/python/site-packages/software/dolloparsimony 133 | [postfix] 134 | #The file name postfix of each species protein and cds, the prefix must be exactly the same as in the tree file 135 | pep=.pep 136 | cds=.cds 137 | [diamond] 138 | #The parameters used by diamond, in addition to the following default parameters, the user can add any parameter that diamond can recognize 139 | -e=1e-10 140 | -p=4 #The number of threads used by each diamond, the number of parallel diamonds in actual operation is Tree2gd thread//it 141 | [phymcl] 142 | #The parameters used by phymcl, the user can add any parameter that phymcl can recognize 143 | [mcl2fasta] 144 | min_taxa=4 #The minimum number of species contained in each gene set when doing paper mulberry, cannot be less than 4, otherwise a meaningful tree cannot be built 145 | [iqtree] 146 | #The parameters used by iqtree, in addition to the following default parameters, the user can add any parameter that iqtree can recognize 147 | -B=1000 #Ultrafast bootstrap (>=1000) If you do not set it default to 1000, you can force it to 0 so that bootstrap is not performed, but it is not recommended except for testing 148 | -m=JTT+G4 #If the -cds2tree parameter is added, it will default to HKY. Please specify DNA or Protein when defining the tree structure model 149 | [tree2gd] 150 | #The parameters used by tree2gd, in addition to the following default parameters, the user can add any parameter that tree2gd can recognize 151 | --bp=50 152 | 153 | Sample output plot show 154 | ================================= 155 | 156 | Summary output plot 157 | ------------------------ 158 | .. image:: https://github.com/Dee-chen/Tree2gd/blob/master/Tree2GD.result_00.png 159 | :target: https://github.com/Dee-chen/Tree2gd/blob/master/Tree2GD.result.pdf 160 | 161 | Interactive html kaks plot 162 | ------------------------ 163 | .. image:: https://github.com/Dee-chen/Tree2gd/blob/master/html_out_example.gif 164 | :align: center 165 | 166 | R kaks diagram 167 | ------------------------ 168 | .. image:: https://github.com/Dee-chen/Tree2gd/blob/master/Dauc_caro.ks.R.result.png 169 | 170 | 171 | WGD identification by support vector machine (SVM) model 172 | ------------------------ 173 | .. image:: https://github.com/Dee-chen/Tree2gd/blob/master/SVM_sample_01.jpg 174 | 175 | Software and Citation 176 | ================================== 177 | 178 | step1.blastp 179 | -------------------------- 180 | 181 | [diamond] Buchfink B, Xie C, Huson DH, "Fast and sensitive protein alignment using DIAMOND", Nature Methods 12, 59-60 (2015). doi:10.1038/nmeth.3176 182 | [seqkit] W Shen, S Le, Y Li*, F Hu*. SeqKit: a cross-platform and ultrafast toolkit for FASTA/Q file manipulation. PLOS ONE. doi:10.1371/journal.pone.0163962. 183 | 184 | step2.MCL 185 | ------------------------- 186 | 187 | [phylomcl] Zhou S , Chen Y , Guo C , et al. PhyloMCL: Accurate clustering of hierarchical orthogroups guided by phylogenetic relationship and inference of polyploidy events[J]. Methods in Ecology and Evolution, 2020. 188 | 189 | step3.dollop 190 | ------------------------- 191 | 192 | [dolloparsimony] 193 | 194 | step4.WGD 195 | ------------------------- 196 | 197 | [Tree2GD](Made some modifications on the 2.4 version) https://tree2gd.sourceforge.io/ 198 | 199 | [MUSCLE] Edgar, R. C. (2004). MUSCLE: multiple sequence alignment with high accuracy and high throughput. Nucleic Acids Research, 32(5), 1792–1797. 200 | 201 | [iqtree] B.Q. Minh, H.A. Schmidt, O. Chernomor, D. Schrempf, M.D. Woodhams, A. von Haeseler, R. Lanfear (2020) IQ-TREE 2: New models and efficient methods for phylogenetic inference in the genomic era. Mol. Biol. Evol., 37:1530-1534. https://doi.org/10.1093/molbev/msaa015 202 | 203 | [pal2nal.pl] (v14; January 6, 2012) Zhang Zhang (zhangzhang@big.ac.cn) 204 | 205 | step5.KaKs 206 | ------------------------- 207 | 208 | [MUSCLE] Edgar, R. C. (2004). MUSCLE: multiple sequence alignment with high accuracy and high throughput. Nucleic Acids Research, 32(5), 1792–1797. 209 | 210 | step6.plot_summary 211 | ------------------------- 212 | [jcvi] Tang H , Krishnakumar V , Li J . jcvi: JCVI utility libraries[J]. 2015. 213 | 214 | [MCscan] Tang H , Bowers J E , Wang X , et al. Synteny and Collinearity in Plant Genomes[J]. Science, 2008, 320(5875):p.486-488. 215 | 216 | [ggtree](R package) G Yu. Using ggtree to visualize data on tree-like structures. Current Protocols in Bioinformatics, 2020, 69:e96. doi: 10.1002/cpbi.96. 217 | 218 | [pyecharts](Python package) https://pyecharts.org/ 219 | 220 | 221 | -------------------------------------------------------------------------------- /SVM.R: -------------------------------------------------------------------------------- 1 | library(e1071) 2 | library(dplyr) 3 | library(ggplot2) 4 | ####################### 5 | lm_eqn <- function(df,x,y){ 6 | m <- lm(y ~ x, df); 7 | eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2*", p-value="~p, 8 | list(a = format(unname(coef(m)[1]), digits = 2), 9 | b = format(unname(coef(m)[2]), digits = 2), 10 | r2 = format(summary(m)$r.squared, digits = 3), 11 | p = format(as.numeric(summary(m)$coefficients[,4][2]), digits = 3))) 12 | as.character(as.expression(eq)); 13 | } 14 | ###################### 15 | 16 | wgd_data=read.csv("SVM_data.csv",header=T,row.names = 1) 17 | wgd_data$Newick_label=rownames(wgd_data) 18 | x=cbind(wgd_data$median,log(wgd_data$GDratio)) 19 | ##The original GD median with scale is used by default and can be replaced with covariance support results 20 | colnames(x)=c("ks","log_ratio") 21 | 22 | if("type" %in% colnames(wgd_data)){ 23 | type=wgd_data$type 24 | x=data.frame(x, type=as.factor(type)) 25 | 26 | svm.model <- svm(type~.,data=x,kernel="linear",cost=5,scale = FALSE) 27 | summary(svm.model) 28 | plot(svm.model, x, ks ~ log_ratio) 29 | 30 | 31 | 32 | w=t(svm.model$coefs)%*%svm.model$SV 33 | b=-svm.model$rho 34 | x$node=wgd_data$Newick_label 35 | 36 | p=ggplot(x[which(x$type=="TRUE"),],aes(x=as.numeric(ks),y=as.numeric(log_ratio),label=node))+ 37 | geom_point(size=4,colour="red")+ 38 | theme_classic()+ 39 | geom_text(size=5,vjust = "inward", hjust = "inward")+ 40 | stat_smooth(color = "blue",formula=y ~x,method = "lm",lty=2)+ 41 | labs(title ="", x="Ks",y="ln(GD_raito)",size=5)+ 42 | geom_point(data=x[which(x$type!="TRUE"),],mapping=aes(x=as.numeric(ks),y=as.numeric(log_ratio),label=node),shape=3,size=3,colour="blue",show.legend=FALSE) 43 | p1 <- p + 44 | geom_text(x = 1.5, y = -0.5, label =lm_eqn(x[which(x$type=="TRUE"),],as.numeric(x[which(x$type=="TRUE"),"ks"]),as.numeric(x[which(x$type=="TRUE"),"log_ratio"])), 45 | parse = TRUE,colour="blue",size=5) 46 | p2 <- p1 +geom_abline(aes(intercept=-b/w[1,2],slope=-w[1,1]/w[1,2]),lty=2,colour="red",size=1) + 47 | geom_text(x =0.5, y = -2.5,label = paste("SVM: y = ",round(-w[1,1]/w[1,2],2),"x",round(-b/w[1,2],2)),colour="red",size=5) 48 | print(p2) 49 | 50 | }else { 51 | x=as.data.frame(cbind(wgd_data$median,log(wgd_data$GDratio))) 52 | colnames(x)=c("ks","log_ratio") 53 | x[,"type"]=x[,"ks"] 54 | for(i in 1:nrow(x)){ 55 | if(x[i,"log_ratio"]>x[i,"ks"]*(-1.28)-1.3){ 56 | x[i,"type"]="TRUE"; 57 | } else { 58 | x[i,"type"]="FALSE"; 59 | } 60 | } 61 | ###########No know WGD loci were given, using the classification planes obtained in the 68 plants data. 62 | a=-1.28 63 | b=-1.3 64 | x$node=wgd_data$Newick_label 65 | 66 | p=ggplot(x[which(x$type=="TRUE"),],aes(x=as.numeric(ks),y=as.numeric(log_ratio),label=node))+ 67 | geom_point(size=4,colour="red")+ 68 | theme_classic()+ 69 | geom_text(size=5,vjust = "inward", hjust = "inward")+ 70 | stat_smooth(color = "blue",formula=y ~x,method = "lm",lty=2)+ 71 | labs(title ="", x="Ks",y="ln(GD_raito)",size=5)+ 72 | geom_point(data=x[which(x$type=="FALSE"),],mapping=aes(x=as.numeric(ks),y=as.numeric(log_ratio),label=node),shape=3,size=3,colour="blue",show.legend=FALSE) 73 | p1 <- p + 74 | geom_text(x = 1.5, y = -0.5, label =lm_eqn(x[which(x$type=="TRUE"),],as.numeric(x[which(x$type=="TRUE"),"ks"]),as.numeric(x[which(x$type=="TRUE"),"log_ratio"])), 75 | parse = TRUE,colour="blue",size=5) 76 | p2 <- p1 +geom_abline(aes(intercept=b,slope=a),lty=2,colour="red",size=1) + 77 | geom_text(x =0.5, y = -2.5,label = paste("SVM: y = "," +",a,"x",b),colour="red",size=5) 78 | print(p2) 79 | 80 | } 81 | -------------------------------------------------------------------------------- /SVM_sample_01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/SVM_sample_01.jpg -------------------------------------------------------------------------------- /Tree2GD.result.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/Tree2GD.result.pdf -------------------------------------------------------------------------------- /Tree2GD.result_00.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/Tree2GD.result_00.png -------------------------------------------------------------------------------- /html_out_example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/html_out_example.gif -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.5 2 | 3 | try: 4 | from setuptools import setup 5 | from setuptools import Command 6 | from setuptools import Extension 7 | except ImportError: 8 | sys.exit( 9 | "We need the Python library setuptools to be installed. " 10 | "Try runnning: python -m ensurepip" 11 | ) 12 | 13 | with open("README.rst", "r") as fh: 14 | long_description = fh.read() 15 | 16 | setup( 17 | name='Tree2gd', 18 | version='1.0.38', 19 | packages=['tree2gd'], 20 | license='GPL', 21 | long_description_content_type='text/x-rst', 22 | long_description=long_description, 23 | author='Duoyuan chen', 24 | author_email='18110700097@fudan.edu.cn', 25 | description='Tree2gd', 26 | py_modules=['tree2gd_main'], 27 | include_package_data=True, 28 | url='https://github.com/Dee-chen/Tree2gd', 29 | install_requires=[ 30 | 'configparser', 31 | 'matplotlib', 32 | 'argparse', 33 | 'coloredlogs', 34 | 'pyecharts', 35 | 'bio', 36 | 'jcvi' 37 | ], 38 | classifiers=[ 39 | "Programming Language :: Python :: 3.6", 40 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 41 | "Operating System :: POSIX :: Linux", 42 | ], 43 | python_requires='>=3.6', 44 | entry_points=''' 45 | [console_scripts] 46 | Tree2gd=tree2gd_main:main 47 | Tree2gd_test=tree2gd_main:test 48 | ''', 49 | ) 50 | -------------------------------------------------------------------------------- /tree2gd/__init__.py: -------------------------------------------------------------------------------- 1 | #Tree2GD 2 | -------------------------------------------------------------------------------- /tree2gd/blastp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.7 2 | 3 | import os 4 | import subprocess 5 | import logging 6 | from multiprocessing import Pool 7 | import sys 8 | import configparser 9 | 10 | def sub_sh(sh): 11 | logging.info("Start runing step1 blastp: %s.."%sh) 12 | stdout=subprocess.run(['sh',sh],stdout=subprocess.PIPE, stderr=subprocess.PIPE) 13 | logging.debug('{} stdout:\n'.format(sh) +stdout.stdout.decode('utf-8')) 14 | logging.debug('{} stderr:\n'.format(sh) +stdout.stderr.decode('utf-8')) 15 | logging.info("step1 blastp: %s has done."%sh) 16 | 17 | 18 | def all2all_diamond(sp_list,config,out,diamond,seqkit,pep_postfix,args): 19 | logging.info("Writing step1 script files...") 20 | sp_num=len(sp_list) 21 | op='' 22 | sh_list=[] 23 | p=config.get("diamond","-p") if config.has_option("diamond","-p") and config.get("diamond","-p")!="" else args.t 24 | if int(p)>args.t: 25 | logging.warning("The number of diamond threads %s is greater than the total program thread %s, it will be set to %s."%(str(p),str(args.t),str(args.t))) 26 | p=args.t 27 | if not config.has_section('diamond'): 28 | config.add_section('diamond') 29 | config.set("diamond","-p",str(p)) 30 | options=config.items("diamond") 31 | summary_sh = open(os.sep.join([out,'summary.sh']),"w") 32 | step1_sh = open(os.sep.join([out,'step1.sh']),"w") 33 | for k,v in options: 34 | op=' '.join((op,' '.join((k,v)))) 35 | for i in sp_list: 36 | SH = open(os.sep.join([out,'sample_sh',i+".sh"]),"w") 37 | SH.write(diamond + ' makedb -d '+os.sep.join([args.i,i+pep_postfix])+' --in '+os.sep.join([args.i,i+pep_postfix])+"\n") 38 | for j in sp_list: 39 | SH.write(diamond+' blastp -f 6 --more-sensitive '+op+' -d '+os.sep.join([args.i,i+pep_postfix])+' -q '+os.sep.join([args.i,j+pep_postfix])+' -o '+os.sep.join([out,'allsample_blast',i+"-"+j+".blast\n"])) 40 | summary_sh.write("cat "+os.sep.join([out,'allsample_blast',i+"-"+j+".blast"])+" >> "+os.sep.join([out,'all_blastp.out'])+"\n") 41 | summary_sh.writelines(["cat "+os.sep.join([args.i,i+pep_postfix])+ " >> " +os.sep.join([out,'all_sample.pep.faa'])+"\n", 42 | seqkit+" fx2tab -l " + os.sep.join([args.i,i+pep_postfix])+"|awk \'{print $1\"\\t\"$NF}\' >> "+os.sep.join([out,'all_sample.faa.length'])+"\n", 43 | seqkit+" fx2tab -l " + os.sep.join([args.i,i+pep_postfix])+"|awk \'{print $1\"\\t"+i+"\"}\' >> "+os.sep.join([out,'all_sample2fa.list'])+"\n"]) 44 | SH.close() 45 | sh_list.append(os.sep.join([out,'sample_sh',i+".sh"])) 46 | summary_sh.close() 47 | 48 | if not args.only_script: 49 | try: 50 | subprocess.run(diamond,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 51 | except FileNotFoundError: 52 | logging.error("diamond can not run.") 53 | sys.exit(0) 54 | try: 55 | subprocess.run(seqkit,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 56 | except FileNotFoundError: 57 | logging.error("seqkit can not run.") 58 | sys.exit(0) 59 | sh_pool=Pool(args.t//int(p)) 60 | sh_pool.map(sub_sh,sh_list) 61 | sh_pool.close() 62 | sh_pool.join() 63 | logging.info("ALL step1 blastp has done.") 64 | logging.info("Start sorting results..") 65 | stdout=subprocess.run(['sh',os.sep.join([out,'summary.sh'])],stdout=subprocess.PIPE, stderr=subprocess.PIPE) 66 | 67 | step1_sh.writelines("\n".join(sh_list)) 68 | step1_sh.write(os.sep.join([out,'summary.sh'])) 69 | step1_sh.close() 70 | -------------------------------------------------------------------------------- /tree2gd/dollop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.7 2 | 3 | import os 4 | import subprocess 5 | import logging 6 | import sys 7 | 8 | def run_dolloparsimony(step1out,step2out,step3out,dolloparsimony,args): 9 | logging.info("Writing step3 script files...") 10 | step3_sh=open(os.sep.join([step3out,'step3.sh']),"w") 11 | step3_sh.write(' '.join([dolloparsimony,args.tree,os.sep.join([step1out,'all_sample2fa.list']),os.sep.join([step2out,'allmcl.out.OGs.group']),os.sep.join([step3out,'dollop.out'])+"\n"])) 12 | step3_sh.write("less "+os.sep.join([step3out,'dollop.out','summary.tree'])+"|cut -d '[' -f2|cut -d ']' -f1 >"+os.sep.join([step3out,'dollop.out.scv'])) 13 | step3_sh.close() 14 | 15 | if not args.only_script: 16 | logging.info("Start runing step3 dollop: %s.."%(os.sep.join([step3out,'step3.sh']))) 17 | stdout=subprocess.run(['sh',os.sep.join([step3out,'step3.sh'])],stdout=subprocess.PIPE, stderr=subprocess.PIPE) 18 | logging.debug('{} stdout:\n'.format('step2.sh') +stdout.stdout.decode('utf-8')) 19 | logging.debug('{} stderr:\n'.format('step2.sh') +stdout.stderr.decode('utf-8')) 20 | logging.info("step3 dollop has done.") 21 | -------------------------------------------------------------------------------- /tree2gd/example_data/Alyrata.pep.dmnd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/example_data/Alyrata.pep.dmnd -------------------------------------------------------------------------------- /tree2gd/example_data/Athaliana.pep.dmnd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/example_data/Athaliana.pep.dmnd -------------------------------------------------------------------------------- /tree2gd/example_data/Brapa.pep.dmnd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/example_data/Brapa.pep.dmnd -------------------------------------------------------------------------------- /tree2gd/example_data/Cpapaya.pep.dmnd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/example_data/Cpapaya.pep.dmnd -------------------------------------------------------------------------------- /tree2gd/example_data/Crubella.pep.dmnd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/example_data/Crubella.pep.dmnd -------------------------------------------------------------------------------- /tree2gd/example_data/Esalsugineum.pep.dmnd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/example_data/Esalsugineum.pep.dmnd -------------------------------------------------------------------------------- /tree2gd/example_data/SVM_testdata.csv: -------------------------------------------------------------------------------- 1 | node,avg,median,GDratio,GDratio_forSynteny,filted_avg,filted_median,type 2 | phyto_0,0.830247319,0.7673995,0.2,0.1388,0.830247319,0.7673995,TRUE 3 | phyto_1,1.716856833,1.63813,0.0755,0.0619,1.716856833,1.63813,TRUE 4 | phyto_10,1.777817895,1.71415,0.0966,0.0626,1.760928061,1.689595,TRUE 5 | phyto_11,1.884820462,1.84439,0.0049,0.0029,1.9664836,1.96882,FALSE 6 | phyto_12,0.264103521,0.182391,0.7164,0.5178,0.255557935,0.181754,TRUE 7 | phyto_13,0.865846636,0.7727885,0.0533,0.0179,0.87091752,0.765723,FALSE 8 | phyto_14,1.436489667,1.36512,0.0044,7.00E-04,1.435073131,1.39087,FALSE 9 | phyto_15,1.246973802,1.27297,0.1481,0.0272,1.213000874,1.23256,TRUE 10 | phyto_16,1.699817614,1.805305,0.0076,0.006,1.34008125,1.03563,FALSE 11 | phyto_17,0.904912921,0.738326,0.0433,2.00E-04,0.92426911,0.82332,FALSE 12 | phyto_18,0.742636402,0.6199465,0.2056,0.1297,0.816025627,0.655325,TRUE 13 | phyto_19,1.072786652,0.881465,0.2396,0.1999,1.293624102,1.24222,TRUE 14 | phyto_2,2.008864359,1.97592,0.0025,9.00E-04,2.008864359,1.97592,FALSE 15 | phyto_20,1.71247915,1.581375,0.001,0.001,1.71247915,1.581375,FALSE 16 | phyto_21,1.149060211,1.015115,0.001,2.00E-04,0.968905257,0.644104,FALSE 17 | phyto_22,1.638626893,1.57601,0.0041,0.0012,1.516010072,1.47429,FALSE 18 | phyto_23,1.858982609,1.77731,0.0044,9.00E-04,1.74398551,1.5775,FALSE 19 | phyto_24,1.173308321,0.9839045,0.294,0.1501,1.175620776,1.01465,TRUE 20 | phyto_25,1.73642628,1.72003,0.0197,0.0116,1.733101679,1.66699,FALSE 21 | phyto_26,1.732264954,1.647395,0.0067,0.0013,1.772337295,1.65781,FALSE 22 | phyto_27,1.920841437,1.90297,0.0025,7.00E-04,2.048995769,2.01235,FALSE 23 | phyto_28,1.127167843,1.005545,0.2625,0.2194,1.15546611,1.0262,TRUE 24 | phyto_29,0.677240529,0.4325705,0.5599,0.2074,0.526231467,0.374115,TRUE 25 | phyto_3,1.73905,1.73905,2.00E-04,2.00E-04,1.73905,1.73905,FALSE 26 | phyto_30,1.274104917,1.14571,0.1234,0.0264,1.241139405,1.14105,FALSE 27 | phyto_31,1.667564478,1.604825,0.005,0.0018,1.818219633,1.796935,FALSE 28 | phyto_32,1.967217731,1.94207,0.0013,8.00E-04,1.723935714,1.37768,FALSE 29 | phyto_33,0.899296077,0.6708195,0.2948,0.138,0.771613572,0.661691,TRUE 30 | phyto_34,1.432131528,1.406945,0.0145,0.0066,1.147691906,1.06011,FALSE 31 | phyto_35,1.461243995,1.405525,0.2197,0.1714,1.474245872,1.420095,TRUE 32 | phyto_36,0.987110112,0.770211,0.3522,0.1974,0.96588876,0.7719905,TRUE 33 | phyto_37,1.263069101,1.22634,0.1095,0.0772,1.416515919,1.41641,TRUE 34 | phyto_38,1.798734541,1.87544,0.0033,0.0014,1.753934333,1.76154,FALSE 35 | phyto_39,1.760701123,1.70581,0.0057,0.0026,1.719684922,1.82868,FALSE 36 | phyto_4,1.401717286,1.37335,2.00E-04,2.00E-04,1.401717286,1.37335,FALSE 37 | phyto_40,1.813661255,1.812505,0.0027,0.0011,1.88720587,1.87687,FALSE 38 | phyto_41,0.405598029,0.232375,0.5699,0.4311,0.421114372,0.258104,TRUE 39 | phyto_42,0.869701229,0.721164,0.0327,0.0216,0.83457274,0.652139,FALSE 40 | phyto_43,0.950731935,0.739045,0.0318,0.0272,0.99271605,0.822635,TRUE 41 | phyto_44,1.669146714,1.68169,0.009,0.0046,1.449951178,1.42473,FALSE 42 | phyto_45,1.84607545,1.836125,0.0223,0.0151,1.858858378,1.83022,TRUE 43 | phyto_46,0.63941316,0.555904,0.1347,0.1121,0.611872806,0.551996,FALSE 44 | phyto_47,1.87897474,1.828935,7.00E-04,5.00E-04,1.835333225,1.76635,FALSE 45 | phyto_48,1.805100105,1.80499,0.0082,0.0035,1.687323,1.64587,FALSE 46 | phyto_49,1.773844531,1.817435,0.0086,0.0045,1.625741412,1.685565,FALSE 47 | phyto_5,0.544582314,0.347113,0.4892,0.3489,0.473387442,0.34208,TRUE 48 | phyto_50,0.877712525,0.690703,0.2889,0.1273,0.914484708,0.699327,TRUE 49 | phyto_51,1.409553508,1.36824,0.0624,0.0503,1.268408453,1.16408,TRUE 50 | phyto_52,1.348855796,1.18581,0.0118,0.0087,0.948361175,0.878747,FALSE 51 | phyto_53,1.771129336,1.83951,0.006,0.0021,1.584980652,1.67754,FALSE 52 | phyto_54,0.785229339,0.640975,0.3165,0.3165,0.86157692,0.745287,TRUE 53 | phyto_55,1.455982777,1.34057,0.0337,0.013,1.378596038,1.31125,FALSE 54 | phyto_56,1.509071725,1.437655,0.0966,0.02,1.461092862,1.389685,FALSE 55 | phyto_57,1.671020101,1.66885,0.1777,0.1111,1.70041211,1.71802,TRUE 56 | phyto_58,1.985524586,1.95661,0.0342,0.012,1.922155755,1.8853,TRUE 57 | phyto_59,1.791263737,1.74041,0.0155,0.0085,1.736374796,1.73989,FALSE 58 | phyto_6,1.07350977,0.9956145,0.0304,0.016,1.143293355,1.04959,FALSE 59 | phyto_60,1.643462864,1.56734,0.1595,0.0409,1.612996293,1.55787,TRUE 60 | phyto_61,1.720003,1.8117,0.0022,0.0011,1.720003,1.8117,FALSE 61 | phyto_62,1.798253649,1.73056,0.046,0.027,1.788658941,1.724965,TRUE 62 | phyto_63,1.750377589,1.68527,0.0128,0.0065,1.649184453,1.53735,FALSE 63 | phyto_64,1.859801116,1.934955,0.0072,0.0023,1.528754014,1.62588,FALSE 64 | phyto_65,1.573892591,1.639835,0.0177,0.0058,1.230738753,1.36926,FALSE 65 | phyto_66,1.886944021,2.00769,0.0053,0.001,1.450361459,1.75912,FALSE 66 | phyto_7,0.478209547,0.327562,0.5642,0.4821,0.546434606,0.374073,TRUE 67 | phyto_8,1.379345311,1.312515,0.0156,0.0046,1.392112641,1.322465,FALSE 68 | phyto_9,1.972832009,1.941325,0.0044,0.0013,1.750705362,1.63832,FALSE 69 | -------------------------------------------------------------------------------- /tree2gd/example_data/Tparvula.pep.dmnd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/example_data/Tparvula.pep.dmnd -------------------------------------------------------------------------------- /tree2gd/example_data/config.ini: -------------------------------------------------------------------------------- 1 | [iqtree] 2 | -B=0 3 | -------------------------------------------------------------------------------- /tree2gd/example_data/example.tree: -------------------------------------------------------------------------------- 1 | (Cpapaya,(((Athaliana,Alyrata),Crubella),(Esalsugineum,(Brapa,Tparvula)))); 2 | -------------------------------------------------------------------------------- /tree2gd/example_data/full_config.ini: -------------------------------------------------------------------------------- 1 | [software] 2 | 3 | diamond =/THE/PATH/OF/python/site-packages/software/diamond 4 | muscle=/THE/PATH/OF/python/site-packages/software/muscle 5 | iqtree=/THE/PATH/OF/python/site-packages/software/iqtree 6 | tree2gd=/THE/PATH/OF/python/site-packages/software/Tree2GD 7 | phymcl=/THE/PATH/OF/python/site-packages/software/PhyloMCL 8 | ParaAT=/THE/PATH/OF/python/site-packages/software/ParaAT.pl 9 | KaKs_Calculator=/THE/PATH/OF/python/site-packages/software/KaKs_Calculator 10 | calculate_4DTV=/THE/PATH/OF/python/site-packages/software/calculate_4DTV_correction.pl 11 | Epal2nal=/THE/PATH/OF/python/site-packages/software/Epal2nal.pl 12 | dolloparsimony=/THE/PATH/OF/python/site-packages/software/dolloparsimony 13 | [postfix] 14 | 15 | pep=.pep 16 | cds=.cds 17 | [diamond] 18 | 19 | -e=1e-10 20 | -p=4 21 | [phymcl] 22 | 23 | [mcl2fasta] 24 | min_taxa=4 25 | 26 | [iqtree] 27 | 28 | -B=1000 29 | -m=JTT+G4 30 | [tree2gd] 31 | 32 | --bp=50 33 | -------------------------------------------------------------------------------- /tree2gd/kaks.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.7 2 | import os 3 | import subprocess 4 | import logging 5 | import sys 6 | from tree2gd.seq import read_fasta_file 7 | import configparser 8 | import subprocess 9 | from multiprocessing import Pool 10 | import re 11 | 12 | def run_kaks(sp_list,step1out,args,config,step4out,step5out,gene_pairs_idmap): 13 | logging.info("Writing step5 script files...") 14 | op='' 15 | if not config.has_section('KaKs_Calculator'): 16 | config.add_section('KaKs_Calculator') 17 | if not config.has_option("KaKs_Calculator", "-m"): 18 | config.set("KaKs_Calculator", "-m","YN") 19 | for k,v in config.items("KaKs_Calculator"): 20 | op=' '.join((op,' '.join((k,v)))) 21 | step5_sh=open(os.sep.join([step5out,'step5.sh']),"w") 22 | KaKs_Calculator=config.get("software", "KaKs_Calculator") 23 | Kaks_aligncmd=config.get("software", "muscle") 24 | Epal2nal=config.get("software", "Epal2nal") 25 | step5_sh.writelines([ "perl ParaAT.pl -kaks "+KaKs_Calculator+op+" -h "+os.sep.join([step5out,"all_gene_pairs.list"]) 26 | +" -n "+os.sep.join([step5out,"all_cds.fa"])+" -a "+os.sep.join([step5out,'all_pep.fa'])+" -p "+str(args.t)+" -k -f axt -o "+os.sep.join([step5out,"all_gene_pairs_kaks"])+"\n", 27 | "cd "+os.sep.join([step5out,"all_gene_pairs_kaks"])+"\n", 28 | "for i in `ls *.axt`;do axt2one-line.py $i ${i}.one-line;done\n", 29 | "ls *.one-line|while read id;do calculate_4DTV_correction.pl $id >${id%%one-line}4dtv;done\n" 30 | "for i in `ls *.4dtv`;do awk 'NR>1{print $1\"\t\"$2}' $i >>all-4dtv.txt;done\n", 31 | "for i in `ls *.kaks`;do awk 'NR>1{print $1\"\t\"$3\"\t\"$4\"\t\"$5}' $i >>all-kaks.txt;done\n", 32 | "sort all-4dtv.txt|uniq >all-4dtv.results\n", 33 | "sort all-kaks.txt|uniq >all-kaks.results\n", 34 | "join -1 1 -2 1 all-kaks.results all-4dtv.results >all-results.txt\n", 35 | "sed -i '1i\Seq\tKa\tKs\tKa/Ks\t4dtv_corrected' all-results.txt\n" 36 | ]) 37 | step5_sh.close() 38 | if not args.only_script: 39 | logging.info("Start KaKs calculation.") 40 | pepmap={} 41 | cdsmap={} 42 | logging.info("Readfile") 43 | for s in read_fasta_file(os.sep.join([step5out,'all_pep.fa'])): 44 | pepmap[s.name]=s.seq 45 | for s in read_fasta_file(os.sep.join([step5out,'all_cds.fa'])): 46 | cdsmap[s.name]=s.seq 47 | if not os.path.exists(os.sep.join([step5out,"sp_kaks_out"])): 48 | os.mkdir(os.sep.join([step5out,"sp_kaks_out"])) 49 | if not os.path.exists(os.sep.join([step5out,"all_gene_pairs_kaks"])): 50 | os.mkdir(os.sep.join([step5out,"all_gene_pairs_kaks"])) 51 | logging.info("Make dir") 52 | os.chdir(os.sep.join([step5out,"all_gene_pairs_kaks"])) 53 | logging.info("Start gene pairs kaks calculation.") 54 | a=0 55 | pairs_num=len(gene_pairs_idmap) 56 | b=pairs_num//20 57 | arg_list=[] 58 | 59 | for pair in gene_pairs_idmap: 60 | tmp=(pair,pepmap,cdsmap,KaKs_Calculator,Kaks_aligncmd,Epal2nal,op) 61 | arg_list.append(tmp) 62 | sh_pool=Pool(args.t) 63 | sh_pool.map(run_ks,arg_list) 64 | #a=a+1 65 | #sh_pool.apply_async(sub_sh,args=(pair,pepmap,cdsmap,KaKs_Calculator,Kaks_aligncmd,Epal2nal,op),callback=write_result) 66 | #if(a%b==0): 67 | # logging.info("%s \%(%s pairs) completed."%((a//b)*5)%(a)) 68 | sh_pool.close() 69 | sh_pool.join() 70 | logging.info("Gene pairs kaks calculation finish.") 71 | logging.info("Start summarize the Ks results of each species.") 72 | for pair in gene_pairs_idmap: 73 | if os.path.exists(pair[2]+"-"+pair[3]+".cds_aln.axt.kaks"): 74 | if os.path.getsize(pair[2] + "-" + pair[3] + ".cds_aln.axt.kaks"): 75 | out=sum_Ks(pair) 76 | write_result(out) 77 | a=a+1 78 | if(a%b==0): 79 | logging.info("%d %% (%d pairs) completed."%((a//b)*5,a)) 80 | 81 | logging.info("ALL step5 kaks has done.") 82 | 83 | def run_ks(args): 84 | sub_sh(args[0],args[1],args[2],args[3],args[4],args[5],args[6]) 85 | 86 | def sum_Ks(pair): 87 | out=[] 88 | with open(pair[2]+"-"+pair[3]+".cds_aln.axt.kaks") as kaks_file,open(pair[2]+"-"+pair[3]+".4dtv") as DTV_file: 89 | kaks=kaks_file.readlines()[1].split("\t") 90 | line=DTV_file.readlines() 91 | if len(line)>1: 92 | dtv=line[1].split("\t") 93 | else: 94 | dtv=["0","NA"] 95 | out=[pair[1],pair[0],pair[2],pair[3],kaks[2],kaks[3],kaks[4],dtv[1]] 96 | return out 97 | 98 | def sub_sh(pair,pepmap,cdsmap,KaKs_Calculator,Kaks_aligncmd,Epal2nal,op): 99 | out=[] 100 | home_dir=os.path.dirname(os.path.abspath(__file__)) 101 | try: 102 | pepseq1 = pepmap[pair[2]] 103 | pepseq2 = pepmap[pair[3]] 104 | cdsseq1 = cdsmap[pair[2]] 105 | cdsseq2 = cdsmap[pair[3]] 106 | with open(pair[2]+"-"+pair[3]+".pep","a") as outfile: 107 | outfile.write(">"+pair[2]+"\n"+pepseq1+"\n") 108 | outfile.write(">"+pair[3]+"\n"+pepseq2+"\n") 109 | with open(pair[2]+"-"+pair[3]+".cds","a") as outfile: 110 | outfile.write(">"+pair[2]+"\n"+cdsseq1+"\n") 111 | outfile.write(">"+pair[3]+"\n"+cdsseq2+"\n") 112 | 113 | except: 114 | logging.info("err") 115 | pass 116 | stdout=subprocess.run(Kaks_aligncmd+" -quiet -in "+pair[2]+"-"+pair[3]+".pep -out "+pair[2]+"-"+pair[3]+".pep_aln >> msg.msa",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 117 | Epal2nal_stdout=subprocess.run(Epal2nal+" "+pair[2]+"-"+pair[3]+".pep_aln "+pair[2]+"-"+pair[3]+".cds -output fasta -nogap -nomismatch > "+pair[2]+"-"+pair[3]+".cds_aln",shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 118 | if not os.path.getsize(pair[2]+"-"+pair[3]+".cds_aln"): 119 | logging.warn(pair[2]+"-"+pair[3]+".cds_aln is empty,Processing of this gene pair has been skipped, please check for special characters in the protein sequence") 120 | pass 121 | else: 122 | trimal_stdout=subprocess.run("trimal -in "+pair[2]+"-"+pair[3]+".cds_aln -out "+pair[2]+"-"+pair[3]+".filted.cds_aln -automated1 -resoverlap 0.7 -seqoverlap 75",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 123 | Fasta2AXT(pair[2]+"-"+pair[3]+".filted.cds_aln",pair[2]+"-"+pair[3]+".cds_aln.axt") 124 | kaks_stdout=subprocess.run(KaKs_Calculator+op+" -i "+pair[2]+"-"+pair[3]+".cds_aln.axt -o "+pair[2]+"-"+pair[3]+".cds_aln.axt.kaks >> msg.kaks",shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 125 | axt2oneline((pair[2]+"-"+pair[3]+".cds_aln.axt"),(pair[2]+"-"+pair[3]+".one-line")) 126 | stdout=subprocess.run("perl "+os.sep.join([home_dir,"software","calculate_4DTV_correction.pl"])+" "+pair[2]+"-"+pair[3]+".one-line"+" > "+pair[2]+"-"+pair[3]+".4dtv",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 127 | 128 | 129 | def write_result(input): 130 | with open(os.sep.join(["..","sp_kaks_out",input[0]+".kaks_4dtv.result"]),"a+") as out: 131 | out.write("\t".join([input[0],input[1],input[2],input[3],input[4],input[5],input[6],input[7]])+"\n") 132 | 133 | 134 | def Fasta2AXT(input,output): 135 | id="" 136 | seq="" 137 | for s in read_fasta_file(input): 138 | if id=="": 139 | id=s.name 140 | else: 141 | id=id+"-"+s.name 142 | if seq=="": 143 | seq=s.seq 144 | else: 145 | seq=seq+'\n'+s.seq 146 | with open(output,"w") as outfile: 147 | outfile.write(id+"\n"+seq+"\n") 148 | 149 | def axt2oneline(reader,out):#copyed 150 | mydict = {} 151 | writer = open(out,"w") 152 | with open(reader) as fh: 153 | for line in fh: 154 | if re.search("-",line): 155 | header = line.strip() 156 | mydict[header] = [] 157 | else: 158 | mydict[header].append(line.strip()) 159 | for key,value in mydict.items(): 160 | seqs = "".join(value) 161 | length = len(seqs) 162 | mid = int(length/2) 163 | seq1 = seqs[0:mid] 164 | seq2 = seqs[mid:] 165 | writer.write(key + "\n" + "\n".join([seq1,seq2])) 166 | writer.close() 167 | -------------------------------------------------------------------------------- /tree2gd/mcl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.7 2 | import os 3 | import subprocess 4 | import logging 5 | import sys 6 | 7 | def run_phymcl(step1out,phymcl,args,options,step2out): 8 | logging.info("Writing step2 script files...") 9 | op='' 10 | for k,v in options: 11 | op=' '.join((op,' '.join((k,v)))) 12 | step2_sh=open(os.sep.join([step2out,'step2.sh']),"w") 13 | step2_sh.write(phymcl+ " -in " +os.sep.join([step1out,'all_blastp.out'])+" -threads "+ str(args.t) + " -length " + os.sep.join([step1out,'all_sample.faa.length']) + 14 | " -species " + os.sep.join([step1out,'all_sample2fa.list']) + " -tree " + os.sep.join([step2out,"phymcl.input.tree"]) + " -out " + os.sep.join([step2out,'allmcl.out'])+"\n") 15 | step2_sh.close() 16 | if not args.only_script: 17 | try: 18 | subprocess.run(phymcl,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 19 | except FileNotFoundError: 20 | logging.error("phymcl can not run.") 21 | sys.exit(0) 22 | logging.info("Start runing step2 MCL: %s.."%(os.sep.join([step2out,'step2.sh']))) 23 | stdout=subprocess.run(['sh',os.sep.join([step2out,'step2.sh'])],stdout=subprocess.PIPE, stderr=subprocess.PIPE) 24 | logging.debug('{} stdout:\n'.format('step2.sh') +stdout.stdout.decode('utf-8')) 25 | logging.debug('{} stderr:\n'.format('step2.sh') +stdout.stderr.decode('utf-8')) 26 | logging.info("step2 mcl has done.") 27 | -------------------------------------------------------------------------------- /tree2gd/plot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.7 2 | import os 3 | import subprocess 4 | import logging 5 | import sys 6 | import configparser 7 | import subprocess 8 | from multiprocessing import Pool 9 | import re 10 | 11 | from pyecharts import options as opts 12 | from pyecharts.charts import Bar 13 | from pyecharts.faker import Faker 14 | 15 | 16 | def run_plot(step6out,args,cf): 17 | logging.info("Start step6 summary plot...") 18 | os.chdir(step6out) 19 | if args.synteny: 20 | logging.info("Writing synteny script files...") 21 | sp_num = len(sp_list) 22 | op = '' 23 | sh_list = [] 24 | step6_sh = open(os.sep.join([out, 'step6.sh']), "w") 25 | for k, v in options: 26 | op = ' '.join((op, ' '.join((k, v)))) 27 | for i in sp_list: 28 | SH = open(os.sep.join([out, 'sample_sh', i + ".sh"]), "w") 29 | SH.write('python -m jcvi.compara.catalog ortholog --no_strip_names --cscore=.99 ' + os.sep.join( 30 | [args.i, i]) + " " + os.sep.join([args.i, i]) + "\n") 31 | SH.close() 32 | sh_list.append(os.sep.join([out, 'sample_sh', i + ".sh"])) 33 | 34 | if not args.only_script: 35 | try: 36 | subprocess.run('python -m jcvi.compara.catalog', stdout=subprocess.PIPE, stderr=subprocess.PIPE) 37 | except FileNotFoundError: 38 | logging.error("jcvi can not run.") 39 | sys.exit(0) 40 | 41 | sh_pool = Pool(int(p)) 42 | sh_pool.map(sub_sh, sh_list) 43 | sh_pool.close() 44 | sh_pool.join() 45 | logging.info("ALL synteny has done.") 46 | logging.info("Start sorting results..") 47 | stdout = subprocess.run(['sh', os.sep.join([out, 'summary.sh'])], stdout=subprocess.PIPE, 48 | stderr=subprocess.PIPE) 49 | 50 | step6_sh.writelines("\n".join(sh_list)) 51 | step6_sh.write(os.sep.join([out, 'summary.sh'])) 52 | step6_sh.close() 53 | if not args.only_script: 54 | stdout=subprocess.run('Rscript '+'Tree2GD_draw.R',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 55 | logging.info("R plot done.") 56 | logging.debug('{} stdout:\n'.format("Tree2GD_draw.R") +stdout.stdout.decode('utf-8')) 57 | logging.debug('{} stderr:\n'.format("Tree2GD_draw.R") +stdout.stderr.decode('utf-8')) 58 | logging.info("Start html plot ...") 59 | if not os.path.exists(os.sep.join([step6out,"ks_html_plot"])): 60 | os.mkdir(os.sep.join([step6out,"ks_html_plot"])) 61 | file_names=[] 62 | file_names = os.listdir("html_plot_in") 63 | os.chdir(os.sep.join([step6out,"html_plot_in"])) 64 | sh_pool=Pool(args.t) 65 | sh_pool.map(html_plot,file_names) 66 | sh_pool.close() 67 | sh_pool.join() 68 | stdout=subprocess.run('Rscript '+'SVM.R',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 69 | logging.info("SVM plot done.") 70 | logging.debug('{} stdout:\n'.format("SVM.R") +stdout.stdout.decode('utf-8')) 71 | logging.debug('{} stderr:\n'.format("SVM.R") +stdout.stderr.decode('utf-8')) 72 | logging.info("ALL step6 plot has done.") 73 | 74 | def html_plot(file): 75 | sp=file.split(".") 76 | with open(file) as f: 77 | l=f.readlines() 78 | i=0 79 | ks={} 80 | for line in l: 81 | if i==0: 82 | head=line.strip().split("\t") 83 | i=1 84 | else: 85 | t=line.strip().split("\t") 86 | name=t[0] 87 | del t[0] 88 | ks[name]=t 89 | bar=Bar(init_opts=opts.InitOpts(page_title=sp[0]+"-ks.htmlpolt",width="1500px",height="700px")) 90 | bar.add_xaxis(head) 91 | for key,value in ks.items(): 92 | bar.add_yaxis(key,value,category_gap=0,stack="stack1",is_large=True) 93 | bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) 94 | bar.set_global_opts( 95 | title_opts=opts.TitleOpts(title=sp[0]+".ks.polt",subtitle="Plot by Tree2gd v1.0"), 96 | toolbox_opts=opts.ToolboxOpts(is_show=True,pos_top='10%',orient='vertical',pos_left='right',feature=opts.ToolBoxFeatureOpts( 97 | save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(title="Save as png"), 98 | restore=opts.ToolBoxFeatureRestoreOpts(title="Recovery"), 99 | data_view=opts.ToolBoxFeatureDataViewOpts(title="Data",lang=['Data View','Close','Refresh']), 100 | data_zoom=opts.ToolBoxFeatureDataZoomOpts(is_show=False), 101 | magic_type=opts.ToolBoxFeatureMagicTypeOpts(line_title="Switch to line plot",bar_title="Switch to histogram plot",stack_title="Switch to stack plot",tiled_title="Switch to tiled plot"), 102 | brush=opts.ToolBoxFeatureBrushOpts(rect_title="Rectangle selection",polygon_title="Circle selection",line_x_title="X line selection",line_y_title="Y line selection",keep_title="Keep selection",clear_title="Clear selection"), 103 | )), 104 | legend_opts=opts.LegendOpts(pos_left = 'right',), 105 | datazoom_opts=[opts.DataZoomOpts(range_start=0,range_end=60),opts.DataZoomOpts(type_="inside")], 106 | xaxis_opts=opts.AxisOpts(name="Ks"),) 107 | bar.render(os.sep.join(["..","ks_html_plot",sp[0]+".ks.plot.html"])) 108 | -------------------------------------------------------------------------------- /tree2gd/seq.py: -------------------------------------------------------------------------------- 1 | offset =33 # 33 for most newer reads, 64 for old Illumina reads 2 | 3 | class Sequence: 4 | def __init__(self,name="",seq=""): 5 | self.name = name 6 | self.seq = seq 7 | self.qualstr = "" #string of quality scores in characters 8 | self.qualarr = [] #list of quality scores in ASCII numbers 9 | 10 | #input a string of quality characters, set both qualstr and qualarr 11 | def set_qualstr(self,qual): 12 | self.qualstr = qual 13 | if len(self.qualarr) == 0: 14 | for j in self.qualstr: 15 | quality_score = ord(j) - offset 16 | self.qualarr.append(quality_score) 17 | assert quality_score <= 41 and quality_score > 0, \ 18 | "Change the offset in seq.py\nqual" 19 | 20 | #output in four-line fastq format 21 | def get_fastq(self): 22 | retstr = "@"+self.name+"\n" 23 | retstr += self.seq+"\n" 24 | retstr += "+\n" 25 | retstr += self.qualstr+"\n" 26 | return retstr 27 | 28 | def get_fasta(self): 29 | return ">"+self.name+"\n"+self.seq+"\n" 30 | 31 | def rev_comp(self): 32 | tseq = "" 33 | for i in self.seq[::-1]: 34 | if i.lower() == "a": 35 | tseq += "t" 36 | elif i.lower() == "t": 37 | tseq += "a" 38 | elif i.lower() == "c": 39 | tseq += "g" 40 | elif i.lower() == "g": 41 | tseq += "c" 42 | else: 43 | tseq += i 44 | self.seq = tseq 45 | 46 | def fastq_generator(infile): 47 | line = infile.readline() 48 | while len(line) > 0: #no empty string at end-of-file in readline 49 | if line[0] == "@": 50 | name = line[1:].strip() #name of sequence, minus "@" 51 | seq = infile.readline().strip() #the actual sequence 52 | line = infile.readline().strip() #"+" 53 | qual = infile.readline().strip() #the quality string 54 | tseq = Sequence(name=name,seq=seq) 55 | tseq.set_qualstr(qual) 56 | yield tseq 57 | line = infile.readline() 58 | 59 | 60 | 61 | def read_fasta_file(filename): 62 | """given the path to a fasta file, retern a list of seq objects""" 63 | fl = open(filename,"r") 64 | seqlist = [] #list of sequence objects 65 | templab = "" 66 | tempseq = "" 67 | first = True 68 | for i in fl: 69 | if i[0] == ">": 70 | if first == True: 71 | first = False 72 | else:#if not first store lastseq read 73 | seqlist.append(Sequence(templab,tempseq)) 74 | templab = i.strip()[1:].split(" ")[0] 75 | tempseq = "" 76 | else: 77 | tempseq = tempseq + i.strip() 78 | fl.close() 79 | seqlist.append(Sequence(templab,tempseq)) 80 | return seqlist 81 | -------------------------------------------------------------------------------- /tree2gd/seq.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/seq.pyc -------------------------------------------------------------------------------- /tree2gd/software/KaKs_Calculator: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/software/KaKs_Calculator -------------------------------------------------------------------------------- /tree2gd/software/PhyloMCL: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/software/PhyloMCL -------------------------------------------------------------------------------- /tree2gd/software/SVM.R: -------------------------------------------------------------------------------- 1 | options(repos=structure(c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))) 2 | options(repos=structure(c(CRAN="http://cran.us.r-project.org"))) 3 | if (!requireNamespace("BiocManager", quietly = TRUE)) 4 | install.packages("BiocManager") 5 | if (!requireNamespace("e1071", quietly = TRUE)) BiocManager::install("e1071") 6 | if (!requireNamespace("ggplot2", quietly = TRUE)) BiocManager::install("ggplot2") 7 | if (!requireNamespace("dplyr", quietly = TRUE)) BiocManager::install("dplyr") 8 | 9 | library(e1071) 10 | library(dplyr) 11 | library(ggplot2) 12 | lm_eqn <- function(df,x,y){ 13 | m <- lm(y ~ x, df); 14 | eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2*", p-value="~p, 15 | list(a = format(unname(coef(m)[1]), digits = 2), 16 | b = format(unname(coef(m)[2]), digits = 2), 17 | r2 = format(summary(m)$r.squared, digits = 3), 18 | p = format(as.numeric(summary(m)$coefficients[,4][2]), digits = 3))) 19 | as.character(as.expression(eq)); 20 | } 21 | 22 | a = list.files("sp_kaks_out/") 23 | dir = paste("./sp_kaks_out/",a,sep="") 24 | n = length(dir) 25 | merge.data = read.csv(file = dir[1],sep="\t",header = F) 26 | for (i in 2:n){ 27 | new.data = read.csv(file = dir[i], sep="\t",header = F) 28 | merge.data = rbind(merge.data,new.data) 29 | } 30 | merge.data=merge.data[which(merge.data$V6<=2),] 31 | kaks_table=aggregate(merge.data[,6],by=list(type=merge.data[,2]),mean) 32 | 33 | 34 | ratio_data=read.table("Tree2GD_out/summarytable.txt",header = T) 35 | wgd_data=merge(x = ratio_data,y = kaks_table,by.x = "Newick_label",by.y = "type") 36 | wgd_data=wgd_data[grep("^phyto", wgd_data[,1]),] 37 | wgd_data$GDratio=as.numeric(sub("%", "", wgd_data$GDratio))/100 38 | wgd_data[is.na(wgd_data)]<-0 39 | 40 | 41 | if("type" %in% colnames(wgd_data)){ 42 | type=wgd_data$type 43 | x=data.frame(x, type=as.factor(type)) 44 | 45 | svm.model <- svm(type~.,data=x,kernel="linear",cost=5,scale = FALSE) 46 | summary(svm.model) 47 | plot(svm.model, x, ks ~ log_ratio) 48 | 49 | 50 | 51 | w=t(svm.model$coefs)%*%svm.model$SV 52 | b=-svm.model$rho 53 | x$node=wgd_data$Newick_label 54 | 55 | p=ggplot(x[which(x$type=="TRUE"),],aes(x=as.numeric(ks),y=as.numeric(log_ratio),label=node))+ 56 | geom_point(size=4,colour="red")+ 57 | theme_classic()+ 58 | geom_text(size=5,vjust = "inward", hjust = "inward")+ 59 | stat_smooth(color = "blue",formula=y ~x,method = "lm",lty=2)+ 60 | labs(title ="", x="Ks",y="ln(GD_raito)",size=5)+ 61 | geom_point(data=x[which(x$type!="TRUE"),],mapping=aes(x=as.numeric(ks),y=as.numeric(log_ratio),label=node),shape=3,size=3,colour="blue",show.legend=FALSE) 62 | p1 <- p + 63 | geom_text(x = 1.5, y = -0.5, label =lm_eqn(x[which(x$type=="TRUE"),],as.numeric(x[which(x$type=="TRUE"),"ks"]),as.numeric(x[which(x$type=="TRUE"),"log_ratio"])), 64 | parse = TRUE,colour="blue",size=5) 65 | p2 <- p1 +geom_abline(aes(intercept=-b/w[1,2],slope=-w[1,1]/w[1,2]),lty=2,colour="red",size=1) + 66 | geom_text(x =0.5, y = -2.5,label = paste("SVM: y = ",round(-w[1,1]/w[1,2],2),"x",round(-b/w[1,2],2)),colour="red",size=5) 67 | print(p2) 68 | 69 | }else { 70 | x=data.frame(cbind(wgd_data$x,log(wgd_data$GDratio))) 71 | colnames(x)=c("ks","log_ratio") 72 | x[,"type"]=x[,"ks"] 73 | for(i in 1:nrow(x)){ 74 | if(x[i,"log_ratio"]>x[i,"ks"]*(-1.28)-1.3){ 75 | x[i,"type"]="TRUE"; 76 | } else { 77 | x[i,"type"]="FALSE"; 78 | } 79 | } 80 | ###########No know WGD loci were given, using the classification planes obtained in the 68 plants data. 81 | a=-1.28 82 | b=-1.3 83 | x$node=wgd_data$Newick_label 84 | 85 | p=ggplot(x[which(x$type=="TRUE"),],aes(x=as.numeric(ks),y=as.numeric(log_ratio),label=node))+ 86 | geom_point(size=4,colour="red")+ 87 | theme_classic()+ 88 | geom_text(size=5,vjust = "inward", hjust = "inward")+ 89 | stat_smooth(color = "blue",formula=y ~x,method = "lm",lty=2)+ 90 | labs(title ="", x="Ks",y="ln(GD_raito)",size=5)+ 91 | geom_point(data=x[which(x$type=="FALSE"),],mapping=aes(x=as.numeric(ks),y=as.numeric(log_ratio),label=node),shape=3,size=3,colour="blue",show.legend=FALSE) 92 | p1 <- p + 93 | geom_text(x = 1.5, y = -0.5, label =lm_eqn(x[which(x$type=="TRUE"),],as.numeric(x[which(x$type=="TRUE"),"ks"]),as.numeric(x[which(x$type=="TRUE"),"log_ratio"])), 94 | parse = TRUE,colour="blue",size=5) 95 | p2 <- p1 +geom_abline(aes(intercept=b,slope=a),lty=2,colour="red",size=1) + 96 | geom_text(x =0.5, y = -2.5,label = paste("SVM: y = "," +",a,"x",b),colour="red",size=5) 97 | print(p2) 98 | 99 | } 100 | -------------------------------------------------------------------------------- /tree2gd/software/Tree2GD: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/software/Tree2GD -------------------------------------------------------------------------------- /tree2gd/software/Tree2GD_draw.R: -------------------------------------------------------------------------------- 1 | options(repos=structure(c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))) 2 | options(repos=structure(c(CRAN="http://cran.us.r-project.org"))) 3 | if (!requireNamespace("BiocManager", quietly = TRUE)) 4 | install.packages("BiocManager") 5 | if (!requireNamespace("ggtree", quietly = TRUE)) BiocManager::install("ggtree") 6 | if (!requireNamespace("ggplot2", quietly = TRUE)) BiocManager::install("ggplot2") 7 | if (!requireNamespace("ggridges", quietly = TRUE)) BiocManager::install("ggridges") 8 | if (!requireNamespace("RColorBrewer", quietly = TRUE)) BiocManager::install("RColorBrewer") 9 | if (!requireNamespace("ggplotify", quietly = TRUE)) BiocManager::install("ggplotify") 10 | library("ggtree") 11 | library("RColorBrewer") 12 | library("ggplot2") 13 | library("ggridges") 14 | library("ggplotify") 15 | library("grid") 16 | library("scales") 17 | 18 | tree=read.tree("./Tree2GD_out/Phtree.nwk") 19 | summary=read.table("./Tree2GD_out/summarytable.txt",header = T) 20 | gdtype=read.table("./Tree2GD_out/GDtype_stat.txt",header = T) 21 | dollop=read.csv("./dollop.out.scv",header = F) 22 | kaks_file_list=list.files("./sp_kaks_out/") 23 | all_kaks_result=data.frame() 24 | kaks_list=c() 25 | 26 | for(F in kaks_file_list){ 27 | sp_name=strsplit(F,'[.]')[[1]][1] 28 | kaks_list=c(kaks_list,sp_name) 29 | tmp=read.table(paste('./sp_kaks_out/',F,sep = "")) 30 | colnames(tmp)=c("sp","level","gene.1","gene.2","ka","ks","ka.ks","4dtv") 31 | assign(sp_name,tmp) 32 | t=get(sp_name) 33 | t$Node=t$level 34 | t$sum=t$ks 35 | for(l in summary$Newick_label){ 36 | if(l %in% t$level){ 37 | a=table(cut(t[which(t$level==l&t$ks<3),6],breaks=seq(0,3,by=0.01))) 38 | tmp=which(a==a[which.max(a)],arr.ind=T)[1]*0.01 39 | num=length(t[which(t$level==l),]$ks) 40 | t[which(t$level==l),]$Node=paste(t[which(t$level==l),]$level,"(",num,";",tmp,")") 41 | t[which(t$level==l),]$sum=num 42 | } 43 | } 44 | all_kaks_result=rbind(all_kaks_result,get(sp_name)) 45 | assign(sp_name,t) 46 | } 47 | 48 | 49 | dollop=cbind(summary[,1],dollop) 50 | names(dollop)=c(names(summary)[1],"up","down","all") 51 | dollop$up=paste("+",dollop$up) 52 | 53 | gdtype$AABBratio=round(as.numeric(gdtype[[2]]/(gdtype[[2]]+gdtype[[3]]+gdtype[[4]])),2) 54 | t=paste(gdtype$AABBratio*100,"%") 55 | gdtype$describe=t 56 | 57 | 58 | summary$GD=paste(summary$GD,"/",summary$NUM) 59 | summary$GDratio=as.double(lapply(summary$GDratio, function(x) as.numeric(gsub("\\%", "", x))/100)) 60 | summary$GDratio=round(summary$GDratio,2) 61 | 62 | tree$edge.length=rep(1,length(tree$edge[,1])) 63 | 64 | ################################### 65 | dir.create("./R_plotout/") 66 | dir.create("./html_plot_in/") 67 | 68 | cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7","#0f4c75","#d7385e","#d2e603","#ff4b5c","#1f3c88","#03c4a1","#f39233","#7579e7") 69 | for(F in kaks_list){ 70 | pdf(paste("./R_plotout/",F,".ks.R.result.pdf",sep = ""),width = 15, height = 6) 71 | kaks=get(F) 72 | kaks_p=ggplot(kaks[which(kaks$ks<3),],aes(x=ks,fill=Node))+geom_histogram(binwidth = 0.05,alpha = 0.8,colour="black",size=0.3,position ="stack",show.legend=FALSE)+ 73 | labs(x = "Ks",y = "Number of Gene Pairs",title = paste(" Ks-plot of paralogs from ",F,sep = ""))+ 74 | scale_fill_manual(values=cbPalette)+ 75 | scale_colour_manual(values=cbPalette)+scale_y_continuous(expand = c(0,0))+scale_x_continuous(expand = c(0,0))+ 76 | theme_classic()+theme(legend.key.size = unit(10, "pt"),legend.position=c(.9,.7),legend.key = element_blank(),legend.background = element_blank(),legend.text = element_text(size = 6),legend.title = element_text(size = 8)) 77 | ks_p=ggplot(kaks[which(kaks$ks<3),],aes(x=ks,y=Node,fill=Node,alpha=rescale(sum,c(0,1))))+ 78 | geom_density_ridges_gradient(scale=3,size=0.3,rel_min_height=0.00,show.legend=FALSE)+ 79 | scale_fill_manual(values=cbPalette)+ 80 | scale_y_discrete(position = "right")+ theme_minimal()+theme(title=element_text(size=7))+ 81 | labs(x = "Ks",title ="Density Ridges Gradient of Gene Pairs Number",y="") 82 | vp <- viewport(width = 0.2, height = 0.4, x = 0.95,y = 0.9,just=c("right","top")) 83 | print(kaks_p) 84 | print(ks_p,vp=vp) 85 | dev.off() 86 | test=data.frame() 87 | node=c() 88 | for(l in unique(kaks$level)){ 89 | hist_data=table(cut(kaks[which(kaks$level==l&kaks$ks<5),6],breaks=seq(0,5,by=0.05))) 90 | test=rbind(test,hist_data) 91 | node=c(node,l) 92 | } 93 | rownames(test)=node 94 | colnames(test)=seq(0,5,by=0.05)[-1] 95 | write.table(test,paste("./html_plot_in/",F,"_gd2ks.txt",sep = ""),sep = "\t",quote=FALSE) 96 | } 97 | 98 | 99 | 100 | ########################### 101 | 102 | summary$pho=substr(summary$Newick_label,7,10) 103 | p=ggtree(tree,size=rel(0.5),branch.length='none') %<+% summary %<+% dollop %<+% gdtype+geom_tippoint(color="#56556e",size=3) 104 | 105 | p2=p+xlim_tree(max(p$data$x)+1.3)+geom_tiplab(offset = 0, hjust = 0,size=7)+geom_rootedge(rootedge = 1)+ 106 | geom_label2(aes(label=pho,subset = !is.na(as.numeric(pho)))) 107 | 108 | p3=p2+ 109 | geom_label(aes(x=branch, label=all), fill='grey',label.size = 0.2,size = 3,colour="blue")+ 110 | geom_text(aes(x=branch, label=up), colour='green',size = 3,vjust=-1.5,check_overlap = T)+ 111 | geom_text(aes(x=branch, label=down), colour='red',size = 3,vjust=+2.5)+ 112 | scale_colour_manual(values =palette(rainbow(as.numeric(length(tree$tip.label)))),guide = FALSE)+ 113 | geom_label(aes(label=describe),size = 3,vjust=+4,fill="#a5ecd7",label.padding = unit(0.03, "lines"),label.size=0.2,show.legend=FALSE)+ 114 | #scale_fill_gradientn(colors = colorRampPalette(rev(brewer.pal(7,'RdYlBu')))(35),position="right",name="Color gradient")+ 115 | geom_label(aes(label=GD),size = 3.5,fill= "#ff9a76",vjust=2,label.padding = unit(0.1, "lines"),label.size=0.2,show.legend=FALSE)+ 116 | theme_classic() 117 | 118 | p4=p3+geom_facet(data=all_kaks_result[which(all_kaks_result$ks<2&!is.na(all_kaks_result$ks)),],mapping = aes(x=`ks`,group=label,height = stat(density)),stat = "density",col="#e94560",size=0.5,scale = 2,rel_min_height = 0.01,alpha=15,geom=geom_density_ridges_gradient,panel = 'Ks Plot')+ 119 | geom_facet(data=all_kaks_result[which(all_kaks_result$`4dtv`<1&!is.na(all_kaks_result$`4dtv`)),],mapping = aes(x=`4dtv`,group=label,height = stat(density)),stat = "density",col="#e94560",size=0.5,scale = 2,rel_min_height = 0.01,alpha=15,geom=geom_density_ridges_gradient,panel = '4dtv Plot') 120 | 121 | 122 | p5=p4%>%facet_labeller(c(Tree = "phylogeny")) %>% facet_widths(c(Tree =1,'4dtv Plot'=0.1,'Ks Plot'=0.1)) 123 | 124 | 125 | 126 | pdf("Tree2GD.result.pdf", width = (max(p$data$x)+1)*1.7, height = length(tree$tip.label)/2+2) 127 | print(p5) 128 | dev.off() 129 | -------------------------------------------------------------------------------- /tree2gd/software/calculate_4DTV_correction.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | use strict; 3 | 4 | ##author: sun ming'an, sunma@genomics.org.cn 5 | ##modifier: fanwei, fanw@genomics.org.cn 6 | ##correction: LiJun, junli@genomics.org.cn 7 | ##Date: 2008-9-24 8 | 9 | ##4dtv (transversion rate on 4-fold degenerated sites) are calculated with HKY substitution models 10 | ##Reference: M. Hasegawa, H. Kishino, and T. Yano, J. Mol. Evol. 22 (2), 160 (1985) 11 | 12 | die "perl $0 AXTfile > outfile\n" unless( @ARGV == 1); 13 | 14 | 15 | #my %codons=( 16 | #'CTT'=>'L', 'CTC'=>'L', 'CTA'=>'L', 'CTG'=>'L', 17 | #'GTT'=>'V', 'GTC'=>'V', 'GTA'=>'V', 'GTG'=>'V', 18 | #'TCT'=>'S', 'TCC'=>'S', 'TCA'=>'S', 'TCG'=>'S', 19 | #'CCU'=>'P', 'CCC'=>'P', 'CCA'=>'P', 'CCG'=>'P', 20 | #'ACU'=>'T', 'ACC'=>'T', 'ACA'=>'T', 'ACG'=>'T', 21 | #'GCT'=>'A', 'GCC'=>'A', 'GCA'=>'A', 'GCG'=>'A', 22 | #'CGT'=>'R', 'CGC'=>'R', 'CGA'=>'R', 'CGG'=>'R', 23 | #'GGU'=>'G', 'GGC'=>'G', 'GGA'=>'G', 'GGG'=>'G' 24 | #); 25 | 26 | # %codons was changed to DNA codon according to the poster below. Thanks to 小霖123. 27 | # https://www.jianshu.com/p/6d704378c342 28 | my %codons=( 29 | 'CTT'=>'L', 'CTC'=>'L', 'CTA'=>'L', 'CTG'=>'L', 30 | 'GTT'=>'V', 'GTC'=>'V', 'GTA'=>'V', 'GTG'=>'V', 31 | 'TCT'=>'S', 'TCC'=>'S', 'TCA'=>'S', 'TCG'=>'S', 32 | 'CCT'=>'P', 'CCC'=>'P', 'CCA'=>'P', 'CCG'=>'P', 33 | 'ACT'=>'T', 'ACC'=>'T', 'ACA'=>'T', 'ACG'=>'T', 34 | 'GCT'=>'A', 'GCC'=>'A', 'GCA'=>'A', 'GCG'=>'A', 35 | 'CGT'=>'R', 'CGC'=>'R', 'CGA'=>'R', 'CGG'=>'R', 36 | 'GGT'=>'G', 'GGC'=>'G', 'GGA'=>'G', 'GGG'=>'G' 37 | ); 38 | 39 | my %transversion = ( 40 | "A" => "TC", 41 | "C" => "AG", 42 | "G" => "TC", 43 | "T" => "AG", 44 | ); 45 | 46 | my $axtFile = shift; 47 | 48 | open(AXT,"$axtFile")||die"Cannot open $axtFile\n"; 49 | $/ = "\n\n"; 50 | my @seqs = ; 51 | $/ ="\n"; 52 | close AXT; 53 | 54 | print "tag\t4dtv_corrected\t4dtv_raw\tcondon_4d\tcodon_4dt\n"; 55 | foreach my $line ( @seqs ){ 56 | chomp $line; 57 | if( $line =~ /^(\S+)\n(\S+)\n(\S+)$/ ){ 58 | my $tag = $1; 59 | my $seq1 =$2; 60 | my $seq2 =$3; 61 | my ($corrected_4dtv, $raw_4dtv, $condon_4d, $codon_4dt) = &calculate_4dtv($seq1, $seq2); 62 | print "$tag\t$corrected_4dtv\t$raw_4dtv\t$condon_4d\t$codon_4dt\n"; 63 | } 64 | } 65 | 66 | 67 | 68 | sub calculate_4dtv { 69 | my($str1, $str2) = @_; 70 | 71 | my ($condon_4d, $codon_4dt) = (0,0); 72 | my ($V,$a,$b,$d) = (0,0,0,0); 73 | my %fre=(); 74 | for( my $i = 0; $i < length($str1); $i += 3){ 75 | my $codon1 = substr($str1, $i, 3); 76 | my $codon2 = substr($str2, $i, 3); 77 | my $base1= uc(substr($str1, $i+2, 1)); 78 | my $base2= uc(substr($str2, $i+2, 1)); 79 | 80 | if( exists $codons{$codon1} && exists $codons{$codon2} && $codons{$codon1} eq $codons{$codon2} ){ 81 | $fre{$base1}++; 82 | $fre{$base2}++; 83 | $condon_4d++; 84 | $codon_4dt++ if(is_transversion($codon1,$codon2)); 85 | } 86 | } 87 | 88 | if($condon_4d > 0){ 89 | $V=$codon_4dt / $condon_4d; ##this is raw 4dtv value 90 | ##correction the raw 4dtv values by HKY substitution model 91 | $fre{"Y"}=$fre{"T"}+$fre{"C"}; 92 | $fre{"R"}=$fre{"A"}+$fre{"G"}; 93 | foreach (keys %fre){ 94 | $fre{$_}=0.5*$fre{$_}/$condon_4d; 95 | } 96 | 97 | if($fre{Y}!=0 && $fre{R}!=0 && $fre{A}!=0 && $fre{C}!=0 && $fre{G}!=0 && $fre{T}!=0){ 98 | $a=-1*log(1-$V*($fre{T}*$fre{C}*$fre{R}/$fre{Y}+$fre{A}*$fre{G}*$fre{Y}/$fre{R})/(2*($fre{T}*$fre{C}*$fre{R}+$fre{A}*$fre{G}*$fre{Y}))); 99 | if (1-$V/(2*$fre{Y}*$fre{R}) > 0) { 100 | $b=-1*log(1-$V/(2*$fre{Y}*$fre{R})); 101 | $d=2*$a*($fre{T}*$fre{C}/$fre{Y}+$fre{A}*$fre{G}/$fre{R})-2*$b*($fre{T}*$fre{C}*$fre{R}/$fre{Y}+$fre{A}*$fre{G}*$fre{Y}/$fre{R}-$fre{Y}*$fre{R}); 102 | }else{ 103 | $d = "NA"; 104 | } 105 | }else{ 106 | $d = "NA"; 107 | } 108 | 109 | 110 | }else{ 111 | $V="NA"; 112 | $d="NA"; 113 | } 114 | 115 | return ($d,$V,$condon_4d, $codon_4dt); 116 | 117 | } 118 | 119 | 120 | sub is_transversion{ 121 | my ($codon1,$codon2) = @_; 122 | my $is_transversion = 0; 123 | my $base1 = substr($codon1,2,1); 124 | my $base2 = substr($codon2,2,1); 125 | $is_transversion = 1 if (exists $transversion{$base1} && $transversion{$base1} =~ /$base2/); 126 | return $is_transversion; 127 | } 128 | -------------------------------------------------------------------------------- /tree2gd/software/diamond: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/software/diamond -------------------------------------------------------------------------------- /tree2gd/software/dolloparsimony: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/software/dolloparsimony -------------------------------------------------------------------------------- /tree2gd/software/iqtree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/software/iqtree -------------------------------------------------------------------------------- /tree2gd/software/muscle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/software/muscle -------------------------------------------------------------------------------- /tree2gd/software/seqkit: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/software/seqkit -------------------------------------------------------------------------------- /tree2gd/software/trimal: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dee-chen/Tree2gd/043a63ca6e5aec41ce246adfbba9ecd4321b2b88/tree2gd/software/trimal -------------------------------------------------------------------------------- /tree2gd/synteny.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.7 2 | 3 | import os 4 | import subprocess 5 | import logging 6 | from multiprocessing import Pool 7 | import sys 8 | import configparser 9 | 10 | def sub_sh(sh): 11 | logging.info("Start runing step6 synteny : %s.."%sh) 12 | stdout=subprocess.run(['sh',sh],stdout=subprocess.PIPE, stderr=subprocess.PIPE) 13 | logging.debug('{} stdout:\n'.format(sh) +stdout.stdout.decode('utf-8')) 14 | logging.debug('{} stderr:\n'.format(sh) +stdout.stderr.decode('utf-8')) 15 | logging.info("step6 synteny : %s has done."%sh) 16 | 17 | 18 | def synteny(sp_list,config,out,diamond,seqkit,pep_postfix,args): 19 | logging.info("Writing synteny script files...") 20 | sp_num=len(sp_list) 21 | op='' 22 | sh_list=[] 23 | step6_sh = open(os.sep.join([out,'step6.sh']),"w") 24 | for k,v in options: 25 | op=' '.join((op,' '.join((k,v)))) 26 | for i in sp_list: 27 | SH = open(os.sep.join([out,'sample_sh',i+".sh"]),"w") 28 | SH.write('python -m jcvi.compara.catalog ortholog --no_strip_names --cscore=.99 '+os.sep.join([args.i,i])+" "+os.sep.join([args.i,i])+"\n") 29 | SH.close() 30 | sh_list.append(os.sep.join([out,'sample_sh',i+".sh"])) 31 | 32 | if not args.only_script: 33 | try: 34 | subprocess.run(jcvi,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 35 | except FileNotFoundError: 36 | logging.error("jcvi can not run.") 37 | sys.exit(0) 38 | 39 | sh_pool=Pool(int(p)) 40 | sh_pool.map(sub_sh,sh_list) 41 | sh_pool.close() 42 | sh_pool.join() 43 | logging.info("ALL synteny has done.") 44 | logging.info("Start sorting results..") 45 | stdout=subprocess.run(['sh',os.sep.join([out,'summary.sh'])],stdout=subprocess.PIPE, stderr=subprocess.PIPE) 46 | 47 | step1_sh.writelines("\n".join(sh_list)) 48 | step1_sh.write(os.sep.join([out,'summary.sh'])) 49 | step1_sh.close() 50 | -------------------------------------------------------------------------------- /tree2gd/wgd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.7 2 | import os 3 | import subprocess 4 | import logging 5 | import sys 6 | from tree2gd.seq import read_fasta_file 7 | import configparser 8 | import subprocess 9 | from multiprocessing import Pool 10 | 11 | 12 | def mcl2fasta(minimal_taxa,outdir,step2out,step1out,args): 13 | logging.info("Reading mcl output file") 14 | clusterDICT = {} 15 | gene_idmap={} 16 | fa_list=[] 17 | count = 0 18 | if outdir[-1] != "/": outdir += "/" 19 | with open(os.sep.join([step1out,'all_sample2fa.list']),"rU") as idmap_file: 20 | for l in idmap_file: 21 | sp = l.strip().split('\t') 22 | gene_idmap[sp[0]]=sp[1] 23 | logging.info("gene_idmap read done.") 24 | with open(os.sep.join([step2out,'allmcl.out.OGs.group']),"rU") as infile: 25 | for line in infile: 26 | spls=[] 27 | if len(line) < 3: continue 28 | genes = line.strip().split('\t') 29 | for gene in genes: 30 | spls.append(gene_idmap[gene]) 31 | if len(set(spls)) >= minimal_taxa: 32 | count += 1 33 | clusterID = str(count) 34 | for seqID in genes: 35 | clusterDICT[seqID] = clusterID 36 | logging.info("clusters with at least "+str(minimal_taxa)+" taxa read") 37 | 38 | logging.info("Reading the fasta file "+os.sep.join([step1out,'all_sample.pep.faa'])) 39 | 40 | for s in read_fasta_file(os.sep.join([step1out,'all_sample.pep.faa'])): 41 | seqid,seq = s.name,s.seq 42 | try: 43 | clusterID = clusterDICT[seqid] 44 | with open(outdir+"cluster"+clusterID+".fa","a") as outfile: 45 | outfile.write(">"+seqid+"\n"+seq+"\n") 46 | fa_list.append("cluster"+str(clusterID)) 47 | except: 48 | pass 49 | fa_list=list(set(fa_list)) 50 | if args.cds2tree: 51 | logging.info("Choose to use cds sequence for gene tree construction and sort out the corresponding cds sequence files.") 52 | for s in read_fasta_file(os.sep.join([step1out,'all_cds.fa'])): 53 | seqid,seq = s.name,s.seq 54 | try: 55 | clusterID = clusterDICT[seqid] 56 | with open(outdir+"cluster"+clusterID+".cds","a") as outfile: 57 | outfile.write(">"+seqid+"\n"+seq+"\n") 58 | except: 59 | pass 60 | return fa_list 61 | 62 | def fa2tree(muscle,iqtree,fa,step4out,iqtreeop,args,Epal2nal): 63 | muscle_stdout=subprocess.run([muscle,'-in',os.sep.join([step4out,'all_fa',fa+".fa"]),'-out',os.sep.join([step4out,'muscle_out',fa+".pep.aln"]),],stdout=subprocess.PIPE, stderr=subprocess.PIPE) 64 | logging.debug('{} stdout:\n'.format(muscle) +muscle_stdout.stdout.decode('utf-8')) 65 | logging.debug('{} stderr:\n'.format(muscle) +muscle_stdout.stderr.decode('utf-8')) 66 | if args.cds2tree: 67 | Epal2nal_stdout=subprocess.run(Epal2nal+" "+os.sep.join([step4out,'muscle_out',fa+".pep.aln"])+" "+os.sep.join([step4out,'all_fa',fa+".cds"])+" -output fasta "+" > "+os.sep.join([step4out,'muscle_out',fa+".cds.aln"]),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 68 | logging.debug('{} stdout:\n'.format(Epal2nal) +Epal2nal_stdout.stdout.decode('utf-8')) 69 | logging.debug('{} stderr:\n'.format(Epal2nal) +Epal2nal_stdout.stderr.decode('utf-8')) 70 | iqtree_stdout=subprocess.run(iqtree+" -s "+os.sep.join([step4out,'muscle_out',fa+".cds.aln"])+" "+iqtreeop+" -pre "+os.sep.join([step4out,'iqtree_out',fa+".iqtree"]),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 71 | logging.debug('{} stdout:\n'.format(iqtree) +iqtree_stdout.stdout.decode('utf-8')) 72 | logging.debug('{} stderr:\n'.format(iqtree) +iqtree_stdout.stderr.decode('utf-8')) 73 | else: 74 | iqtree_stdout=subprocess.run(iqtree+" -s "+os.sep.join([step4out,'muscle_out',fa+".pep.aln"])+" "+iqtreeop+" -pre "+os.sep.join([step4out,'iqtree_out',fa+".iqtree"]),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 75 | logging.debug('{} stdout:\n'.format(iqtree) +iqtree_stdout.stdout.decode('utf-8')) 76 | logging.debug('{} stderr:\n'.format(iqtree) +iqtree_stdout.stderr.decode('utf-8')) 77 | def run_fa2tree(args): 78 | fa2tree(args[0],args[1],args[2],args[3],args[4],args[5],args[6]) 79 | 80 | def run_tree2gd(step1out,args,config,step2out,step4out): 81 | logging.info("Writing step4 script files...") 82 | step4_sh=open(os.sep.join([step4out,'step4.sh']),"w") 83 | iqtreeop='' 84 | if not config.has_section('iqtree'): 85 | config.add_section('iqtree') 86 | if not config.has_option("iqtree", "-B"): 87 | config.set("iqtree", "-B","1000") 88 | if config.get("iqtree", "-B")=="0": 89 | config.remove_option("iqtree", "-B") 90 | if not config.has_option("iqtree", "-m"): 91 | if args.cds2tree: 92 | config.set("iqtree", "-m","HKY") 93 | else: 94 | config.set("iqtree", "-m","JTT+G4") 95 | for k,v in config.items("iqtree"): 96 | iqtreeop=' '.join((iqtreeop,' '.join((k,v)))) 97 | tree2gd=config.get("software", "tree2gd") 98 | muscle=config.get("software", "muscle") 99 | iqtree=config.get("software", "iqtree") 100 | if args.cds2tree: 101 | Epal2nal=config.get("software", "Epal2nal") 102 | else: 103 | Epal2nal="Epal2nal.pl" 104 | step4_sh.writelines(["for F in "+os.sep.join([step4out,'all_fa/'])+"*.fa;do "+muscle+" -in $F -out "+os.sep.join([step4out,'muscle_out/'])+"`basename $F`.aln;done\n", 105 | "for F in "+os.sep.join([step4out,'muscle_out/'])+"*.aln;do "+iqtree+iqtreeop+" -s $F -pre "+os.sep.join([step4out,'iqtree_out/'])+"`basename $F`.iqtree;done \n", 106 | "ls "+os.sep.join([step4out,'iqtree_out/'])+"|grep contree > "+os.sep.join([step4out,'tree.list.tmp'])+"\n", 107 | "cat -n "+os.sep.join([step4out,'tree.list.tmp'])+" > "+ os.sep.join([step4out,'tree.list'])+"\n", 108 | tree2gd+" "+args.tree+" "+os.sep.join([step1out,'all_sample2fa.list'])+" "+os.sep.join([step4out,'tree.list'])+" "+os.sep.join([step4out,'Tree2GD_out/']) 109 | ]) 110 | step4_sh.close() 111 | if not args.only_script: 112 | if not os.path.exists(os.sep.join([step4out,'all_fa/'])): 113 | os.mkdir(os.sep.join([step4out,'all_fa/'])) 114 | minimal_taxa=config.get("mcl2fasta", "min_taxa") if config.has_option("mcl2fasta", "min_taxa") and config.get("mcl2fasta", "min_taxa")!="" else '4' 115 | if int(minimal_taxa)<4: 116 | logging.warning("The mcl2fasta min_taxa cannot be set less than 4, otherwise a valid tree cannot be obtained ,it will be changed to the default 4!") 117 | minimal_taxa="4" 118 | fa_list=mcl2fasta(int(minimal_taxa),os.sep.join([step4out,'all_fa/']),step2out,step1out,args) 119 | logging.info("FASTA file selection has been completed ,according to MCL results.") 120 | try: 121 | subprocess.run(muscle,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 122 | except FileNotFoundError: 123 | logging.error("muscle can not run.") 124 | sys.exit(0) 125 | try: 126 | subprocess.run(iqtree,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 127 | except FileNotFoundError: 128 | logging.error("iqtree can not run.") 129 | sys.exit(0) 130 | try: 131 | subprocess.run(tree2gd,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 132 | except FileNotFoundError: 133 | logging.error("tree2gd can not run.") 134 | sys.exit(0) 135 | sh_list=[] 136 | if not os.path.exists(os.sep.join([step4out,'muscle_out/'])): 137 | os.mkdir(os.sep.join([step4out,'muscle_out/'])) 138 | if not os.path.exists(os.sep.join([step4out,'iqtree_out/'])): 139 | os.mkdir(os.sep.join([step4out,'iqtree_out/'])) 140 | for fa in fa_list: 141 | tmp=(muscle,iqtree,fa,step4out,iqtreeop,args,Epal2nal) 142 | sh_list.append(tmp) 143 | sh_pool=Pool(args.t) 144 | logging.info("Start runing step4 fa2tree.") 145 | sh_pool.map(run_fa2tree,sh_list) 146 | sh_pool.close() 147 | sh_pool.join() 148 | logging.info("step4 fa2tree has done.") 149 | logging.info("All sequences have completed the construction of the tree.") 150 | logging.info("Start WGD calculation.") 151 | tree2gdop="" 152 | if not config.has_section('tree2gd'): 153 | config.add_section('tree2gd') 154 | if not config.has_option("iqtree", "-B"): 155 | config.set("tree2gd", "--bp","0") 156 | for k,v in config.items("tree2gd"): 157 | tree2gdop=' '.join((tree2gdop,'='.join((k,v)))) 158 | subprocess.run("ls "+os.sep.join([step4out,"iqtree_out"])+"|grep treefile |awk '{print \""+os.sep.join([step4out,"iqtree_out"])+"/\"$0;}' |cat -n > "+os.sep.join([step4out,'tree.list']),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 159 | tree2gd_out=subprocess.run(tree2gd+" "+args.tree+" "+os.sep.join([step1out,'all_sample2fa.list'])+" "+os.sep.join([step4out,'tree.list'])+" "+os.sep.join([step4out,'Tree2GD_out/'])+" "+tree2gdop,shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 160 | logging.debug('{} stdout:\n'.format(tree2gd) +tree2gd_out.stdout.decode('utf-8')) 161 | logging.debug('{} stderr:\n'.format(tree2gd) +tree2gd_out.stderr.decode('utf-8')) 162 | logging.info("step4 Tree2GD has done.") 163 | -------------------------------------------------------------------------------- /tree2gd_main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.7 2 | 3 | import argparse 4 | #import threading 5 | import time 6 | import os 7 | import configparser 8 | import logging 9 | import coloredlogs 10 | import sys 11 | import subprocess 12 | import multiprocessing 13 | import shutil 14 | from Bio import Phylo 15 | from tree2gd.seq import read_fasta_file 16 | import re 17 | 18 | class NewConfigParser(configparser.ConfigParser): 19 | def optionxform(self, optionstr): 20 | return optionstr 21 | 22 | def err_exit(): 23 | sys.exit('\033[1;31;47m!!The Tree2gd program exited abnormally, please check the log file !!\033[0m') 24 | 25 | def cmd_check(cmd): 26 | try: 27 | p=subprocess.run(cmd,check=True,stdout=subprocess.PIPE, 28 | stderr=subprocess.PIPE) 29 | logging.debug(p.stdout.decode("utf-8").strip()) 30 | pass 31 | except FileNotFoundError: 32 | logging.error("The program %s path exists, please check the settings"%(cmd)) 33 | err_exit() 34 | except subprocess.CalledProcessError: 35 | logging.error("The program %s not working properly, please check the settings"%(cmd)) 36 | err_exit() 37 | logging.info("The program %s working properly [OK]"%(cmd)) 38 | 39 | def main(): 40 | pwd= os.getcwd() 41 | parser = argparse.ArgumentParser(description='Tree2GD:A pipeline for WGD V1.0.40') 42 | parser.add_argument('-i', type=str, required=True, metavar='input_dir',help='The CDS and pep dir.') 43 | parser.add_argument('-tree', type=str, required=True, metavar='phytree.nwk',help='The phytree file.') 44 | parser.add_argument('-t', type=int,metavar='t',default='1', help='Thread num.default:1') 45 | parser.add_argument('-o', type=str,metavar='outputdir',default=os.sep.join([pwd,'output']),help='The output dir.default:'+os.sep.join([pwd,'output'])) 46 | parser.add_argument('--step', type=str,metavar='123456',default='123456', help='Which steps you need.default:123456(Choose from numbers: such as \'234\')') 47 | parser.add_argument('--log', type=str, metavar='logfile',help='log file name,or log will print on stdout') 48 | parser.add_argument('--config', type=str,metavar='config.ini', help='config.ini configuration file, leave it blank to run with default parameters and the program\'s own software version.') 49 | parser.add_argument('--debug', action='store_true', default=False, help='The log file will contain the output of each software itself, which is convenient for finding errors (-log is required)') 50 | parser.add_argument('--only_script', action='store_true', default=False,help='Only generate scripts, not run automatically.') 51 | parser.add_argument('--cds2tree', action='store_true', default=False,help='Use cds sequence to construct gene tree.') 52 | parser.add_argument('--synteny', action='store_true', default=False,help=' Using the results of the covariance analysis, the GD ratio and Ks distribution were optimized. **Gene annotations information for each species need to be provided in the input folder as *.bed files') 53 | args = parser.parse_args() 54 | 55 | if not args.log: 56 | coloredlogs.install( 57 | fmt='%(asctime)s: %(levelname)s\t%(message)s', 58 | evel='info'.upper(), stream=sys.stdout 59 | ) 60 | else: 61 | if args.debug: 62 | l='debug' 63 | else: 64 | l='info' 65 | print('Logs will be written to {}'.format(args.log)) 66 | if os.path.exists(args.log): 67 | os.remove(args.log) 68 | logging.basicConfig( 69 | filename=args.log, 70 | filemode='a', 71 | format='%(asctime)s: %(levelname)s\t%(message)s', 72 | datefmt='%H:%M:%S', 73 | level=l.upper() 74 | ) 75 | home_dir=os.path.dirname(os.path.abspath(__file__)) 76 | cf=NewConfigParser() 77 | 78 | if not args.config: 79 | logging.info('The user does not provide a configuration file, it will run with the default parameters and the software version of the program.') 80 | cf.add_section('software') 81 | else: 82 | cf.read(args.config) 83 | if not cf.has_section('software'): 84 | cf.add_section('software') 85 | abs_out=os.path.abspath(args.o) 86 | sp_list=[] 87 | logging.info("Start checking the input tree file..") 88 | try: 89 | tree_file=Phylo.read(args.tree,'newick') 90 | for i in tree_file.get_terminals(): 91 | sp_list.append(i.name) 92 | except FileNotFoundError: 93 | logging.error('Checking Newicktree file :[ERR] -- The tree file :%s does not exist' %(args.tree)) 94 | err_exit() 95 | except Phylo.NewickIO.NewickError as err: 96 | logging.error('Checking Newicktree file :[ERR] -- %s'%(err)) 97 | err_exit() 98 | logging.info("Checking Newicktree file :[OK]") 99 | logging.info("Start checking the input fasta file..") 100 | pep_postfix=cf.get("postfix", "pep") if cf.has_option("postfix", "pep") else ".pep" 101 | cds_postfix=cf.get("postfix", "cds") if cf.has_option("postfix", "cds") else ".cds" 102 | for sp in sp_list: 103 | seqid_list=[] 104 | if not os.path.exists(os.sep.join([args.i,sp+pep_postfix])): 105 | logging.error('The input pep file :%s does not exist.'%(os.sep.join([args.i,sp+pep_postfix]))) 106 | err_exit() 107 | for s in read_fasta_file(os.sep.join([args.i,sp+pep_postfix])): 108 | seqid,seq = s.name,s.seq 109 | if '.' in s.seq: 110 | logging.error("The %s sequence of %s contains the character \".\", diamond will not run normally, please replace it with the \"*\" character."%(seqid,sp+pep_postfix)) 111 | err_exit() 112 | seqid_list.append(s.name) 113 | logging.info("Checking pep file %s:[OK]"%(sp+pep_postfix)) 114 | if '5' in args.step or args.cds2tree: 115 | logging.info("Need to perform kaks calculation or use cds for tree structure, start to check the correspondence between cds file %s and pep :"%(sp+cds_postfix)) 116 | for s in read_fasta_file(os.sep.join([args.i,sp+cds_postfix])): 117 | seqid,seq = s.name,s.seq 118 | if s.name not in seqid_list: 119 | logging.error("The %s sequence id in cdsfile:%s does not have corresponding sequence in pep file."%(s.name,sp+cds_postfix)) 120 | err_exit() 121 | logging.info("Checking cds file %s:[OK]"%(sp+cds_postfix)) 122 | logging.info("Checking all input file :[OK]") 123 | 124 | logging.info("Start checking required software..") 125 | if '1' in args.step: 126 | diamond=cf.get("software", "diamond") if cf.has_option("software", "diamond") and cf.get("software", "diamond")!="" else os.sep.join([home_dir,"tree2gd","software", "diamond"]) 127 | seqkit=cf.get("software", "seqkit") if cf.has_option("software", "seqkit") and cf.get("software", "seqkit")!="" else os.sep.join([home_dir,"tree2gd","software", "seqkit"]) 128 | cmd_check([diamond,"help"]) 129 | cmd_check(seqkit) 130 | if '2' in args.step: 131 | phymcl=cf.get("software", "phymcl") if cf.has_option("software", "phymcl") and cf.get("software", "phymcl")!="" else os.sep.join([home_dir,"tree2gd","software", "PhyloMCL"]) 132 | cmd_check(phymcl) 133 | if '3' in args.step: 134 | dolloparsimony=cf.get("software", "dolloparsimony") if cf.has_option("software", "dolloparsimony") and cf.get("software", "dolloparsimony")!="" else os.sep.join([home_dir,"tree2gd","software", "dolloparsimony"]) 135 | cmd_check(dolloparsimony) 136 | if '4' in args.step: 137 | tree2gd=cf.get("software", "tree2gd") if cf.has_option("software", "tree2gd") and cf.get("software", "tree2gd")!="" else os.sep.join([home_dir,"tree2gd","software", "Tree2GD"]) 138 | cmd_check(tree2gd) 139 | cf.set("software", "tree2gd",tree2gd) 140 | muscle=cf.get("software", "muscle") if cf.has_option("software", "muscle") and cf.get("software", "muscle")!="" else os.sep.join([home_dir,"tree2gd","software", "muscle"]) 141 | cmd_check([muscle,"-version"]) 142 | cf.set("software", "muscle",muscle) 143 | iqtree=cf.get("software", "iqtree") if cf.has_option("software", "iqtree") and cf.get("software", "iqtree")!="" else os.sep.join([home_dir,"tree2gd","software", "iqtree"]) 144 | cmd_check([iqtree,"-h"]) 145 | cf.set("software","iqtree",iqtree) 146 | if args.cds2tree: 147 | Epal2nal=cf.get("software", "Epal2nal") if cf.has_option("software", "Epal2nal") and cf.get("software", "Epal2nal")!="" else os.sep.join([home_dir,"tree2gd","software", "Epal2nal.pl"]) 148 | cmd_check(Epal2nal) 149 | cf.set("software","Epal2nal",Epal2nal) 150 | if '5' in args.step: 151 | KaKs_Calculator=cf.get("software", "KaKs_Calculator") if cf.has_option("software", "KaKs_Calculator") and cf.get("software", "KaKs_Calculator")!="" else os.sep.join([home_dir,"tree2gd","software", "KaKs_Calculator"]) 152 | cmd_check(KaKs_Calculator) 153 | cf.set("software", "KaKs_Calculator",KaKs_Calculator) 154 | muscle=cf.get("software", "muscle") if cf.has_option("software", "muscle") and cf.get("software", "muscle")!="" else os.sep.join([home_dir,"tree2gd","software", "muscle"]) 155 | cmd_check([muscle,"-version"]) 156 | cf.set("software", "muscle",muscle) 157 | Epal2nal=cf.get("software", "Epal2nal") if cf.has_option("software", "Epal2nal") and cf.get("software", "Epal2nal")!="" else os.sep.join([home_dir,"tree2gd","software", "Epal2nal.pl"]) 158 | cmd_check(Epal2nal) 159 | cf.set("software", "Epal2nal",Epal2nal) 160 | 161 | 162 | if not os.path.exists(abs_out): 163 | logging.info('The output dir :%s does not exist,will create it.'%(abs_out)) 164 | os.mkdir(abs_out) 165 | 166 | if '1' in args.step: 167 | step1out=os.sep.join([abs_out,'step1.blastp']) 168 | if not os.path.exists(step1out): 169 | logging.info('The Step1 output dir :%s does not exist,will create it.'%(step1out)) 170 | else: 171 | logging.warning('The Step1 output dir :%s has exist,will backup it as %s_backup and create new.'%(step1out,step1out)) 172 | os.rename(step1out,step1out+"_backup") 173 | os.mkdir(step1out) 174 | if not os.path.exists(os.sep.join([step1out,'sample_sh'])): 175 | logging.info('The Step1 scripts dir :%s does not exist,will create it.'%(os.sep.join([step1out,'sample_sh']))) 176 | os.mkdir(os.sep.join([step1out,'sample_sh'])) 177 | if not os.path.exists(os.sep.join([step1out,'allsample_blast'])): 178 | logging.info('The Step1 blastp result dir :%s does not exist,will create it.'%(os.sep.join([step1out,'allsample_blast']))) 179 | os.mkdir(os.sep.join([step1out,'allsample_blast'])) 180 | 181 | from tree2gd.blastp import all2all_diamond 182 | all2all_diamond(sp_list,cf,step1out,diamond,seqkit,pep_postfix,args) 183 | logging.info('pep all2all diamond done.') 184 | 185 | if '2' in args.step: 186 | step1out=os.sep.join([abs_out,'step1.blastp']) 187 | step2out=os.sep.join([abs_out,'step2.MCL']) 188 | if not os.path.exists(step2out): 189 | logging.info('The Step2 output dir :%s does not exist,will create it.'%(step2out)) 190 | else: 191 | logging.warning('The Step2 output dir :%s has exist,will backup it as %s_backup and create new.'%(step2out,step2out)) 192 | os.rename(step2out,step2out+"_backup") 193 | os.mkdir(step2out) 194 | if not cf.has_section('phymcl'): 195 | cf.add_section('phymcl') 196 | with open(args.tree) as tree_in,open(os.sep.join([step2out,"phymcl.input.tree"]),"w") as out: 197 | tree_text=tree_in.readlines()[0].strip('\n') 198 | pattern = re.compile(r":\b[0-9]+(?:\.[0-9]+)?\b") 199 | out.write(pattern.sub("",tree_text)) 200 | from tree2gd.mcl import run_phymcl 201 | run_phymcl(step1out,phymcl,args,cf.items('phymcl'),step2out) 202 | 203 | 204 | if '3' in args.step: 205 | step1out=os.sep.join([abs_out,'step1.blastp']) 206 | step2out=os.sep.join([abs_out,'step2.MCL']) 207 | step3out=os.sep.join([abs_out,'step3.dollop']) 208 | if not os.path.exists(step3out): 209 | logging.info('The Step3 output dir :%s does not exist,will create it.'%(step3out)) 210 | else: 211 | logging.warning('The Step3 output dir :%s has exist,will backup it as %s_backup and create new.'%(step3out,step3out)) 212 | os.rename(step3out,step3out+"_backup") 213 | os.mkdir(step3out) 214 | from tree2gd.dollop import run_dolloparsimony 215 | run_dolloparsimony(step1out,step2out,step3out,dolloparsimony,args) 216 | 217 | if '4' in args.step: 218 | step1out=os.sep.join([abs_out,'step1.blastp']) 219 | step2out=os.sep.join([abs_out,'step2.MCL']) 220 | step4out=os.sep.join([abs_out,'step4.WGD']) 221 | 222 | if not os.path.exists(step4out): 223 | logging.info('The Step4 output dir :%s does not exist,will create it.'%(step4out)) 224 | else: 225 | logging.warning('The Step4 output dir :%s has exist,will backup it as %s_backup and create new.'%(step4out,step4out)) 226 | os.rename(step4out,step4out+"_backup") 227 | os.mkdir(step4out) 228 | if args.cds2tree: 229 | for i in sp_list: 230 | cds_path = os.sep.join([args.i,i+cds_postfix]) 231 | with open(cds_path, 'r') as sf, open(os.sep.join([step4out,"all_cds.fa"]), 'a+') as df: 232 | lines=sf.readlines() 233 | for line in lines: 234 | df.write(line.strip().split(" ")[0]+"\n") 235 | from tree2gd.wgd import run_tree2gd 236 | run_tree2gd(step1out,args,cf,step2out,step4out) 237 | shutil.rmtree(os.sep.join([step4out,'all_fa'])) 238 | shutil.rmtree(os.sep.join([step4out,'muscle_out'])) 239 | 240 | if '5' in args.step: 241 | step1out=os.sep.join([abs_out,'step1.blastp']) 242 | step4out=os.sep.join([abs_out,'step4.WGD']) 243 | step5out=os.sep.join([abs_out,'step5.KaKs']) 244 | gene_pairs_idmap=[] 245 | if not os.path.exists(step5out): 246 | logging.info('The Step5 output dir :%s does not exist,will create it.'%(step5out)) 247 | else: 248 | logging.warning('The Step5 output dir :%s has exist,will backup it as %s_backup and create new.'%(step5out,step5out)) 249 | os.rename(step5out,step5out+"_backup") 250 | os.mkdir(step5out) 251 | cds_postfix=cf.get("postfix", "cds") if cf.has_option("postfix", "cds") else ".cds" 252 | with open(os.sep.join([step1out,'all_sample.pep.faa']), 'r') as pep,open(os.sep.join([step5out,"all_pep.fa"]), 'a+') as pep_out: 253 | lines=pep.readlines() 254 | for line in lines: 255 | pep_out.write(line.strip().split(" ")[0]+"\n") 256 | for i in sp_list: 257 | cds_path = os.sep.join([args.i,i+cds_postfix]) 258 | with open(cds_path, 'r') as sf, open(os.sep.join([step5out,"all_cds.fa"]), 'a+') as df: 259 | lines=sf.readlines() 260 | for line in lines: 261 | df.write(line.strip().split(" ")[0]+"\n") 262 | with open(os.sep.join([step4out,'Tree2GD_out','gd.gene_pairs.txt']),"r") as gene_pairs,open(os.sep.join([step5out,"all_gene_pairs.list"]), 'a+') as out: 263 | for l in gene_pairs: 264 | if not "#" in l: 265 | out.write(l.strip().split("\t")[4]+"\t"+l.strip().split("\t")[5]+"\n") 266 | gene_pairs_idmap.append([l.strip().split("\t")[2],l.strip().split("\t")[3],l.strip().split("\t")[4],l.strip().split("\t")[5]]) 267 | from tree2gd.kaks import run_kaks 268 | run_kaks(sp_list,step1out,args,cf,step4out,step5out,gene_pairs_idmap) 269 | 270 | if '6' in args.step: 271 | step2out=os.sep.join([abs_out,'step2.MCL']) 272 | step3out=os.sep.join([abs_out,'step3.dollop']) 273 | step4out=os.sep.join([abs_out,'step4.WGD']) 274 | step5out=os.sep.join([abs_out,'step5.KaKs']) 275 | step6out=os.sep.join([abs_out,'step6.plot_summary']) 276 | if not os.path.exists(step6out): 277 | logging.info('The Step6 output dir :%s does not exist,will create it.'%(step6out)) 278 | else: 279 | logging.warning('The Step6 output dir :%s has exist,will backup it as %s_backup and create new.'%(step6out,step6out)) 280 | os.rename(step6out,step6out+"_backup") 281 | os.mkdir(step6out) 282 | shutil.copyfile(os.sep.join([step2out,"allmcl.out.OGs.tabular"]),os.sep.join([step6out,"allmcl.out.OGs.tabular"])) 283 | shutil.copyfile(os.sep.join([step3out,"dollop.out.scv"]),os.sep.join([step6out,"dollop.out.scv"])) 284 | os.mkdir(os.sep.join([step6out,"Tree2GD_out"])) 285 | shutil.copyfile(os.sep.join([step4out,"Tree2GD_out","gd.gene_pairs.txt"]),os.sep.join([step6out,"Tree2GD_out","gd.gene_pairs.txt"])) 286 | shutil.copyfile(os.sep.join([step4out,"Tree2GD_out","GDtype_stat.txt"]),os.sep.join([step6out,"Tree2GD_out","GDtype_stat.txt"])) 287 | shutil.copyfile(os.sep.join([step4out,"Tree2GD_out","Phtree.nwk"]),os.sep.join([step6out,"Tree2GD_out","Phtree.nwk"])) 288 | shutil.copyfile(os.sep.join([step4out,"Tree2GD_out","summarytable.txt"]),os.sep.join([step6out,"Tree2GD_out","summarytable.txt"])) 289 | shutil.copytree(os.sep.join([step5out,"sp_kaks_out"]),os.sep.join([step6out,"sp_kaks_out"])) 290 | shutil.copyfile(os.sep.join([home_dir,"tree2gd","software","Tree2GD_draw.R"]),os.sep.join([step6out,"Tree2GD_draw.R"])) 291 | shutil.copyfile(os.sep.join([home_dir,"tree2gd","software", "SVM.R"]), 292 | os.sep.join([step6out, "SVM.R"])) 293 | from tree2gd.plot import run_plot 294 | run_plot(step6out,args,cf) 295 | os.remove(os.sep.join([step6out,"Rplots.pdf"])) 296 | 297 | 298 | def test(): 299 | home_dir=os.path.dirname(os.path.abspath(__file__)) 300 | parser = argparse.ArgumentParser(description='test cmd for Tree2GD') 301 | parser.add_argument('-t', type=int, default='1', help='Thread num.default:1') 302 | parser.add_argument('--config',default=os.sep.join([home_dir,"tree2gd","example_data","config.ini"]),type=str, help='config.ini configuration file, leave it blank to run with default parameters and the program\'s own software version.') 303 | args = parser.parse_args() 304 | subprocess.run("Tree2gd -i "+os.sep.join([home_dir,"tree2gd","example_data"])+" -tree "+os.sep.join([home_dir,"tree2gd","example_data","example.tree"])+" --config "+args.config+" -o ./Tree2gd_test_out -t "+str(args.t),shell=True) 305 | shutil.copy(os.sep.join([home_dir,"tree2gd","example_data","full_config.ini"]),"./full_config.ini") 306 | 307 | if __name__ == '__main__': 308 | main() 309 | --------------------------------------------------------------------------------