Migrated from GitHub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +3 -0
- data/HomoAug/LICENSE.txt +216 -0
- data/HomoAug/README.md +199 -0
- data/HomoAug/bin/TMalign +3 -0
- data/HomoAug/bin/esl-reformat +3 -0
- data/HomoAug/bin/jackhmmer +3 -0
- data/HomoAug/run_HomoAug.py +838 -0
- data/HomoAug/utils/misc.py +111 -0
- data/HomoAug/utils/ray_tools.py +90 -0
- data/LICENSE +21 -0
- data/README.md +122 -0
- data/bindclip.sh +44 -0
- data/docs/framework.jpg +3 -0
- data/docs/logo.png +3 -0
- data/encode_ligand_atom.sh +14 -0
- data/py_scripts/lmdb_utils.py +74 -0
- data/py_scripts/write_data_with_docked.py +237 -0
- data/py_scripts/write_dude_multi.py +237 -0
- data/retrieval.sh +18 -0
- data/test.sh +15 -0
- data/unimol/__init__.py +6 -0
- data/unimol/data/__init__.py +51 -0
- data/unimol/data/add_2d_conformer_dataset.py +46 -0
- data/unimol/data/affinity_dataset.py +567 -0
- data/unimol/data/atom_type_dataset.py +34 -0
- data/unimol/data/complex_center_dataset.py +65 -0
- data/unimol/data/conformer_sample_dataset.py +315 -0
- data/unimol/data/coord_pad_dataset.py +82 -0
- data/unimol/data/cropping_dataset.py +269 -0
- data/unimol/data/data_utils.py +23 -0
- data/unimol/data/dictionary.py +157 -0
- data/unimol/data/distance_dataset.py +64 -0
- data/unimol/data/from_str_dataset.py +19 -0
- data/unimol/data/key_dataset.py +29 -0
- data/unimol/data/lmdb_dataset.py +49 -0
- data/unimol/data/mask_points_dataset.py +267 -0
- data/unimol/data/normalize_dataset.py +68 -0
- data/unimol/data/plasma_utils.py +188 -0
- data/unimol/data/pocket2mol_dataset.py +403 -0
- data/unimol/data/prepend_and_append_2d_dataset.py +23 -0
- data/unimol/data/remove_hydrogen_dataset.py +200 -0
- data/unimol/data/resampling_dataset.py +117 -0
- data/unimol/data/tta_dataset.py +146 -0
- data/unimol/data/vae_binding_dataset.py +176 -0
- data/unimol/demo.py +12 -0
- data/unimol/encode_pocket_ligand.py +131 -0
- data/unimol/losses/__init__.py +7 -0
- data/unimol/losses/cross_entropy.py +1333 -0
- data/unimol/losses/unimol.py +210 -0
- data/unimol/models/__init__.py +3 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
data/HomoAug/bin/TMalign filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
data/HomoAug/bin/esl-reformat filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
data/HomoAug/bin/jackhmmer filter=lfs diff=lfs merge=lfs -text
|
data/HomoAug/LICENSE.txt
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright © 2023 Institute for AI Industry Research (AIR), Tsinghua University.
|
| 2 |
+
|
| 3 |
+
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
| 4 |
+
|
| 5 |
+
Preamble
|
| 6 |
+
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
| 7 |
+
|
| 8 |
+
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
| 9 |
+
|
| 10 |
+
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
| 11 |
+
|
| 12 |
+
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
| 13 |
+
|
| 14 |
+
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
| 15 |
+
|
| 16 |
+
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
| 17 |
+
|
| 18 |
+
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
| 19 |
+
|
| 20 |
+
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
| 21 |
+
|
| 22 |
+
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
| 23 |
+
|
| 24 |
+
The precise terms and conditions for copying, distribution and modification follow.
|
| 25 |
+
|
| 26 |
+
TERMS AND CONDITIONS
|
| 27 |
+
0. Definitions.
|
| 28 |
+
“This License” refers to version 3 of the GNU General Public License.
|
| 29 |
+
|
| 30 |
+
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
| 31 |
+
|
| 32 |
+
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
| 33 |
+
|
| 34 |
+
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
| 35 |
+
|
| 36 |
+
A “covered work” means either the unmodified Program or a work based on the Program.
|
| 37 |
+
|
| 38 |
+
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
| 39 |
+
|
| 40 |
+
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
| 41 |
+
|
| 42 |
+
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
| 43 |
+
|
| 44 |
+
1. Source Code.
|
| 45 |
+
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
| 46 |
+
|
| 47 |
+
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
| 48 |
+
|
| 49 |
+
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
| 50 |
+
|
| 51 |
+
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
| 52 |
+
|
| 53 |
+
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
| 54 |
+
|
| 55 |
+
The Corresponding Source for a work in source code form is that same work.
|
| 56 |
+
|
| 57 |
+
2. Basic Permissions.
|
| 58 |
+
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
| 59 |
+
|
| 60 |
+
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
| 61 |
+
|
| 62 |
+
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
| 63 |
+
|
| 64 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 65 |
+
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
| 66 |
+
|
| 67 |
+
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
| 68 |
+
|
| 69 |
+
4. Conveying Verbatim Copies.
|
| 70 |
+
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
| 71 |
+
|
| 72 |
+
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
| 73 |
+
|
| 74 |
+
5. Conveying Modified Source Versions.
|
| 75 |
+
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
| 76 |
+
|
| 77 |
+
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
| 78 |
+
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
| 79 |
+
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
| 80 |
+
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
| 81 |
+
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
| 82 |
+
|
| 83 |
+
6. Conveying Non-Source Forms.
|
| 84 |
+
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
| 85 |
+
|
| 86 |
+
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
| 87 |
+
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
| 88 |
+
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
| 89 |
+
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
| 90 |
+
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
| 91 |
+
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
| 92 |
+
|
| 93 |
+
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
| 94 |
+
|
| 95 |
+
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
| 96 |
+
|
| 97 |
+
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
| 98 |
+
|
| 99 |
+
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
| 100 |
+
|
| 101 |
+
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
| 102 |
+
|
| 103 |
+
7. Additional Terms.
|
| 104 |
+
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
| 105 |
+
|
| 106 |
+
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
| 107 |
+
|
| 108 |
+
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
| 109 |
+
|
| 110 |
+
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
| 111 |
+
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
| 112 |
+
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
| 113 |
+
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
| 114 |
+
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
| 115 |
+
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
| 116 |
+
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
| 117 |
+
|
| 118 |
+
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
| 119 |
+
|
| 120 |
+
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
| 121 |
+
|
| 122 |
+
8. Termination.
|
| 123 |
+
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
| 124 |
+
|
| 125 |
+
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
| 126 |
+
|
| 127 |
+
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
| 128 |
+
|
| 129 |
+
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
| 130 |
+
|
| 131 |
+
9. Acceptance Not Required for Having Copies.
|
| 132 |
+
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
| 133 |
+
|
| 134 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 135 |
+
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
| 136 |
+
|
| 137 |
+
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
| 138 |
+
|
| 139 |
+
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
| 140 |
+
|
| 141 |
+
11. Patents.
|
| 142 |
+
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
| 143 |
+
|
| 144 |
+
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
| 145 |
+
|
| 146 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
| 147 |
+
|
| 148 |
+
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
| 149 |
+
|
| 150 |
+
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
| 151 |
+
|
| 152 |
+
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
| 153 |
+
|
| 154 |
+
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
| 155 |
+
|
| 156 |
+
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
| 157 |
+
|
| 158 |
+
12. No Surrender of Others' Freedom.
|
| 159 |
+
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
| 160 |
+
|
| 161 |
+
13. Use with the GNU Affero General Public License.
|
| 162 |
+
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
| 163 |
+
|
| 164 |
+
14. Revised Versions of this License.
|
| 165 |
+
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
| 166 |
+
|
| 167 |
+
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
| 168 |
+
|
| 169 |
+
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
| 170 |
+
|
| 171 |
+
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
| 172 |
+
|
| 173 |
+
15. Disclaimer of Warranty.
|
| 174 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 175 |
+
|
| 176 |
+
16. Limitation of Liability.
|
| 177 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
| 178 |
+
|
| 179 |
+
17. Interpretation of Sections 15 and 16.
|
| 180 |
+
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
| 181 |
+
|
| 182 |
+
END OF TERMS AND CONDITIONS
|
| 183 |
+
|
| 184 |
+
How to Apply These Terms to Your New Programs
|
| 185 |
+
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
| 186 |
+
|
| 187 |
+
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
| 188 |
+
|
| 189 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 190 |
+
Copyright (C) <year> <name of author>
|
| 191 |
+
|
| 192 |
+
This program is free software: you can redistribute it and/or modify
|
| 193 |
+
it under the terms of the GNU General Public License as published by
|
| 194 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 195 |
+
(at your option) any later version.
|
| 196 |
+
|
| 197 |
+
This program is distributed in the hope that it will be useful,
|
| 198 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 199 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 200 |
+
GNU General Public License for more details.
|
| 201 |
+
|
| 202 |
+
You should have received a copy of the GNU General Public License
|
| 203 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 204 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 205 |
+
|
| 206 |
+
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
| 207 |
+
|
| 208 |
+
<program> Copyright (C) <year> <name of author>
|
| 209 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
| 210 |
+
This is free software, and you are welcome to redistribute it
|
| 211 |
+
under certain conditions; type `show c' for details.
|
| 212 |
+
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
| 213 |
+
|
| 214 |
+
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
| 215 |
+
|
| 216 |
+
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
|
data/HomoAug/README.md
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Code for HomoAug
|
| 2 |
+
|
| 3 |
+
Homoaug is a data augmentation method for generate pseudo-pocket-ligand pairs. It is based on the idea that the ligand binding sites of homologous proteins are similar. The details of HomoAug can be found in our paper: "DrugCLIP: Contrastive Protein-Molecule Representation Learning for Virtual Screening"
|
| 4 |
+
|
| 5 |
+
## Requirements
|
| 6 |
+
|
| 7 |
+
To run the code, you need to install the following packages:
|
| 8 |
+
|
| 9 |
+
- ray (version 1.12.0)
|
| 10 |
+
- jackmmer (a part of HMMER)
|
| 11 |
+
- esl-reformat (a part of HMMER)
|
| 12 |
+
- TM-align
|
| 13 |
+
|
| 14 |
+
Please use 'pip install ray==1.12.0' to install ray.
|
| 15 |
+
|
| 16 |
+
The exeauctable files of jackmmer, esl-reformat and TM-align are included in our folder 'bin', please add the path of 'bin' to your environment variable.
|
| 17 |
+
|
| 18 |
+
## Usage
|
| 19 |
+
|
| 20 |
+
<!--- parser = argparse.ArgumentParser()
|
| 21 |
+
parser.add_argument("--id_file", type=str, default="/drug/BioLip/tmp.id")
|
| 22 |
+
parser.add_argument("--homoaug_dir", type=str, default="/drug/BioLip/homoaug_new")
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"--fasta_file",
|
| 25 |
+
type=str,
|
| 26 |
+
default="/drug/BioLip/BioLiP_v2023-04-13_regularLigand.fasta",
|
| 27 |
+
)
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
"--protein_pdb_dir", type=str, default="/drug/BioLip/protein_pdb"
|
| 30 |
+
)
|
| 31 |
+
parser.add_argument(
|
| 32 |
+
"--pocket_pdbs_dir", type=str, default="/drug/BioLip/pocket_pdb"
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument(
|
| 35 |
+
"--jackhmmer_output_dir", type=str, default="/drug/BioLip/pdbbind_MSA_fasta"
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--n_thread", type=int, default=10, help="number of threads for running"
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument(
|
| 41 |
+
"--database_fasta_path",
|
| 42 |
+
type=str,
|
| 43 |
+
default="/data/protein/AF2DB/AFDB_HC_50.fa",
|
| 44 |
+
help="jackhmmer search database, in fasta format",
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--database_pdb_dir",
|
| 48 |
+
type=str,
|
| 49 |
+
default="/drug/AFDB_HC_50_PDB",
|
| 50 |
+
help="homoaug search database, e.g. AF2DB",
|
| 51 |
+
)
|
| 52 |
+
parser.add_argument(
|
| 53 |
+
"--max_extend_num",
|
| 54 |
+
type=int,
|
| 55 |
+
default=20,
|
| 56 |
+
help="max number of extended pocket-ligand pairs for one real pocket-ligand pair",
|
| 57 |
+
)
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--TMscore_threshold",
|
| 60 |
+
type=float,
|
| 61 |
+
default=0.4,
|
| 62 |
+
help="TMscore threshold for extending",
|
| 63 |
+
)
|
| 64 |
+
parser.add_argument(
|
| 65 |
+
"--Match_rate_threshold",
|
| 66 |
+
type=float,
|
| 67 |
+
default=0.4,
|
| 68 |
+
help="Match_rate threshold for extending",
|
| 69 |
+
)
|
| 70 |
+
-->
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
To use HomoAug, you only need to run the following command:
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
python run_HomoAug.py
|
| 77 |
+
--id_file your_id_file
|
| 78 |
+
--homoaug_dir your_homoaug_dir
|
| 79 |
+
--fasta_file your_fasta_file
|
| 80 |
+
--protein_pdb_dir your_protein_pdb_dir
|
| 81 |
+
--pocket_pdbs_dir your_pocket_pdbs_dir
|
| 82 |
+
--jackhmmer_output_dir your_jackhmmer_output_dir
|
| 83 |
+
--n_thread your_n_thread
|
| 84 |
+
--database_fasta_path your_database_fasta_path
|
| 85 |
+
--database_pdb_dir your_database_pdb_dir
|
| 86 |
+
--max_extend_num your_max_extend_num
|
| 87 |
+
--TMscore_threshold your_TMscore_threshold
|
| 88 |
+
--Match_rate_threshold your_Match_rate_threshold
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
We will explain the meaning of each parameter in the following.
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
#### --id_file
|
| 95 |
+
|
| 96 |
+
The id_file is a file containing the ids of the real pocket-ligand pairs.
|
| 97 |
+
|
| 98 |
+
For example, the id_file of BioLip dataset can be like this:
|
| 99 |
+
|
| 100 |
+
```
|
| 101 |
+
2WNS_B_receptor_B_550_OMP
|
| 102 |
+
5RVK_A_receptor_A_201_2AK
|
| 103 |
+
5F03_A_receptor_A_301_5TA
|
| 104 |
+
7EXF_B_receptor_B_801_GAL
|
| 105 |
+
4OJ4_A_receptor_A_501_DIF
|
| 106 |
+
1PJ7_A_receptor_A_2887_FFO
|
| 107 |
+
......
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
You need to create your own id_file according to your dataset, with the format like :`<pdb_id>_<chain_id>_<any_string>_<ligand_name_in_pdb>
|
| 111 |
+
|
| 112 |
+
#### --homoaug_dir
|
| 113 |
+
|
| 114 |
+
The output directory of HomoAug. When the program is finished, you will find the extended pocket-ligand pairs in this directory.
|
| 115 |
+
|
| 116 |
+
The structure of homoaug_dir is like this:
|
| 117 |
+
|
| 118 |
+
```
|
| 119 |
+
homoaug_dir
|
| 120 |
+
├── PDBID
|
| 121 |
+
│ ├── PDBID.fasta
|
| 122 |
+
│ ├── PDBID.pdb
|
| 123 |
+
│ ├── PDBID_pocket.pdb
|
| 124 |
+
│ ├── PDBID_pocket_chain.pdb
|
| 125 |
+
│ ├── PDBID_ligand.pdb
|
| 126 |
+
│ ├── PDBID_pocket_position.txt
|
| 127 |
+
│ ├── rotation_matrix
|
| 128 |
+
│ │ ├── (several TMalign output files)
|
| 129 |
+
│ ├── *extend*
|
| 130 |
+
│ ├──AugmentedPDBID1
|
| 131 |
+
│ │ ├── AugmentedPDBID1_protein.pdb
|
| 132 |
+
│ │ ├── AugmentedPDBID1_pocket.pdb
|
| 133 |
+
│ ├── AugmentedPDBID2
|
| 134 |
+
│ │ ├── AugmentedPDBID2_protein.pdb
|
| 135 |
+
│ │ ├── AugmentedPDBID2_pocket.pdb
|
| 136 |
+
│ ......
|
| 137 |
+
│
|
| 138 |
+
......
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
Each AugmentedPDBID in extend directory refers to an extended pocket-ligand pair.
|
| 142 |
+
|
| 143 |
+
#### --fasta_file
|
| 144 |
+
|
| 145 |
+
The fasta file crossponding to the id_file. Each title should have the pdbid at the beginning.
|
| 146 |
+
|
| 147 |
+
e.g.:
|
| 148 |
+
|
| 149 |
+
```
|
| 150 |
+
>1q20_A_O00204_A_PLO
|
| 151 |
+
SDISEISQKLPGEYFRYK......
|
| 152 |
+
>1q21_A_P01112_A_GDP
|
| 153 |
+
MTEYKLVVVGAGGVGKSA......
|
| 154 |
+
>1q22_A_O00204_A_A3P
|
| 155 |
+
SDISEISQKLPGEYFRVP......
|
| 156 |
+
......
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
#### --protein_pdb_dir
|
| 160 |
+
|
| 161 |
+
CIF files of the input proteins, in cif format.
|
| 162 |
+
|
| 163 |
+
Name format: <pdb_id>.cif
|
| 164 |
+
|
| 165 |
+
#### --pocket_pdbs_dir
|
| 166 |
+
|
| 167 |
+
PDB files of the input pockets, in pdb format.
|
| 168 |
+
|
| 169 |
+
Name format: <pdb_id>.pdb
|
| 170 |
+
|
| 171 |
+
#### --jackhmmer_output_dir
|
| 172 |
+
|
| 173 |
+
The temporary directory for storing the output of jackhmmer.
|
| 174 |
+
|
| 175 |
+
#### --n_thread
|
| 176 |
+
|
| 177 |
+
Number of threads for running.
|
| 178 |
+
|
| 179 |
+
#### --database_fasta_path
|
| 180 |
+
|
| 181 |
+
The fasta file of the database used for augmentation database, e.g. AF2DB.
|
| 182 |
+
|
| 183 |
+
#### --database_pdb_dir
|
| 184 |
+
|
| 185 |
+
The pdb directory of the database used for augmentation database, e.g. AF2DB's pdb directory.
|
| 186 |
+
|
| 187 |
+
#### --max_extend_num
|
| 188 |
+
|
| 189 |
+
The max number of extended pocket-ligand pairs for one real pocket-ligand pair.
|
| 190 |
+
|
| 191 |
+
#### --TMscore_threshold and Match_rate_threshold
|
| 192 |
+
|
| 193 |
+
Only the extended pocket-ligand pairs with TMscore >= TMscore_threshold and Match_rate >= Match_rate_threshold will be kept.
|
| 194 |
+
|
| 195 |
+
Match_rate is the ratio of the number of matched residues to the number of residues in the real pocket.
|
| 196 |
+
|
| 197 |
+
## Note
|
| 198 |
+
|
| 199 |
+
For various error scenarios, we choose to skip the HomoAug for this pocket-ligand pair, including but not limited to cases where the pocket is composed of multiple chains. Please note that even if the program executes successfully, some files may be missing in certain output directories, indicating that this pocket-ligand pair is currently not suitable for HomoAug. In summary, all valid HomoAug results will be saved in the 'extend' folder.
|
data/HomoAug/bin/TMalign
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:251728ae4011e44afa8b680645d6803cecf3c7f57a359a4f6975788a439f7cc4
|
| 3 |
+
size 3020432
|
data/HomoAug/bin/esl-reformat
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a25da01e2b0601b59b6c14c08e87bb9c2cf41c6accbc3d02c72b40cfff0037cc
|
| 3 |
+
size 475088
|
data/HomoAug/bin/jackhmmer
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:68807de0c9f86e9061ac168603e2e741511226164b09d4fea1cafb8471454990
|
| 3 |
+
size 1165768
|
data/HomoAug/run_HomoAug.py
ADDED
|
@@ -0,0 +1,838 @@
|
|
|
|
|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
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
import glob
|
| 7 |
+
import Bio.PDB
|
| 8 |
+
import ray
|
| 9 |
+
import random
|
| 10 |
+
import json
|
| 11 |
+
import mmap
|
| 12 |
+
import time
|
| 13 |
+
import sys
|
| 14 |
+
import traceback
|
| 15 |
+
from ray.util.queue import Queue
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
sys.path.append(".")
|
| 19 |
+
from utils.misc import execute
|
| 20 |
+
from utils.ray_tools import ProgressBar
|
| 21 |
+
from tqdm import tqdm
|
| 22 |
+
import pathlib
|
| 23 |
+
import subprocess
|
| 24 |
+
import shutil
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class JackhmmerRunner:
|
| 28 |
+
def __init__(self, database_dir, task_ids, seq_dir, output_dir, n_thread):
|
| 29 |
+
self.N_CPU_PER_THREAD = 1
|
| 30 |
+
self.n_thread = n_thread
|
| 31 |
+
self.database_dir = database_dir
|
| 32 |
+
self.task_ids = task_ids
|
| 33 |
+
self.seq_dir = seq_dir
|
| 34 |
+
self.output_dir = output_dir
|
| 35 |
+
if output_dir.endswith("/"):
|
| 36 |
+
output_dir = output_dir[:-1]
|
| 37 |
+
if not os.path.exists(output_dir):
|
| 38 |
+
os.mkdir(output_dir)
|
| 39 |
+
self.sto_dir = output_dir + "_sto"
|
| 40 |
+
if not os.path.exists(self.sto_dir):
|
| 41 |
+
os.mkdir(self.sto_dir)
|
| 42 |
+
self.a2m_dir = output_dir + "_a2m"
|
| 43 |
+
if not os.path.exists(self.a2m_dir):
|
| 44 |
+
os.mkdir(self.a2m_dir)
|
| 45 |
+
|
| 46 |
+
def split_list(_list, n):
|
| 47 |
+
chunk_size = (len(_list) - 1) // n + 1
|
| 48 |
+
chunks = [_list[i * chunk_size : (i + 1) * chunk_size] for i in range(n)]
|
| 49 |
+
return chunks
|
| 50 |
+
|
| 51 |
+
@ray.remote(num_cpus=1)
|
| 52 |
+
def process_jobs(self, id, jobs_queue, actor):
|
| 53 |
+
print("start process", id)
|
| 54 |
+
while not jobs_queue.empty():
|
| 55 |
+
job = jobs_queue.get()
|
| 56 |
+
try:
|
| 57 |
+
self.execute_one_job(job)
|
| 58 |
+
|
| 59 |
+
except:
|
| 60 |
+
print(f"failed: {job}")
|
| 61 |
+
traceback.print_exception(*sys.exc_info())
|
| 62 |
+
try:
|
| 63 |
+
actor.update.remote(1)
|
| 64 |
+
except:
|
| 65 |
+
pass
|
| 66 |
+
return 1
|
| 67 |
+
|
| 68 |
+
def execute_one_job(self, job):
|
| 69 |
+
seq_file_Path = pathlib.Path(self.seq_dir) / job[:4] / (job + ".fasta")
|
| 70 |
+
output_file_Path = pathlib.Path(self.sto_dir) / (job + ".sto")
|
| 71 |
+
execute(
|
| 72 |
+
f"jackhmmer"
|
| 73 |
+
f" --cpu {self.N_CPU_PER_THREAD}"
|
| 74 |
+
f" -A {output_file_Path}"
|
| 75 |
+
f" -o /dev/null"
|
| 76 |
+
f" -E 0.001"
|
| 77 |
+
f" -N 3"
|
| 78 |
+
f" {str(seq_file_Path)}"
|
| 79 |
+
f" {self.database_dir}"
|
| 80 |
+
)
|
| 81 |
+
# with open(output_file_Path,"w") as f:
|
| 82 |
+
# f.write("")
|
| 83 |
+
# # sleep 1 s
|
| 84 |
+
# time.sleep(1)
|
| 85 |
+
return 1
|
| 86 |
+
|
| 87 |
+
def change_sto_to_fasta(self):
|
| 88 |
+
sto_files = glob.glob(self.sto_dir + "/*.sto")
|
| 89 |
+
for sto_path in tqdm(sto_files):
|
| 90 |
+
pdb_id = sto_path.split("/")[-1].split(".")[0]
|
| 91 |
+
# print(pdb_id)
|
| 92 |
+
a2m_path = self.a2m_dir + f"/{pdb_id}.a2m"
|
| 93 |
+
execute(
|
| 94 |
+
f"esl-reformat --informat stockholm"
|
| 95 |
+
f" -o {str(a2m_path)} a2m"
|
| 96 |
+
f" {str(sto_path)}"
|
| 97 |
+
)
|
| 98 |
+
fasta_path = self.output_dir + f"/{pdb_id}.fasta"
|
| 99 |
+
output = ""
|
| 100 |
+
with open(a2m_path) as f:
|
| 101 |
+
for line in f:
|
| 102 |
+
line = line.strip()
|
| 103 |
+
if line[0] != ">":
|
| 104 |
+
output += line
|
| 105 |
+
else:
|
| 106 |
+
output += "\n" + line + "\n"
|
| 107 |
+
output = output.strip()
|
| 108 |
+
output = output.split("\n")[:-2]
|
| 109 |
+
output = "\n".join(output)
|
| 110 |
+
with open(fasta_path, "w") as f:
|
| 111 |
+
f.write(output)
|
| 112 |
+
|
| 113 |
+
def run_jackhmmer(self):
|
| 114 |
+
all_jobs = []
|
| 115 |
+
with open(self.task_ids, "r") as f:
|
| 116 |
+
data = f.readlines()
|
| 117 |
+
for line in data:
|
| 118 |
+
job = line.strip()
|
| 119 |
+
job = job[:4].upper()
|
| 120 |
+
all_jobs.append(job)
|
| 121 |
+
print("all jobs:", len(all_jobs))
|
| 122 |
+
uncompleted_jobs = all_jobs
|
| 123 |
+
# completed?
|
| 124 |
+
# uncompleted_jobs=[]
|
| 125 |
+
# for job in all_jobs:
|
| 126 |
+
# if (not is_complete(job)):
|
| 127 |
+
# uncompleted_jobs.append(job)
|
| 128 |
+
# print("uncompleted jobs:",len(uncompleted_jobs))
|
| 129 |
+
ray.init()
|
| 130 |
+
job_queue = Queue()
|
| 131 |
+
for job in tqdm(uncompleted_jobs):
|
| 132 |
+
job_queue.put(job)
|
| 133 |
+
print("job queue size:", job_queue.qsize())
|
| 134 |
+
pb = ProgressBar(len(all_jobs))
|
| 135 |
+
actor = pb.actor
|
| 136 |
+
print("actor:", actor)
|
| 137 |
+
job_id_list = []
|
| 138 |
+
self.n_thread = min(self.n_thread, len(uncompleted_jobs))
|
| 139 |
+
for i in range(self.n_thread):
|
| 140 |
+
job_id_list.append(self.process_jobs.remote(self, i, job_queue, actor))
|
| 141 |
+
pb.print_until_done()
|
| 142 |
+
result = ray.get(job_id_list)
|
| 143 |
+
print("Run homo search done!")
|
| 144 |
+
ray.shutdown()
|
| 145 |
+
|
| 146 |
+
# remove tmp folders
|
| 147 |
+
shutil.rmtree(self.a2m_dir)
|
| 148 |
+
shutil.rmtree(self.sto_dir)
|
| 149 |
+
|
| 150 |
+
# change sto to fasta
|
| 151 |
+
self.change_sto_to_fasta()
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class LigandPocketExtractor:
|
| 155 |
+
def __init__(self, id_file, homoaug_dir, n_thread):
|
| 156 |
+
self.id_file = id_file
|
| 157 |
+
self.homoaug_dir = homoaug_dir
|
| 158 |
+
self.n_thread = n_thread
|
| 159 |
+
self.read_ligand_name_chain_name()
|
| 160 |
+
|
| 161 |
+
def read_ligand_name_chain_name(self):
|
| 162 |
+
# read ligand_name
|
| 163 |
+
ligand_name = {}
|
| 164 |
+
chain_name = {}
|
| 165 |
+
with open(self.id_file, "r") as f:
|
| 166 |
+
for line in f.readlines():
|
| 167 |
+
line = line.strip()
|
| 168 |
+
id = line[:4].upper()
|
| 169 |
+
ligand_name[id] = line.split("_")[-1]
|
| 170 |
+
chain_name[id] = line.split("_")[1]
|
| 171 |
+
# print("ligand_name:",ligand_name)
|
| 172 |
+
self.ligand_name = ligand_name
|
| 173 |
+
self.chain_name = chain_name
|
| 174 |
+
|
| 175 |
+
def execute_one_job(self, job):
|
| 176 |
+
id = job
|
| 177 |
+
# print ('############################')
|
| 178 |
+
# print (id)
|
| 179 |
+
# read original pdb
|
| 180 |
+
pdb_file = self.homoaug_dir + "/" + id + "/" + id + "_protein.pdb"
|
| 181 |
+
if not os.path.exists(pdb_file):
|
| 182 |
+
print("no pdb file for id:", id)
|
| 183 |
+
return 1
|
| 184 |
+
pdb_parser = Bio.PDB.PDBParser(QUIET=True)
|
| 185 |
+
structure = pdb_parser.get_structure(id, pdb_file)
|
| 186 |
+
model = structure[0]
|
| 187 |
+
chain = model[self.chain_name[id]]
|
| 188 |
+
# get pocket_chain to a new pdb
|
| 189 |
+
pocket_chain = Bio.PDB.Chain.Chain(self.chain_name[id])
|
| 190 |
+
for residue in chain:
|
| 191 |
+
if residue.id[0] == " ":
|
| 192 |
+
pocket_chain.add(residue)
|
| 193 |
+
io = Bio.PDB.PDBIO()
|
| 194 |
+
io.set_structure(pocket_chain)
|
| 195 |
+
io.save(self.homoaug_dir + "/" + id + "/" + id + "_pocket_chain.pdb")
|
| 196 |
+
|
| 197 |
+
# save ligand to a new pdb
|
| 198 |
+
ligand_chain = Bio.PDB.Chain.Chain(self.chain_name[id])
|
| 199 |
+
ligand_found = False
|
| 200 |
+
for residue in chain:
|
| 201 |
+
if residue.resname == self.ligand_name[id]:
|
| 202 |
+
ligand_chain.add(residue)
|
| 203 |
+
ligand_found = True
|
| 204 |
+
if ligand_found:
|
| 205 |
+
io = Bio.PDB.PDBIO()
|
| 206 |
+
io.set_structure(ligand_chain)
|
| 207 |
+
io.save(self.homoaug_dir + "/" + id + "/" + id + "_ligand.pdb")
|
| 208 |
+
else:
|
| 209 |
+
print("ligand not found:", id)
|
| 210 |
+
return 1
|
| 211 |
+
|
| 212 |
+
# remove ligand in the id.pocket.pdb
|
| 213 |
+
pdb_file = self.homoaug_dir + "/" + id + "/" + id + "_pocket.pdb"
|
| 214 |
+
pdb_parser = Bio.PDB.PDBParser(QUIET=True)
|
| 215 |
+
structure = pdb_parser.get_structure(id, pdb_file)
|
| 216 |
+
model = structure[0]
|
| 217 |
+
chain = model["R"]
|
| 218 |
+
# get pocket to a new pdb
|
| 219 |
+
pocket = Bio.PDB.Chain.Chain("A")
|
| 220 |
+
for residue in chain:
|
| 221 |
+
if residue.id[0] == " ":
|
| 222 |
+
pocket.add(residue)
|
| 223 |
+
# write pocket pdb
|
| 224 |
+
io = Bio.PDB.PDBIO()
|
| 225 |
+
io.set_structure(pocket)
|
| 226 |
+
io.save(self.homoaug_dir + "/" + id + "/" + id + "_pocket.pdb")
|
| 227 |
+
|
| 228 |
+
@ray.remote(num_cpus=1)
|
| 229 |
+
def process_jobs(self, id, jobs_queue, actor):
|
| 230 |
+
print("start process", id)
|
| 231 |
+
while not jobs_queue.empty():
|
| 232 |
+
job = jobs_queue.get()
|
| 233 |
+
try:
|
| 234 |
+
self.execute_one_job(job)
|
| 235 |
+
except:
|
| 236 |
+
print(f"failed: {job}")
|
| 237 |
+
traceback.print_exception(*sys.exc_info())
|
| 238 |
+
try:
|
| 239 |
+
actor.update.remote(1)
|
| 240 |
+
except:
|
| 241 |
+
pass
|
| 242 |
+
return 1
|
| 243 |
+
|
| 244 |
+
def run(self):
|
| 245 |
+
all_jobs = glob.glob(self.homoaug_dir + "/*")
|
| 246 |
+
all_jobs = [x.split("/")[-1] for x in all_jobs]
|
| 247 |
+
uncompleted_jobs = all_jobs
|
| 248 |
+
job_queue = Queue()
|
| 249 |
+
for job in tqdm(uncompleted_jobs):
|
| 250 |
+
job_queue.put(job)
|
| 251 |
+
print("job queue size:", job_queue.qsize())
|
| 252 |
+
pb = ProgressBar(len(all_jobs))
|
| 253 |
+
actor = pb.actor
|
| 254 |
+
job_id_list = []
|
| 255 |
+
self.n_thread = min(self.n_thread, len(uncompleted_jobs))
|
| 256 |
+
for i in range(self.n_thread):
|
| 257 |
+
job_id_list.append(self.process_jobs.remote(self, i, job_queue, actor))
|
| 258 |
+
pb.print_until_done()
|
| 259 |
+
result = ray.get(job_id_list)
|
| 260 |
+
ray.shutdown()
|
| 261 |
+
print("Done!")
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class PocketPositionExtractor:
|
| 265 |
+
def __init__(self, homoaug_dir, n_thread):
|
| 266 |
+
self.homoaug_dir = homoaug_dir
|
| 267 |
+
self.n_thread = n_thread
|
| 268 |
+
self.aa_3_to_1 = {
|
| 269 |
+
"CYS": "C",
|
| 270 |
+
"ASP": "D",
|
| 271 |
+
"SER": "S",
|
| 272 |
+
"GLN": "Q",
|
| 273 |
+
"LYS": "K",
|
| 274 |
+
"ILE": "I",
|
| 275 |
+
"PRO": "P",
|
| 276 |
+
"THR": "T",
|
| 277 |
+
"PHE": "F",
|
| 278 |
+
"ASN": "N",
|
| 279 |
+
"GLY": "G",
|
| 280 |
+
"HIS": "H",
|
| 281 |
+
"LEU": "L",
|
| 282 |
+
"ARG": "R",
|
| 283 |
+
"TRP": "W",
|
| 284 |
+
"ALA": "A",
|
| 285 |
+
"VAL": "V",
|
| 286 |
+
"GLU": "E",
|
| 287 |
+
"TYR": "Y",
|
| 288 |
+
"MET": "M",
|
| 289 |
+
"MSE": "M",
|
| 290 |
+
"CME": "C",
|
| 291 |
+
"CSO": "C",
|
| 292 |
+
"UNK": "X",
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
def execute_one_job(self, job):
|
| 296 |
+
id = job
|
| 297 |
+
# print ('############################')
|
| 298 |
+
# print (id)
|
| 299 |
+
|
| 300 |
+
# read pocket_pdb
|
| 301 |
+
pocket_pdb_file = self.homoaug_dir + "/" + id + "/" + id + "_pocket.pdb"
|
| 302 |
+
pocket_pdb_structure = Bio.PDB.PDBParser().get_structure(id, pocket_pdb_file)
|
| 303 |
+
model = pocket_pdb_structure[0]
|
| 304 |
+
for chain in model:
|
| 305 |
+
pocket_chain_id = chain.id
|
| 306 |
+
break
|
| 307 |
+
chain = model[pocket_chain_id]
|
| 308 |
+
|
| 309 |
+
# get the pocket atom coordinates
|
| 310 |
+
pocket_atom_coordinates = set()
|
| 311 |
+
for residue in chain:
|
| 312 |
+
if residue.id[0] != " ":
|
| 313 |
+
continue
|
| 314 |
+
for atom in residue:
|
| 315 |
+
pocket_atom_coordinates.add(tuple(atom.get_coord()))
|
| 316 |
+
# print("pocket_atom_coordinates:",pocket_atom_coordinates)
|
| 317 |
+
|
| 318 |
+
sequence = ""
|
| 319 |
+
pocket_chain_pdb_file = (
|
| 320 |
+
self.homoaug_dir + "/" + id + "/" + id + "_pocket_chain.pdb"
|
| 321 |
+
)
|
| 322 |
+
# get the position of the pocket residues in the pocket chain
|
| 323 |
+
pocket_chain_structure = Bio.PDB.PDBParser().get_structure(
|
| 324 |
+
id, pocket_chain_pdb_file
|
| 325 |
+
)
|
| 326 |
+
model = pocket_chain_structure[0]
|
| 327 |
+
for chain in model:
|
| 328 |
+
pocket_chain_id = chain.id
|
| 329 |
+
break
|
| 330 |
+
chain_num = len(list(model.get_chains()))
|
| 331 |
+
if chain_num > 1:
|
| 332 |
+
print("error: more than 1 chain in pocket_pdb_file:", id)
|
| 333 |
+
return 1
|
| 334 |
+
chain = model[pocket_chain_id]
|
| 335 |
+
for residue in chain:
|
| 336 |
+
if residue.id[0] != " ":
|
| 337 |
+
continue
|
| 338 |
+
in_pocket = False
|
| 339 |
+
for atom in residue:
|
| 340 |
+
if tuple(atom.get_coord()) in pocket_atom_coordinates:
|
| 341 |
+
in_pocket = True
|
| 342 |
+
break
|
| 343 |
+
if in_pocket:
|
| 344 |
+
sequence += self.aa_3_to_1[residue.resname]
|
| 345 |
+
else:
|
| 346 |
+
sequence += "-"
|
| 347 |
+
|
| 348 |
+
# save
|
| 349 |
+
sequence_position_file = (
|
| 350 |
+
self.homoaug_dir + "/" + id + "/" + id + "_pocket_position.txt"
|
| 351 |
+
)
|
| 352 |
+
with open(sequence_position_file, "w") as f:
|
| 353 |
+
f.write(sequence)
|
| 354 |
+
|
| 355 |
+
@ray.remote(num_cpus=1)
|
| 356 |
+
def process_jobs(self, id, jobs_queue, actor):
|
| 357 |
+
print("start process", id)
|
| 358 |
+
while not jobs_queue.empty():
|
| 359 |
+
job = jobs_queue.get()
|
| 360 |
+
try:
|
| 361 |
+
self.execute_one_job(job)
|
| 362 |
+
except:
|
| 363 |
+
print(f"failed: {job}")
|
| 364 |
+
traceback.print_exception(*sys.exc_info())
|
| 365 |
+
try:
|
| 366 |
+
actor.update.remote(1)
|
| 367 |
+
except:
|
| 368 |
+
pass
|
| 369 |
+
return 1
|
| 370 |
+
|
| 371 |
+
def run(self):
|
| 372 |
+
all_jobs = []
|
| 373 |
+
for id in os.listdir(self.homoaug_dir):
|
| 374 |
+
if os.path.isfile(self.homoaug_dir + "/" + id + "/" + id + "_ligand.pdb"):
|
| 375 |
+
if os.path.isfile(
|
| 376 |
+
self.homoaug_dir + "/" + id + "/" + id + "_pocket.pdb"
|
| 377 |
+
):
|
| 378 |
+
all_jobs.append(id)
|
| 379 |
+
uncompleted_jobs = all_jobs
|
| 380 |
+
job_queue = Queue()
|
| 381 |
+
for job in tqdm(uncompleted_jobs):
|
| 382 |
+
job_queue.put(job)
|
| 383 |
+
print("job queue size:", job_queue.qsize())
|
| 384 |
+
pb = ProgressBar(len(all_jobs))
|
| 385 |
+
actor = pb.actor
|
| 386 |
+
job_id_list = []
|
| 387 |
+
self.n_thread = min(self.n_thread, len(uncompleted_jobs))
|
| 388 |
+
for i in range(self.n_thread):
|
| 389 |
+
job_id_list.append(self.process_jobs.remote(self, i, job_queue, actor))
|
| 390 |
+
pb.print_until_done()
|
| 391 |
+
result = ray.get(job_id_list)
|
| 392 |
+
ray.shutdown()
|
| 393 |
+
print("Done!")
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class TMalignRunner:
|
| 397 |
+
def __init__(
|
| 398 |
+
self,
|
| 399 |
+
max_extend_num,
|
| 400 |
+
homoaug_dir,
|
| 401 |
+
MSA_dir,
|
| 402 |
+
AF2DB_dir,
|
| 403 |
+
TMscore_threshold,
|
| 404 |
+
Match_rate_threshold,
|
| 405 |
+
n_thread,
|
| 406 |
+
):
|
| 407 |
+
self.n_thread = n_thread
|
| 408 |
+
self.max_extend_num = max_extend_num
|
| 409 |
+
self.homoaug_dir = homoaug_dir
|
| 410 |
+
self.MSA_dir = MSA_dir
|
| 411 |
+
self.AF2DB_dir = AF2DB_dir
|
| 412 |
+
self.TMscore_threshold = TMscore_threshold
|
| 413 |
+
self.Match_rate_threshold = Match_rate_threshold
|
| 414 |
+
|
| 415 |
+
def _remove_gap_of_primary_sequence(self, primary_sequence, candidate_sequence):
|
| 416 |
+
assert len(primary_sequence) == len(candidate_sequence)
|
| 417 |
+
primary_sequence_without_gap = ""
|
| 418 |
+
candidate_sequence_without_gap = ""
|
| 419 |
+
for i in range(len(primary_sequence)):
|
| 420 |
+
if primary_sequence[i] != "-":
|
| 421 |
+
primary_sequence_without_gap += primary_sequence[i]
|
| 422 |
+
candidate_sequence_without_gap += candidate_sequence[i]
|
| 423 |
+
return primary_sequence_without_gap, candidate_sequence_without_gap
|
| 424 |
+
|
| 425 |
+
def _calc_match_rate(self, pocket_position, Aligned_seq):
|
| 426 |
+
total_cnt = 0
|
| 427 |
+
match_cnt = 0
|
| 428 |
+
for i in range(len(Aligned_seq)):
|
| 429 |
+
if pocket_position[i] != "-":
|
| 430 |
+
total_cnt += 1
|
| 431 |
+
if pocket_position[i] == Aligned_seq[i]:
|
| 432 |
+
match_cnt += 1
|
| 433 |
+
return match_cnt / total_cnt
|
| 434 |
+
|
| 435 |
+
def _get_rotate_matrix(self, rotate_matrix_file):
|
| 436 |
+
with open(rotate_matrix_file, "r") as f:
|
| 437 |
+
data = f.readlines()
|
| 438 |
+
u = []
|
| 439 |
+
t = []
|
| 440 |
+
for i in range(2, 5):
|
| 441 |
+
line = data[i].split(" ")
|
| 442 |
+
line_float = [float(x) for x in line if x != ""]
|
| 443 |
+
t.append(line_float[1])
|
| 444 |
+
u.append(line_float[2:])
|
| 445 |
+
u = np.array(u)
|
| 446 |
+
t = np.array(t)
|
| 447 |
+
return u, t
|
| 448 |
+
|
| 449 |
+
def _read_ligand_pdb(self, ligand_pdb_file):
|
| 450 |
+
parser = Bio.PDB.PDBParser()
|
| 451 |
+
structure = parser.get_structure("ligand", ligand_pdb_file)
|
| 452 |
+
ligand_coords = []
|
| 453 |
+
for model in structure:
|
| 454 |
+
for chain in model:
|
| 455 |
+
for residue in chain:
|
| 456 |
+
for atom in residue:
|
| 457 |
+
ligand_coords.append(atom.get_coord())
|
| 458 |
+
return ligand_coords
|
| 459 |
+
|
| 460 |
+
@ray.remote(num_cpus=1)
|
| 461 |
+
def process_jobs(self, id, jobs_queue, actor):
|
| 462 |
+
print("start process", id)
|
| 463 |
+
while not jobs_queue.empty():
|
| 464 |
+
job = jobs_queue.get()
|
| 465 |
+
try:
|
| 466 |
+
self.execute_one_job(job)
|
| 467 |
+
|
| 468 |
+
except:
|
| 469 |
+
print(f"failed: {job}")
|
| 470 |
+
traceback.print_exception(*sys.exc_info())
|
| 471 |
+
try:
|
| 472 |
+
actor.update.remote(1)
|
| 473 |
+
except:
|
| 474 |
+
pass
|
| 475 |
+
return 1
|
| 476 |
+
|
| 477 |
+
def execute_one_job(self, id):
|
| 478 |
+
# print("#######################")
|
| 479 |
+
print(id)
|
| 480 |
+
# get the sequence from pdb
|
| 481 |
+
fasta_dir = self.homoaug_dir + "/" + id + "/" + id + ".fasta"
|
| 482 |
+
with open(fasta_dir) as f:
|
| 483 |
+
fasta = f.readlines()
|
| 484 |
+
|
| 485 |
+
# read the pocket position
|
| 486 |
+
pocket_position_file = (
|
| 487 |
+
self.homoaug_dir + "/" + id + "/" + id + "_pocket_position.txt"
|
| 488 |
+
)
|
| 489 |
+
if not os.path.exists(pocket_position_file):
|
| 490 |
+
print("position_file not exist")
|
| 491 |
+
return 1
|
| 492 |
+
with open(pocket_position_file) as f:
|
| 493 |
+
pocket_position = f.readline().strip()
|
| 494 |
+
|
| 495 |
+
# create rotation matrix dir
|
| 496 |
+
rotation_matrix_dir = self.homoaug_dir + "/" + id + "/" + "rotation_matrix/"
|
| 497 |
+
if not os.path.exists(rotation_matrix_dir):
|
| 498 |
+
os.makedirs(rotation_matrix_dir)
|
| 499 |
+
|
| 500 |
+
# get the sequence from TMalign
|
| 501 |
+
chain_pdb_file = self.homoaug_dir + "/" + id + "/" + id + "_pocket_chain.pdb"
|
| 502 |
+
MSA_file = self.MSA_dir + f"/{id}" + ".fasta"
|
| 503 |
+
if not os.path.exists(MSA_file):
|
| 504 |
+
print("MSA_file not exist")
|
| 505 |
+
return 1
|
| 506 |
+
MSA_ids = []
|
| 507 |
+
with open(MSA_file) as f:
|
| 508 |
+
lines = f.readlines()
|
| 509 |
+
for idx in range(0, len(lines), 2):
|
| 510 |
+
MSA_ids.append(lines[idx].strip().split(" ")[-1])
|
| 511 |
+
|
| 512 |
+
# create extend dir
|
| 513 |
+
extend_dir = self.homoaug_dir + "/" + id + "/" + "extend"
|
| 514 |
+
if not os.path.exists(extend_dir):
|
| 515 |
+
os.mkdir(extend_dir)
|
| 516 |
+
|
| 517 |
+
# get ligand
|
| 518 |
+
ligand_file = self.homoaug_dir + "/" + id + "/" + id + "_ligand.pdb"
|
| 519 |
+
ligand_coords = self._read_ligand_pdb(ligand_file)
|
| 520 |
+
|
| 521 |
+
# TMalign
|
| 522 |
+
cnt = len(glob.glob(extend_dir + "/*"))
|
| 523 |
+
for MSA_id in list(MSA_ids):
|
| 524 |
+
if cnt >= self.max_extend_num:
|
| 525 |
+
break
|
| 526 |
+
# calculate TMscore
|
| 527 |
+
MSA_pdb_file = self.AF2DB_dir + f"/{MSA_id}.pdb"
|
| 528 |
+
if not os.path.exists(MSA_pdb_file):
|
| 529 |
+
continue
|
| 530 |
+
rotation_matrix_file = rotation_matrix_dir + f"{MSA_id}.txt"
|
| 531 |
+
if os.path.exists(rotation_matrix_file):
|
| 532 |
+
continue
|
| 533 |
+
out_bytes = subprocess.check_output(
|
| 534 |
+
["TMalign", MSA_pdb_file, chain_pdb_file, "-m", rotation_matrix_file]
|
| 535 |
+
)
|
| 536 |
+
out_text = out_bytes.decode("utf-8").strip().split("\n")
|
| 537 |
+
TMscore1 = float(out_text[12].split(" ")[1])
|
| 538 |
+
TMscore2 = float(out_text[13].split(" ")[1])
|
| 539 |
+
(
|
| 540 |
+
sequence_from_TMalign,
|
| 541 |
+
MSA_aligned_sequence,
|
| 542 |
+
) = self._remove_gap_of_primary_sequence(out_text[19], out_text[17])
|
| 543 |
+
TMalign_file = rotation_matrix_dir + f"{MSA_id}_TMscore.txt"
|
| 544 |
+
with open(TMalign_file, "w") as f:
|
| 545 |
+
f.write("TMscore normalized to chain_pdb:" + str(TMscore2) + "\n")
|
| 546 |
+
f.write("TMscore normalized to MSA_pdb:" + str(TMscore1) + "\n")
|
| 547 |
+
f.write("Aligned sequence : \n")
|
| 548 |
+
f.write(sequence_from_TMalign + "\n")
|
| 549 |
+
f.write(MSA_aligned_sequence + "\n")
|
| 550 |
+
TMscore = TMscore2
|
| 551 |
+
|
| 552 |
+
# calculate Match_score
|
| 553 |
+
Aligned_seq = MSA_aligned_sequence
|
| 554 |
+
Match_rate = self._calc_match_rate(pocket_position, Aligned_seq)
|
| 555 |
+
|
| 556 |
+
# print("MSA_id:",MSA_id)
|
| 557 |
+
# print("TMscore:",TMscore)
|
| 558 |
+
# print("Match_rate:",Match_rate)
|
| 559 |
+
if (
|
| 560 |
+
TMscore >= self.TMscore_threshold
|
| 561 |
+
and Match_rate >= self.Match_rate_threshold
|
| 562 |
+
):
|
| 563 |
+
extend_instance_dir = extend_dir + "/" + MSA_id + "/"
|
| 564 |
+
# if os.path.exists(extend_instance_dir):
|
| 565 |
+
# continue
|
| 566 |
+
os.mkdir(extend_instance_dir)
|
| 567 |
+
|
| 568 |
+
# read ori MSA pdb file
|
| 569 |
+
MSA_pdb_file = self.AF2DB_dir + f"/{MSA_id}" + ".pdb"
|
| 570 |
+
parser = Bio.PDB.PDBParser()
|
| 571 |
+
structure = parser.get_structure(MSA_id, MSA_pdb_file)
|
| 572 |
+
model = structure[0]
|
| 573 |
+
for chain in model:
|
| 574 |
+
MSA_chain_id = chain.id
|
| 575 |
+
break
|
| 576 |
+
MSA_chain = model[MSA_chain_id]
|
| 577 |
+
|
| 578 |
+
# get rotate_matrix
|
| 579 |
+
rotation_matrix_file = rotation_matrix_dir + f"{MSA_id}.txt"
|
| 580 |
+
rotation_matrix = self._get_rotate_matrix(rotation_matrix_file)
|
| 581 |
+
|
| 582 |
+
for residue in MSA_chain:
|
| 583 |
+
for atom in residue:
|
| 584 |
+
coord = atom.get_coord()
|
| 585 |
+
coord = np.array(coord)
|
| 586 |
+
new_coord = (
|
| 587 |
+
np.dot(rotation_matrix[0], coord) + rotation_matrix[1]
|
| 588 |
+
)
|
| 589 |
+
atom.set_coord(new_coord)
|
| 590 |
+
|
| 591 |
+
# write new pdb file
|
| 592 |
+
io = Bio.PDB.PDBIO()
|
| 593 |
+
io.set_structure(structure)
|
| 594 |
+
io.save(extend_instance_dir + f"{MSA_id}" + "_protein.pdb")
|
| 595 |
+
|
| 596 |
+
# get pocket , which is in the 6A of ligand
|
| 597 |
+
MSA_pocket_file = extend_instance_dir + f"{MSA_id}" + "_pocket.pdb"
|
| 598 |
+
for residue in MSA_chain:
|
| 599 |
+
remove_atom_ids = []
|
| 600 |
+
for atom in residue:
|
| 601 |
+
# print("atom: ",atom.id)
|
| 602 |
+
coord = atom.get_coord()
|
| 603 |
+
f = 0
|
| 604 |
+
for ligand_coord in ligand_coords:
|
| 605 |
+
dis = np.linalg.norm(coord - ligand_coord)
|
| 606 |
+
if np.linalg.norm(coord - ligand_coord) <= 6:
|
| 607 |
+
f = 1
|
| 608 |
+
break
|
| 609 |
+
if f == 0:
|
| 610 |
+
remove_atom_ids.append(atom.id)
|
| 611 |
+
for atom_id in remove_atom_ids:
|
| 612 |
+
residue.detach_child(atom_id)
|
| 613 |
+
io = Bio.PDB.PDBIO()
|
| 614 |
+
io.set_structure(structure)
|
| 615 |
+
io.save(MSA_pocket_file)
|
| 616 |
+
cnt += 1
|
| 617 |
+
print("finish: pdb_id:", id)
|
| 618 |
+
return 1
|
| 619 |
+
|
| 620 |
+
def run(self):
|
| 621 |
+
all_jobs = []
|
| 622 |
+
for id in os.listdir(self.homoaug_dir):
|
| 623 |
+
if (
|
| 624 |
+
os.path.isfile(self.homoaug_dir + "/" + id + "/" + id + "_ligand.pdb")
|
| 625 |
+
and os.path.isfile(
|
| 626 |
+
self.homoaug_dir + "/" + id + "/" + id + "_pocket.pdb"
|
| 627 |
+
)
|
| 628 |
+
and os.path.isfile(
|
| 629 |
+
self.homoaug_dir + "/" + id + "/" + id + "_pocket_position.txt"
|
| 630 |
+
)
|
| 631 |
+
):
|
| 632 |
+
all_jobs.append(id)
|
| 633 |
+
uncompleted_jobs = all_jobs
|
| 634 |
+
job_queue = Queue()
|
| 635 |
+
for job in tqdm(uncompleted_jobs):
|
| 636 |
+
job_queue.put(job)
|
| 637 |
+
print("job queue size:", job_queue.qsize())
|
| 638 |
+
pb = ProgressBar(len(all_jobs))
|
| 639 |
+
actor = pb.actor
|
| 640 |
+
job_id_list = []
|
| 641 |
+
self.n_thread = min(self.n_thread, len(uncompleted_jobs))
|
| 642 |
+
for i in range(self.n_thread):
|
| 643 |
+
job_id_list.append(self.process_jobs.remote(self, i, job_queue, actor))
|
| 644 |
+
pb.print_until_done()
|
| 645 |
+
result = ray.get(job_id_list)
|
| 646 |
+
ray.shutdown()
|
| 647 |
+
print("Done!")
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
class HomoAugRunner:
|
| 651 |
+
def __init__(self, args):
|
| 652 |
+
self.id_file = args.id_file
|
| 653 |
+
self.homoaug_dir = args.homoaug_dir
|
| 654 |
+
self.fasta_file = args.fasta_file
|
| 655 |
+
self.protein_pdb_dir = args.protein_pdb_dir
|
| 656 |
+
self.pocket_pdbs_dir = args.pocket_pdbs_dir
|
| 657 |
+
self.jackhmmer_output_dir = args.jackhmmer_output_dir
|
| 658 |
+
self.database_fasta_path = args.database_fasta_path
|
| 659 |
+
self.max_extend_num = args.max_extend_num
|
| 660 |
+
self.database_pdb_dir = args.database_pdb_dir
|
| 661 |
+
self.TMscore_threshold = args.TMscore_threshold
|
| 662 |
+
self.Match_rate_threshold = args.Match_rate_threshold
|
| 663 |
+
self.n_thread = args.n_thread
|
| 664 |
+
|
| 665 |
+
def read_dataset_fasta(self):
|
| 666 |
+
protein_seq = {}
|
| 667 |
+
with open(self.fasta_file) as f:
|
| 668 |
+
fasta = f.readlines()
|
| 669 |
+
for i in range(0, len(fasta), 2):
|
| 670 |
+
id = fasta[i].strip()
|
| 671 |
+
id = id[1:5].upper()
|
| 672 |
+
seq = fasta[i + 1].strip()
|
| 673 |
+
protein_seq[id] = seq
|
| 674 |
+
return protein_seq
|
| 675 |
+
|
| 676 |
+
def create_dir(self):
|
| 677 |
+
# Create homoaug dir and subdirs
|
| 678 |
+
# Dir format
|
| 679 |
+
# homoaug_dir
|
| 680 |
+
# └── id
|
| 681 |
+
# ├── id.fasta
|
| 682 |
+
# └── id_protein.pdb
|
| 683 |
+
# └── id_pocket.pdb
|
| 684 |
+
|
| 685 |
+
protein_seq = self.read_dataset_fasta()
|
| 686 |
+
if not os.path.exists(self.homoaug_dir):
|
| 687 |
+
os.mkdir(self.homoaug_dir)
|
| 688 |
+
with open(self.id_file, "r") as f:
|
| 689 |
+
lines = f.readlines()
|
| 690 |
+
for line in tqdm(lines):
|
| 691 |
+
id = line.strip()
|
| 692 |
+
id = id[:4].upper()
|
| 693 |
+
if not os.path.exists(self.homoaug_dir + "/" + id):
|
| 694 |
+
os.mkdir(self.homoaug_dir + "/" + id)
|
| 695 |
+
|
| 696 |
+
# create fasta
|
| 697 |
+
with open(self.homoaug_dir + "/" + id + "/" + id + ".fasta", "w") as f:
|
| 698 |
+
f.write(">" + id + "\n" + protein_seq[id] + "\n")
|
| 699 |
+
|
| 700 |
+
# copy pdb
|
| 701 |
+
cif_file = glob.glob(self.protein_pdb_dir + "/" + id + "*")
|
| 702 |
+
if len(cif_file) != 1:
|
| 703 |
+
print("error : having more than 1 cif file", id)
|
| 704 |
+
continue
|
| 705 |
+
cif_file = cif_file[0]
|
| 706 |
+
# read cif
|
| 707 |
+
parser = Bio.PDB.MMCIFParser(QUIET=True)
|
| 708 |
+
structure = parser.get_structure(id, cif_file)
|
| 709 |
+
# get number of models
|
| 710 |
+
n_model = len(structure)
|
| 711 |
+
if n_model != 1:
|
| 712 |
+
print("error : having more than 1 model", id)
|
| 713 |
+
continue
|
| 714 |
+
# get number of chains
|
| 715 |
+
n_chain = len(list(structure.get_chains()))
|
| 716 |
+
if n_chain != 1:
|
| 717 |
+
print("error : having more than 1 chain", id)
|
| 718 |
+
continue
|
| 719 |
+
# save pdb
|
| 720 |
+
io = Bio.PDB.PDBIO()
|
| 721 |
+
io.set_structure(structure)
|
| 722 |
+
io.save(self.homoaug_dir + "/" + id + "/" + id + "_protein.pdb")
|
| 723 |
+
# os.system("cp "+homoaug_dir+"/"+id+"/"+id+"_protein.pdb "+homoaug_dir+"/"+id+"/"+id+"_pocket_chain.pdb")
|
| 724 |
+
|
| 725 |
+
# copy pocket
|
| 726 |
+
pocket_file = glob.glob(self.pocket_pdbs_dir + "/" + id + "*")
|
| 727 |
+
if len(pocket_file) != 1:
|
| 728 |
+
print("error : having more than 1 pocket file", id)
|
| 729 |
+
continue
|
| 730 |
+
pocket_file = pocket_file[0]
|
| 731 |
+
# copy to homoaug
|
| 732 |
+
os.system(
|
| 733 |
+
"cp "
|
| 734 |
+
+ pocket_file
|
| 735 |
+
+ " "
|
| 736 |
+
+ self.homoaug_dir
|
| 737 |
+
+ "/"
|
| 738 |
+
+ id
|
| 739 |
+
+ "/"
|
| 740 |
+
+ id
|
| 741 |
+
+ "_pocket.pdb"
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
def run(self):
|
| 745 |
+
self.create_dir()
|
| 746 |
+
|
| 747 |
+
# Run jackhmmer
|
| 748 |
+
print("# Start running jackhmmer")
|
| 749 |
+
jackhmmer_runner = JackhmmerRunner(
|
| 750 |
+
database_dir=self.database_fasta_path,
|
| 751 |
+
task_ids=self.id_file,
|
| 752 |
+
seq_dir=self.homoaug_dir,
|
| 753 |
+
output_dir=self.jackhmmer_output_dir,
|
| 754 |
+
n_thread=self.n_thread,
|
| 755 |
+
)
|
| 756 |
+
jackhmmer_runner.run_jackhmmer()
|
| 757 |
+
|
| 758 |
+
print("# Start running ligand pocket extractor")
|
| 759 |
+
ligand_pocket_extractor = LigandPocketExtractor(
|
| 760 |
+
self.id_file, self.homoaug_dir, self.n_thread
|
| 761 |
+
)
|
| 762 |
+
ligand_pocket_extractor.run()
|
| 763 |
+
|
| 764 |
+
print("# Start running pocket position extractor")
|
| 765 |
+
pocket_position_extractor = PocketPositionExtractor(
|
| 766 |
+
self.homoaug_dir, self.n_thread
|
| 767 |
+
)
|
| 768 |
+
pocket_position_extractor.run()
|
| 769 |
+
|
| 770 |
+
print("# Start running TMalign")
|
| 771 |
+
tmalign_runner = TMalignRunner(
|
| 772 |
+
self.max_extend_num,
|
| 773 |
+
self.homoaug_dir,
|
| 774 |
+
self.jackhmmer_output_dir,
|
| 775 |
+
self.database_pdb_dir,
|
| 776 |
+
self.TMscore_threshold,
|
| 777 |
+
self.Match_rate_threshold,
|
| 778 |
+
self.n_thread,
|
| 779 |
+
)
|
| 780 |
+
tmalign_runner.run()
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
if __name__ == "__main__":
|
| 784 |
+
parser = argparse.ArgumentParser()
|
| 785 |
+
parser.add_argument("--id_file", type=str, default="/drug/BioLip/tmp.id")
|
| 786 |
+
parser.add_argument("--homoaug_dir", type=str, default="/drug/BioLip/homoaug_new")
|
| 787 |
+
parser.add_argument(
|
| 788 |
+
"--fasta_file",
|
| 789 |
+
type=str,
|
| 790 |
+
default="/drug/BioLip/BioLiP_v2023-04-13_regularLigand.fasta",
|
| 791 |
+
)
|
| 792 |
+
parser.add_argument(
|
| 793 |
+
"--protein_pdb_dir", type=str, default="/drug/BioLip/protein_pdb"
|
| 794 |
+
)
|
| 795 |
+
parser.add_argument(
|
| 796 |
+
"--pocket_pdbs_dir", type=str, default="/drug/BioLip/pocket_pdb"
|
| 797 |
+
)
|
| 798 |
+
parser.add_argument(
|
| 799 |
+
"--jackhmmer_output_dir", type=str, default="/drug/BioLip/pdbbind_MSA_fasta"
|
| 800 |
+
)
|
| 801 |
+
parser.add_argument(
|
| 802 |
+
"--n_thread", type=int, default=10, help="number of threads for running"
|
| 803 |
+
)
|
| 804 |
+
parser.add_argument(
|
| 805 |
+
"--database_fasta_path",
|
| 806 |
+
type=str,
|
| 807 |
+
default="/data/protein/AF2DB/AFDB_HC_50.fa",
|
| 808 |
+
help="jackhmmer search database, in fasta format",
|
| 809 |
+
)
|
| 810 |
+
parser.add_argument(
|
| 811 |
+
"--database_pdb_dir",
|
| 812 |
+
type=str,
|
| 813 |
+
default="/drug/AFDB_HC_50_PDB",
|
| 814 |
+
help="homoaug search database, e.g. AF2DB",
|
| 815 |
+
)
|
| 816 |
+
parser.add_argument(
|
| 817 |
+
"--max_extend_num",
|
| 818 |
+
type=int,
|
| 819 |
+
default=20,
|
| 820 |
+
help="max number of extended pocket-ligand pairs for one real pocket-ligand pair",
|
| 821 |
+
)
|
| 822 |
+
parser.add_argument(
|
| 823 |
+
"--TMscore_threshold",
|
| 824 |
+
type=float,
|
| 825 |
+
default=0.4,
|
| 826 |
+
help="TMscore threshold for extending",
|
| 827 |
+
)
|
| 828 |
+
parser.add_argument(
|
| 829 |
+
"--Match_rate_threshold",
|
| 830 |
+
type=float,
|
| 831 |
+
default=0.4,
|
| 832 |
+
help="Match_rate threshold for extending",
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
args = parser.parse_args()
|
| 836 |
+
homoaug_runner = HomoAugRunner(args)
|
| 837 |
+
homoaug_runner.run()
|
| 838 |
+
print("HomoAug Done!")
|
data/HomoAug/utils/misc.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import os
|
| 3 |
+
import signal
|
| 4 |
+
import subprocess
|
| 5 |
+
import sys
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def time2str(time_used):
|
| 10 |
+
gaps = [
|
| 11 |
+
('days', 86400000),
|
| 12 |
+
('h', 3600000),
|
| 13 |
+
('min', 60000),
|
| 14 |
+
('s', 1000),
|
| 15 |
+
('ms', 1)
|
| 16 |
+
]
|
| 17 |
+
time_used *= 1000
|
| 18 |
+
time_str = []
|
| 19 |
+
for unit, gap in gaps:
|
| 20 |
+
val = time_used // gap
|
| 21 |
+
if val > 0:
|
| 22 |
+
time_str.append('{}{}'.format(int(val), unit))
|
| 23 |
+
time_used -= val * gap
|
| 24 |
+
if len(time_str) == 0:
|
| 25 |
+
time_str.append('0ms')
|
| 26 |
+
return ' '.join(time_str)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_date():
|
| 30 |
+
return time.strftime('%Y-%m-%d', time.localtime(time.time()))
|
| 31 |
+
|
| 32 |
+
def get_time(t=None):
|
| 33 |
+
if t is None:
|
| 34 |
+
t = time.time()
|
| 35 |
+
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def hash_seed(*items, width=32):
|
| 39 |
+
# width: range of seed: [0, 2**width)
|
| 40 |
+
sha = hashlib.sha256()
|
| 41 |
+
for item in items:
|
| 42 |
+
sha.update(str(item).encode('utf-8'))
|
| 43 |
+
return int(sha.hexdigest()[23:23+width//4], 16)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def execute(command, verbose=False, cmd_out_off=False):
|
| 47 |
+
if verbose:
|
| 48 |
+
print(command)
|
| 49 |
+
print()
|
| 50 |
+
if cmd_out_off:
|
| 51 |
+
popen = silent(subprocess.Popen)
|
| 52 |
+
else:
|
| 53 |
+
popen = subprocess.Popen
|
| 54 |
+
p = popen(command, shell=True)
|
| 55 |
+
try:
|
| 56 |
+
p.wait()
|
| 57 |
+
except KeyboardInterrupt:
|
| 58 |
+
try:
|
| 59 |
+
os.kill(p.pid, signal.SIGINT)
|
| 60 |
+
except OSError:
|
| 61 |
+
pass
|
| 62 |
+
p.wait()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def silent(func):
|
| 66 |
+
"""
|
| 67 |
+
Make function silent.
|
| 68 |
+
Useful for closing the output if you don't find a switch.
|
| 69 |
+
"""
|
| 70 |
+
def wrap_silent(*args, **kwargs):
|
| 71 |
+
fd = os.dup(1)
|
| 72 |
+
sys.stdout.flush()
|
| 73 |
+
os.close(1)
|
| 74 |
+
os.open(os.devnull, os.O_WRONLY)
|
| 75 |
+
|
| 76 |
+
res = func(*args, **kwargs)
|
| 77 |
+
|
| 78 |
+
os.close(1)
|
| 79 |
+
os.dup(fd)
|
| 80 |
+
os.close(fd)
|
| 81 |
+
|
| 82 |
+
return res
|
| 83 |
+
return wrap_silent
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def with_time(func, pretty_time=False):
|
| 87 |
+
"""
|
| 88 |
+
Usage:
|
| 89 |
+
|
| 90 |
+
1. as a function decorator
|
| 91 |
+
``` python
|
| 92 |
+
@with_time
|
| 93 |
+
def func(...):
|
| 94 |
+
...
|
| 95 |
+
result, cost_in_seconds = func(...)
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
2. directly apply
|
| 99 |
+
``` python
|
| 100 |
+
result, cost_in_seconds = with_time(func)(...)
|
| 101 |
+
```
|
| 102 |
+
"""
|
| 103 |
+
def wrap_time(*args, **kwargs):
|
| 104 |
+
start = time.time()
|
| 105 |
+
res = func(*args, **kwargs)
|
| 106 |
+
time_cost = time.time() - start
|
| 107 |
+
if pretty_time:
|
| 108 |
+
time_cost = time2str(time_cost)
|
| 109 |
+
return res, time_cost
|
| 110 |
+
return wrap_time
|
| 111 |
+
|
data/HomoAug/utils/ray_tools.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from asyncio import Event
|
| 2 |
+
from typing import Tuple
|
| 3 |
+
|
| 4 |
+
import ray
|
| 5 |
+
from ray.actor import ActorHandle
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def split_list(_list, n):
|
| 10 |
+
chunk_size = (len(_list) - 1) // n + 1
|
| 11 |
+
chunks = [_list[i * chunk_size : (i + 1) * chunk_size] for i in range(n)]
|
| 12 |
+
return chunks
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@ray.remote
|
| 16 |
+
class ProgressBarActor:
|
| 17 |
+
counter: int
|
| 18 |
+
delta: int
|
| 19 |
+
event: Event
|
| 20 |
+
|
| 21 |
+
def __init__(self) -> None:
|
| 22 |
+
self.counter = 0
|
| 23 |
+
self.delta = 0
|
| 24 |
+
self.event = Event()
|
| 25 |
+
|
| 26 |
+
def update(self, num_items_completed: int) -> None:
|
| 27 |
+
"""Updates the ProgressBar with the incremental
|
| 28 |
+
number of items that were just completed.
|
| 29 |
+
"""
|
| 30 |
+
self.counter += num_items_completed
|
| 31 |
+
self.delta += num_items_completed
|
| 32 |
+
self.event.set()
|
| 33 |
+
|
| 34 |
+
async def wait_for_update(self) -> Tuple[int, int]:
|
| 35 |
+
"""Blocking call.
|
| 36 |
+
|
| 37 |
+
Waits until somebody calls `update`, then returns a tuple of
|
| 38 |
+
the number of updates since the last call to
|
| 39 |
+
`wait_for_update`, and the total number of completed items.
|
| 40 |
+
"""
|
| 41 |
+
await self.event.wait()
|
| 42 |
+
self.event.clear()
|
| 43 |
+
saved_delta = self.delta
|
| 44 |
+
self.delta = 0
|
| 45 |
+
return saved_delta, self.counter
|
| 46 |
+
|
| 47 |
+
def get_counter(self) -> int:
|
| 48 |
+
"""
|
| 49 |
+
Returns the total number of complete items.
|
| 50 |
+
"""
|
| 51 |
+
return self.counter
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class ProgressBar:
|
| 55 |
+
progress_actor: ActorHandle
|
| 56 |
+
total: int
|
| 57 |
+
description: str
|
| 58 |
+
pbar: tqdm
|
| 59 |
+
|
| 60 |
+
def __init__(self, total: int, description: str = ""):
|
| 61 |
+
# Ray actors don't seem to play nice with mypy, generating
|
| 62 |
+
# a spurious warning for the following line,
|
| 63 |
+
# which we need to suppress. The code is fine.
|
| 64 |
+
self.progress_actor = ProgressBarActor.remote() # type: ignore
|
| 65 |
+
self.total = total
|
| 66 |
+
print("Total:", total)
|
| 67 |
+
self.description = description
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def actor(self) -> ActorHandle:
|
| 71 |
+
"""Returns a reference to the remote `ProgressBarActor`.
|
| 72 |
+
|
| 73 |
+
When you complete tasks, call `update` on the actor.
|
| 74 |
+
"""
|
| 75 |
+
return self.progress_actor
|
| 76 |
+
|
| 77 |
+
def print_until_done(self) -> None:
|
| 78 |
+
"""Blocking call.
|
| 79 |
+
|
| 80 |
+
Do this after starting a series of remote Ray tasks, to which you've
|
| 81 |
+
passed the actor handle. Each of them calls `update` on the actor.
|
| 82 |
+
When the progress meter reaches 100%, this method returns.
|
| 83 |
+
"""
|
| 84 |
+
pbar = tqdm(desc=self.description, total=self.total, ncols=80)
|
| 85 |
+
while True:
|
| 86 |
+
delta, counter = ray.get(self.actor.wait_for_update.remote())
|
| 87 |
+
pbar.update(delta)
|
| 88 |
+
if counter >= self.total:
|
| 89 |
+
pbar.close()
|
| 90 |
+
return
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2022 DP Technology
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<div align="center">
|
| 2 |
+
<img src="docs/logo.png" alt="BindCLIP logo" width="500">
|
| 3 |
+
<h2>
|
| 4 |
+
A Unified Contrastive–Generative Representation Learning Framework<br>
|
| 5 |
+
for Virtual Screening
|
| 6 |
+
</h2>
|
| 7 |
+
</div>
|
| 8 |
+
|
| 9 |
+
<p align="center">
|
| 10 |
+
Official implementation of BindCLIP (<strong>KDD 2026 Oral</strong>)
|
| 11 |
+
</p>
|
| 12 |
+
|
| 13 |
+
<p align="center">
|
| 14 |
+
<a href="https://dl.acm.org/doi/10.1145/3770855.3819040">📄 Paper</a> •
|
| 15 |
+
<a href="./LICENSE">📜 License</a>
|
| 16 |
+
</p>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
<p align="center">
|
| 20 |
+
<img src="docs/framework.jpg" alt="BindCLIP framework" width="950">
|
| 21 |
+
</p>
|
| 22 |
+
|
| 23 |
+
# Requirements
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
conda create -n bindclip python=3.10
|
| 27 |
+
conda activate bindclip
|
| 28 |
+
conda install pytorch=2.0 pytorch-cuda=11.8 -c pytorch -c nvidia
|
| 29 |
+
# Verify PyTorch and CUDA installation
|
| 30 |
+
# python -c "import torch; print(torch.__version__); print(torch.version.cuda)"
|
| 31 |
+
|
| 32 |
+
conda install pyg=2.3.1 -c pyg
|
| 33 |
+
conda install "rdkit=2022.09.5" openbabel tensorboard pyyaml easydict python-lmdb -c conda-forge
|
| 34 |
+
# [IMPORTANT]: RDKit 2022.09.5 is required.
|
| 35 |
+
# Using a different version may require reprocessing the training data.
|
| 36 |
+
|
| 37 |
+
# Install Uni-Core
|
| 38 |
+
cd Uni-Core-main
|
| 39 |
+
python setup.py install
|
| 40 |
+
|
| 41 |
+
# Additional dependencies
|
| 42 |
+
pip install tokenizers==0.13.3
|
| 43 |
+
pip install ml-collections tensorboardX wandb
|
| 44 |
+
pip install ipython
|
| 45 |
+
pip install torch-scatter -f https://data.pyg.org/whl/torch-2.0.0+cu118.html
|
| 46 |
+
pip install torch-sparse -f https://data.pyg.org/whl/torch-2.0.1+cu118.html
|
| 47 |
+
pip install torch-cluster -f https://data.pyg.org/whl/torch-2.0.1+cu118.html
|
| 48 |
+
conda install biopandas
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
# Data
|
| 52 |
+
|
| 53 |
+
## Training Data
|
| 54 |
+
|
| 55 |
+
We release the training data used in BindCLIP, together with the external molecular library used for negative augmentation:
|
| 56 |
+
|
| 57 |
+
https://drive.google.com/drive/folders/1F48zwXEtmAgwGGuKCXOMFR21U8fxEAJh?usp=sharing
|
| 58 |
+
|
| 59 |
+
The released training data contains two versions corresponding to the hard-negative construction strategies described in the paper:
|
| 60 |
+
|
| 61 |
+
- Random Sampling
|
| 62 |
+
- UniMol Retrieval
|
| 63 |
+
|
| 64 |
+
**NOTE:** We use the same training/validation split as DrugCLIP. The only difference is that we additionally provide a binding pose and a negative molecule for each pair.
|
| 65 |
+
|
| 66 |
+
## Evaluation Data
|
| 67 |
+
|
| 68 |
+
We follow the DrugCLIP evaluation setup for virtual screening benchmarks, including: LIT-PCBA and DUD-E
|
| 69 |
+
|
| 70 |
+
The processed benchmark data can be downloaded from:
|
| 71 |
+
|
| 72 |
+
https://drive.google.com/drive/folders/1zW1MGpgunynFxTKXC2Q4RgWxZmg6CInV?usp=sharing
|
| 73 |
+
|
| 74 |
+
# Checkpoints
|
| 75 |
+
|
| 76 |
+
We release two pretrained checkpoints:
|
| 77 |
+
|
| 78 |
+
https://drive.google.com/drive/folders/1KKID5DU_hh2e5sE5Xmem10lfSy_qWwIE?usp=sharing
|
| 79 |
+
|
| 80 |
+
The released checkpoints correspond to two different negative sampling strategies used during training:
|
| 81 |
+
|
| 82 |
+
- Random Negative Augmentation
|
| 83 |
+
- Hard Negative Augmentation
|
| 84 |
+
|
| 85 |
+
We provide both versions because we observed that the random-negative model can sometimes exhibit competitive or even better generalization performance depending on the downstream application. We encourage users to evaluate both checkpoints and choose the one that works best for their specific use case.
|
| 86 |
+
|
| 87 |
+
**NOTE: Our checkpoints are fully compatible with the DrugCLIP inference code. Users can directly replace the DrugCLIP checkpoint with a BindCLIP checkpoint without any code modifications.**
|
| 88 |
+
|
| 89 |
+
# Train
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
bash bindclip.sh
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
# Test
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
bash test.sh
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
# Retrieval
|
| 102 |
+
|
| 103 |
+
```bash
|
| 104 |
+
bash retrieval.sh
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
Example files (`pocket.lmdb` and `mols.lmdb`) can be found in the DrugCLIP Google Drive folder under the `retrieval/` directory.
|
| 108 |
+
|
| 109 |
+
# Citation
|
| 110 |
+
|
| 111 |
+
If you find this work useful, please consider citing:
|
| 112 |
+
|
| 113 |
+
```bibtex
|
| 114 |
+
@inproceedings{qiao2026bindclip,
|
| 115 |
+
title={BindCLIP: A Unified Contrastive-Generative Representation Learning Framework for Virtual Screening},
|
| 116 |
+
author={Qiao, Anjie and Wang, Zhen and Li, Yaliang and Rao, Jiahua and Yang, Yuedong},
|
| 117 |
+
year={2026},
|
| 118 |
+
booktitle = {Proceedings of the 32nd ACM SIGKDD Conference on Knowledge Discovery and Data Mining V.2},
|
| 119 |
+
pages = {11854–11865},
|
| 120 |
+
numpages = {12}
|
| 121 |
+
}
|
| 122 |
+
```
|
data/bindclip.sh
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
data_path="data/train_no_test_af"
|
| 4 |
+
|
| 5 |
+
param_dir="hingeloss_lmdba1.5_seed42"
|
| 6 |
+
save_dir="ckpt/savedir${param_dir}"
|
| 7 |
+
|
| 8 |
+
tmp_save_dir="ckpt/tmp/tmp_save_dir${param_dir}"
|
| 9 |
+
tsb_dir="ckpt/tsb/tsb_dir${param_dir}"
|
| 10 |
+
|
| 11 |
+
n_gpu=1
|
| 12 |
+
MASTER_PORT=10055
|
| 13 |
+
finetune_mol_model="unimol/ckp/mol_pre_no_h_220816.pt" # unimol pretrained mol model
|
| 14 |
+
finetune_pocket_model="unimol/ckp/pocket_pre_220816.pt" # unimol pretrained pocket model
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
batch_size=48
|
| 18 |
+
batch_size_valid=64
|
| 19 |
+
epoch=200
|
| 20 |
+
dropout=0.0
|
| 21 |
+
warmup=0.06
|
| 22 |
+
update_freq=4
|
| 23 |
+
dist_threshold=8.0
|
| 24 |
+
recycling=3
|
| 25 |
+
lr=1e-3
|
| 26 |
+
|
| 27 |
+
export NCCL_ASYNC_ERROR_HANDLING=1
|
| 28 |
+
export OMP_NUM_THREADS=1
|
| 29 |
+
CUDA_VISIBLE_DEVICES="0" $(which unicore-train) $data_path --user-dir ./unimol --train-subset train --valid-subset valid \
|
| 30 |
+
--num-workers 0 --ddp-backend=c10d \
|
| 31 |
+
--task drugclip --loss in_batch_softmax_hinge --arch drugclip \
|
| 32 |
+
--max-pocket-atoms 256 \
|
| 33 |
+
--optimizer adam --adam-betas "(0.9, 0.999)" --adam-eps 1e-8 --clip-norm 1.0 \
|
| 34 |
+
--lr-scheduler polynomial_decay --lr $lr --warmup-ratio $warmup --max-epoch $epoch --batch-size $batch_size --batch-size-valid $batch_size_valid \
|
| 35 |
+
--fp16 --fp16-init-scale 4 --fp16-scale-window 256 --update-freq $update_freq --seed 42 \
|
| 36 |
+
--tensorboard-logdir $tsb_dir \
|
| 37 |
+
--log-interval 100 --log-format simple \
|
| 38 |
+
--validate-interval 1 \
|
| 39 |
+
--best-checkpoint-metric valid_bedroc --patience 2000 --all-gather-list-size 2048000 \
|
| 40 |
+
--save-dir $save_dir --tmp-save-dir $tmp_save_dir --keep-last-epochs 5 \
|
| 41 |
+
--find-unused-parameters \
|
| 42 |
+
--maximize-best-checkpoint-metric \
|
| 43 |
+
--finetune-pocket-model $finetune_pocket_model \
|
| 44 |
+
--finetune-mol-model $finetune_mol_model \
|
data/docs/framework.jpg
ADDED
|
Git LFS Details
|
data/docs/logo.png
ADDED
|
Git LFS Details
|
data/encode_ligand_atom.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
results_path="./test" # replace to your results path
|
| 2 |
+
batch_size=8
|
| 3 |
+
weight_path="ckpt/savedirrandom_zinc/checkpoint_best_seed-1.pt"
|
| 4 |
+
SAVE_DIR="./motivation_analysis_1/sampled_subset/" # path to the cached mol embedding file
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES="0" python ./unimol/encode_ligand_atom.py --user-dir ./unimol $data_path "./data" --valid-subset test \
|
| 7 |
+
--results-path $results_path \
|
| 8 |
+
--num-workers 8 --ddp-backend=c10d --batch-size $batch_size \
|
| 9 |
+
--task drugclip --loss in_batch_softmax --arch drugclip \
|
| 10 |
+
--max-pocket-atoms 256 \
|
| 11 |
+
--fp16 --fp16-init-scale 4 --fp16-scale-window 256 --seed 1 \
|
| 12 |
+
--path $weight_path \
|
| 13 |
+
--log-interval 100 --log-format simple \
|
| 14 |
+
--save-dir $SAVE_DIR \
|
data/py_scripts/lmdb_utils.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
import lmdb
|
| 4 |
+
from tqdm import tqdm, trange
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def read_lmdb(lmdb_path):
|
| 13 |
+
env = lmdb.open(
|
| 14 |
+
lmdb_path,
|
| 15 |
+
subdir=False,
|
| 16 |
+
readonly=True,
|
| 17 |
+
lock=False,
|
| 18 |
+
readahead=False,
|
| 19 |
+
meminit=False,
|
| 20 |
+
max_readers=256,
|
| 21 |
+
)
|
| 22 |
+
txn = env.begin()
|
| 23 |
+
keys = list(txn.cursor().iternext(values=False))
|
| 24 |
+
out_list = []
|
| 25 |
+
for idx in tqdm(keys):
|
| 26 |
+
datapoint_pickled = txn.get(idx)
|
| 27 |
+
data = pickle.loads(datapoint_pickled)
|
| 28 |
+
out_list.append(data)
|
| 29 |
+
#print(len(data["coordinates"]))
|
| 30 |
+
env.close()
|
| 31 |
+
return out_list
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def write_lmdb(out_list, save_path):
|
| 36 |
+
|
| 37 |
+
env = lmdb.open(
|
| 38 |
+
save_path,
|
| 39 |
+
subdir=False,
|
| 40 |
+
lock=False,
|
| 41 |
+
readahead=False,
|
| 42 |
+
meminit=False,
|
| 43 |
+
max_readers=64,
|
| 44 |
+
map_size=1099511627776
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
with env.begin(write=True) as lmdb_txn:
|
| 48 |
+
for i in tqdm(range(len(out_list))):
|
| 49 |
+
lmdb_txn.put(str(i).encode('ascii'), pickle.dumps(out_list[i]))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
# Example usage
|
| 55 |
+
# Read LMDB
|
| 56 |
+
lmdb_path = "/HOME/nsccgz_ywang/nsccgz_ywang_wzh/HDD_POOL/qiaoaj/DrugCLIP/data/train_no_test_af/train.lmdb"
|
| 57 |
+
data = read_lmdb(lmdb_path)
|
| 58 |
+
print(len(data))
|
| 59 |
+
print(data[0].keys())
|
| 60 |
+
#print(len(data[1]["coordinates"]))
|
| 61 |
+
|
| 62 |
+
dic = {
|
| 63 |
+
"atoms": "atom types for each atom in the ligand",
|
| 64 |
+
"coordinates": "3D coordinates for each atom in the ligand generated by RDKit. Max number of conformations is 10",
|
| 65 |
+
"pocket_atoms": "atom types for each atom in the pocket",
|
| 66 |
+
"pocket_coordinates": "3D coordinates for each atom in the pocket",
|
| 67 |
+
"mol": "RDKit molecule object for the ligand",
|
| 68 |
+
"smi": "SMILES string for the ligand",
|
| 69 |
+
"pocket": "pdbid of the pocket",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
|
data/py_scripts/write_data_with_docked.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import gzip
|
| 3 |
+
import multiprocessing as mp
|
| 4 |
+
import os
|
| 5 |
+
import pickle
|
| 6 |
+
import random
|
| 7 |
+
|
| 8 |
+
import lmdb
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import rdkit
|
| 12 |
+
import rdkit.Chem.AllChem as AllChem
|
| 13 |
+
import torch
|
| 14 |
+
import tqdm
|
| 15 |
+
from biopandas.mol2 import PandasMol2
|
| 16 |
+
from biopandas.pdb import PandasPdb
|
| 17 |
+
from rdkit import Chem, RDLogger
|
| 18 |
+
from rdkit.Chem.MolStandardize import rdMolStandardize
|
| 19 |
+
|
| 20 |
+
RDLogger.DisableLog('rdApp.*')
|
| 21 |
+
|
| 22 |
+
parser = argparse.ArgumentParser()
|
| 23 |
+
parser.add_argument('--mol_data_path', type=str, default='/data/protein/DUD-E/raw/all')
|
| 24 |
+
parser.add_argument('--lmdb_path', type=str, default='docked_dude_fromweb2D.lmdb')
|
| 25 |
+
args = parser.parse_args()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def gen_conformation(mol, num_conf=20, num_worker=8):
|
| 29 |
+
try:
|
| 30 |
+
mol = Chem.AddHs(mol)
|
| 31 |
+
AllChem.EmbedMultipleConfs(mol, numConfs=num_conf, numThreads=num_worker, pruneRmsThresh=1, maxAttempts=10000, useRandomCoords=False)
|
| 32 |
+
try:
|
| 33 |
+
AllChem.MMFFOptimizeMoleculeConfs(mol, numThreads=num_worker)
|
| 34 |
+
except:
|
| 35 |
+
pass
|
| 36 |
+
mol = Chem.RemoveHs(mol)
|
| 37 |
+
except:
|
| 38 |
+
print("cannot gen conf", Chem.MolToSmiles(mol))
|
| 39 |
+
return None
|
| 40 |
+
if mol.GetNumConformers() == 0:
|
| 41 |
+
print("cannot gen conf", Chem.MolToSmiles(mol))
|
| 42 |
+
return None
|
| 43 |
+
return mol
|
| 44 |
+
|
| 45 |
+
def convert_2Dmol_to_data(mol, num_conf=10, num_worker=5):
|
| 46 |
+
#to 3D
|
| 47 |
+
mol = gen_conformation(mol, num_conf, num_worker)
|
| 48 |
+
if mol is None:
|
| 49 |
+
return None
|
| 50 |
+
coords = [np.array(mol.GetConformer(i).GetPositions()) for i in range(mol.GetNumConformers())]
|
| 51 |
+
atom_types = [a.GetSymbol() for a in mol.GetAtoms()]
|
| 52 |
+
return {'coords': coords, 'atom_types': atom_types, 'smi': Chem.MolToSmiles(mol), 'mol': mol}
|
| 53 |
+
|
| 54 |
+
def convert_3Dmol_to_data(mol):
|
| 55 |
+
|
| 56 |
+
if mol is None:
|
| 57 |
+
return None
|
| 58 |
+
coords = [np.array(mol.GetConformer(i).GetPositions()) for i in range(mol.GetNumConformers())]
|
| 59 |
+
atom_types = [a.GetSymbol() for a in mol.GetAtoms()]
|
| 60 |
+
return {'coords': coords, 'atom_types': atom_types, 'smi': Chem.MolToSmiles(mol), 'mol': mol}
|
| 61 |
+
|
| 62 |
+
def read_pdb(path):
|
| 63 |
+
pdb_df = PandasPdb().read_pdb(path)
|
| 64 |
+
|
| 65 |
+
coord = pdb_df.df['ATOM'][['x_coord', 'y_coord', 'z_coord']]
|
| 66 |
+
atom_type = pdb_df.df['ATOM']['atom_name']
|
| 67 |
+
residue_name = pdb_df.df['ATOM']['chain_id'] + pdb_df.df['ATOM']['residue_number'].astype(str)
|
| 68 |
+
residue_type = pdb_df.df['ATOM']['residue_name']
|
| 69 |
+
protein = {'coord': np.array(coord),
|
| 70 |
+
'atom_type': list(atom_type),
|
| 71 |
+
'residue_name': list(residue_name),
|
| 72 |
+
'residue_type': list(residue_type)}
|
| 73 |
+
return protein
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def read_sdf_gz_3d(path):
|
| 77 |
+
inf = gzip.open(path)
|
| 78 |
+
with Chem.ForwardSDMolSupplier(inf, removeHs=False, sanitize=False) as gzsuppl:
|
| 79 |
+
ms = [add_charges(x) for x in gzsuppl if x is not None]
|
| 80 |
+
ms = [rdMolStandardize.Uncharger().uncharge(Chem.RemoveHs(m)) for m in ms if m is not None]
|
| 81 |
+
return ms
|
| 82 |
+
|
| 83 |
+
def add_charges(m):
|
| 84 |
+
m.UpdatePropertyCache(strict=False)
|
| 85 |
+
ps = Chem.DetectChemistryProblems(m)
|
| 86 |
+
if not ps:
|
| 87 |
+
Chem.SanitizeMol(m)
|
| 88 |
+
return m
|
| 89 |
+
for p in ps:
|
| 90 |
+
if p.GetType()=='AtomValenceException':
|
| 91 |
+
at = m.GetAtomWithIdx(p.GetAtomIdx())
|
| 92 |
+
if at.GetAtomicNum()==7 and at.GetFormalCharge()==0 and at.GetExplicitValence()==4:
|
| 93 |
+
at.SetFormalCharge(1)
|
| 94 |
+
if at.GetAtomicNum()==6 and at.GetExplicitValence()==5:
|
| 95 |
+
#remove a bond
|
| 96 |
+
for b in at.GetBonds():
|
| 97 |
+
if b.GetBondType()==Chem.rdchem.BondType.DOUBLE:
|
| 98 |
+
b.SetBondType(Chem.rdchem.BondType.SINGLE)
|
| 99 |
+
break
|
| 100 |
+
if at.GetAtomicNum()==8 and at.GetFormalCharge()==0 and at.GetExplicitValence()==3:
|
| 101 |
+
at.SetFormalCharge(1)
|
| 102 |
+
if at.GetAtomicNum()==5 and at.GetFormalCharge()==0 and at.GetExplicitValence()==4:
|
| 103 |
+
at.SetFormalCharge(-1)
|
| 104 |
+
try:
|
| 105 |
+
Chem.SanitizeMol(m)
|
| 106 |
+
except:
|
| 107 |
+
return None
|
| 108 |
+
return m
|
| 109 |
+
|
| 110 |
+
def get_different_raid(protein, ligand, raid=6):
|
| 111 |
+
protein_coord = protein['coord']
|
| 112 |
+
ligand_coord = ligand['coord']
|
| 113 |
+
protein_residue_name = protein['residue_name']
|
| 114 |
+
pocket_residue = set()
|
| 115 |
+
for i in range(len(protein_coord)):
|
| 116 |
+
for j in range(len(ligand_coord)):
|
| 117 |
+
if np.linalg.norm(protein_coord[i] - ligand_coord[j]) < raid:
|
| 118 |
+
pocket_residue.add(protein_residue_name[i])
|
| 119 |
+
return pocket_residue
|
| 120 |
+
|
| 121 |
+
def read_mol2_ligand(path):
|
| 122 |
+
mol2_df = PandasMol2().read_mol2(path)
|
| 123 |
+
coord = mol2_df.df[['x', 'y', 'z']]
|
| 124 |
+
atom_type = mol2_df.df['atom_name']
|
| 125 |
+
ligand = {'coord': np.array(coord), 'atom_type': list(atom_type), 'mol': Chem.MolFromMol2File(path)}
|
| 126 |
+
return ligand
|
| 127 |
+
|
| 128 |
+
def read_smi_mol(path):
|
| 129 |
+
with open(path, 'r') as f:
|
| 130 |
+
mols_lines = list(f.readlines())
|
| 131 |
+
smis = [l.split(' ')[0] for l in mols_lines]
|
| 132 |
+
mols = [Chem.MolFromSmiles(m) for m in smis]
|
| 133 |
+
return mols
|
| 134 |
+
|
| 135 |
+
def parser(protein_path, mol_path, ligand_path, activity, pocket_index, raid=6):
|
| 136 |
+
protein = read_pdb(protein_path)
|
| 137 |
+
data_mols = read_smi_mol(mol_path)
|
| 138 |
+
|
| 139 |
+
ligand = read_mol2_ligand(ligand_path)
|
| 140 |
+
pocket_residue = get_different_raid(protein, ligand, raid=raid)
|
| 141 |
+
pocket_atom_idx = [i for i, r in enumerate(protein['residue_name']) if r in pocket_residue]
|
| 142 |
+
pocket_atom_type = [protein['atom_type'][i] for i in pocket_atom_idx]
|
| 143 |
+
pocket_coord = [protein['coord'][i] for i in pocket_atom_idx]
|
| 144 |
+
pocket_residue_type = [protein['residue_type'][i] for i in pocket_atom_idx]
|
| 145 |
+
pocket_name = protein_path.split('/')[-2]
|
| 146 |
+
pool = mp.Pool(32)
|
| 147 |
+
#mols = [convert_2Dmol_to_data(m) for m in data_mols if m is not None]
|
| 148 |
+
data_mols = [m for m in data_mols if m is not None]
|
| 149 |
+
mols = [m for m in tqdm.tqdm(pool.imap_unordered(convert_2Dmol_to_data, data_mols))]
|
| 150 |
+
mols = [m for m in mols if m is not None]
|
| 151 |
+
|
| 152 |
+
return [{'atoms': m['atom_types'],
|
| 153 |
+
'coordinates': m['coords'],
|
| 154 |
+
'smi': m['smi'],
|
| 155 |
+
'mol': ligand,
|
| 156 |
+
'pocket_name': pocket_name,
|
| 157 |
+
'pocket_index': pocket_index,
|
| 158 |
+
'activity': activity,
|
| 159 |
+
"pocket_atom_type": pocket_atom_type,
|
| 160 |
+
"pocket_coord": pocket_coord} for m in mols]
|
| 161 |
+
|
| 162 |
+
def mol_parser(mol_path, ligand_path, label):
|
| 163 |
+
data_mols = read_smi_mol(mol_path)
|
| 164 |
+
data_mols = [m for m in data_mols if m is not None]
|
| 165 |
+
ligand = read_mol2_ligand(ligand_path)
|
| 166 |
+
pool = mp.Pool(32)
|
| 167 |
+
mols = [m for m in tqdm.tqdm(pool.imap_unordered(convert_2Dmol_to_data, data_mols))]
|
| 168 |
+
mols = [m for m in mols if m is not None]
|
| 169 |
+
return [{'atoms': m['atom_types'],
|
| 170 |
+
'coordinates': m['coords'],
|
| 171 |
+
'smi': m['smi'],
|
| 172 |
+
'mol': m['mol'],
|
| 173 |
+
'label': label
|
| 174 |
+
} for m in mols]
|
| 175 |
+
|
| 176 |
+
def pocket_parser(protein_path, ligand_path, pocket_index, raid=6):
|
| 177 |
+
protein = read_pdb(protein_path)
|
| 178 |
+
ligand = read_mol2_ligand(ligand_path)
|
| 179 |
+
pocket_residue = get_different_raid(protein, ligand, raid=raid)
|
| 180 |
+
pocket_atom_idx = [i for i, r in enumerate(protein['residue_name']) if r in pocket_residue]
|
| 181 |
+
pocket_atom_type = [protein['atom_type'][i] for i in pocket_atom_idx]
|
| 182 |
+
pocket_coord = [protein['coord'][i] for i in pocket_atom_idx]
|
| 183 |
+
pocket_residue_type = [protein['residue_type'][i] for i in pocket_atom_idx]
|
| 184 |
+
pocket_name = protein_path.split('/')[-2]
|
| 185 |
+
return {'pocket': pocket_name,
|
| 186 |
+
'pocket_index': pocket_index,
|
| 187 |
+
"pocket_atoms": pocket_atom_type,
|
| 188 |
+
"pocket_coordinates": pocket_coord}
|
| 189 |
+
|
| 190 |
+
def write_lmdb(data, lmdb_path):
|
| 191 |
+
#resume
|
| 192 |
+
|
| 193 |
+
env = lmdb.open(lmdb_path, subdir=False, readonly=False, lock=False, readahead=False, meminit=False, map_size=1099511627776)
|
| 194 |
+
num = 0
|
| 195 |
+
with env.begin(write=True) as txn:
|
| 196 |
+
for d in data:
|
| 197 |
+
txn.put(str(num).encode('ascii'), pickle.dumps(d))
|
| 198 |
+
num += 1
|
| 199 |
+
|
| 200 |
+
if __name__ == '__main__':
|
| 201 |
+
protein_path = [os.path.join(args.mol_data_path, x, 'receptor.pdb') for x in os.listdir(args.mol_data_path)]
|
| 202 |
+
act_mol_path = [os.path.join(args.mol_data_path, x, 'actives_final.ism') for x in os.listdir(args.mol_data_path)]
|
| 203 |
+
decoy_mol_path = [os.path.join(args.mol_data_path, x, 'decoys_final.ism') for x in os.listdir(args.mol_data_path)]
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
for i, pocket in tqdm.tqdm(enumerate(protein_path)):
|
| 208 |
+
# acive mols
|
| 209 |
+
print(i, pocket)
|
| 210 |
+
data = []
|
| 211 |
+
d_active = (mol_parser(act_mol_path[i], pocket.replace('receptor.pdb', 'crystal_ligand.mol2'), 1))
|
| 212 |
+
|
| 213 |
+
data.extend(d_active)
|
| 214 |
+
|
| 215 |
+
# decoy mols
|
| 216 |
+
d_decoy = (mol_parser(decoy_mol_path[i], pocket.replace('receptor.pdb', 'crystal_ligand.mol2'), 0))
|
| 217 |
+
|
| 218 |
+
data.extend(d_decoy)
|
| 219 |
+
|
| 220 |
+
write_lmdb(data, pocket.replace('receptor.pdb', 'mols.lmdb'))
|
| 221 |
+
|
| 222 |
+
# write pocket
|
| 223 |
+
d = pocket_parser(pocket, pocket.replace('receptor.pdb', 'crystal_ligand.mol2'), i)
|
| 224 |
+
write_lmdb([d], pocket.replace('receptor.pdb', 'pocket.lmdb'))
|
| 225 |
+
|
| 226 |
+
# number of lines in actives_final.smi
|
| 227 |
+
with open(act_mol_path[i], 'r') as f:
|
| 228 |
+
mols_lines = list(f.readlines())
|
| 229 |
+
print("active", len(d_active), len(mols_lines))
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
with open(decoy_mol_path[i], 'r') as f:
|
| 234 |
+
mols_lines = list(f.readlines())
|
| 235 |
+
print("decoy", len(d_decoy), len(mols_lines))
|
| 236 |
+
|
| 237 |
+
|
data/py_scripts/write_dude_multi.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import gzip
|
| 3 |
+
import multiprocessing as mp
|
| 4 |
+
import os
|
| 5 |
+
import pickle
|
| 6 |
+
import random
|
| 7 |
+
|
| 8 |
+
import lmdb
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import rdkit
|
| 12 |
+
import rdkit.Chem.AllChem as AllChem
|
| 13 |
+
import torch
|
| 14 |
+
import tqdm
|
| 15 |
+
from biopandas.mol2 import PandasMol2
|
| 16 |
+
from biopandas.pdb import PandasPdb
|
| 17 |
+
from rdkit import Chem, RDLogger
|
| 18 |
+
from rdkit.Chem.MolStandardize import rdMolStandardize
|
| 19 |
+
|
| 20 |
+
RDLogger.DisableLog('rdApp.*')
|
| 21 |
+
|
| 22 |
+
parser = argparse.ArgumentParser()
|
| 23 |
+
parser.add_argument('--mol_data_path', type=str, default='/HOME/nsccgz_ywang/nsccgz_ywang_wzh/HDD_POOL/qiaoaj/DrugCLIP-Assamble/motivation_analysis_6/data')
|
| 24 |
+
parser.add_argument('--lmdb_path', type=str, default='/HOME/nsccgz_ywang/nsccgz_ywang_wzh/HDD_POOL/qiaoaj/DrugCLIP-Assamble/motivation_analysis_6/data/ood_case.lmdb')
|
| 25 |
+
args = parser.parse_args()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def gen_conformation(mol, num_conf=20, num_worker=8):
|
| 29 |
+
try:
|
| 30 |
+
mol = Chem.AddHs(mol)
|
| 31 |
+
AllChem.EmbedMultipleConfs(mol, numConfs=num_conf, numThreads=num_worker, pruneRmsThresh=1, maxAttempts=10000, useRandomCoords=False)
|
| 32 |
+
try:
|
| 33 |
+
AllChem.MMFFOptimizeMoleculeConfs(mol, numThreads=num_worker)
|
| 34 |
+
except:
|
| 35 |
+
pass
|
| 36 |
+
mol = Chem.RemoveHs(mol)
|
| 37 |
+
except:
|
| 38 |
+
print("cannot gen conf", Chem.MolToSmiles(mol))
|
| 39 |
+
return None
|
| 40 |
+
if mol.GetNumConformers() == 0:
|
| 41 |
+
print("cannot gen conf", Chem.MolToSmiles(mol))
|
| 42 |
+
return None
|
| 43 |
+
return mol
|
| 44 |
+
|
| 45 |
+
def convert_2Dmol_to_data(mol, num_conf=5, num_worker=5):
|
| 46 |
+
#to 3D
|
| 47 |
+
mol = gen_conformation(mol, num_conf, num_worker)
|
| 48 |
+
if mol is None:
|
| 49 |
+
return None
|
| 50 |
+
coords = [np.array(mol.GetConformer(i).GetPositions()) for i in range(mol.GetNumConformers())]
|
| 51 |
+
atom_types = [a.GetSymbol() for a in mol.GetAtoms()]
|
| 52 |
+
return {'coords': coords, 'atom_types': atom_types, 'smi': Chem.MolToSmiles(mol), 'mol': mol}
|
| 53 |
+
|
| 54 |
+
def convert_3Dmol_to_data(mol):
|
| 55 |
+
|
| 56 |
+
if mol is None:
|
| 57 |
+
return None
|
| 58 |
+
coords = [np.array(mol.GetConformer(i).GetPositions()) for i in range(mol.GetNumConformers())]
|
| 59 |
+
atom_types = [a.GetSymbol() for a in mol.GetAtoms()]
|
| 60 |
+
return {'coords': coords, 'atom_types': atom_types, 'smi': Chem.MolToSmiles(mol), 'mol': mol}
|
| 61 |
+
|
| 62 |
+
def read_pdb(path):
|
| 63 |
+
pdb_df = PandasPdb().read_pdb(path)
|
| 64 |
+
|
| 65 |
+
coord = pdb_df.df['ATOM'][['x_coord', 'y_coord', 'z_coord']]
|
| 66 |
+
atom_type = pdb_df.df['ATOM']['atom_name']
|
| 67 |
+
residue_name = pdb_df.df['ATOM']['chain_id'] + pdb_df.df['ATOM']['residue_number'].astype(str)
|
| 68 |
+
residue_type = pdb_df.df['ATOM']['residue_name']
|
| 69 |
+
protein = {'coord': np.array(coord),
|
| 70 |
+
'atom_type': list(atom_type),
|
| 71 |
+
'residue_name': list(residue_name),
|
| 72 |
+
'residue_type': list(residue_type)}
|
| 73 |
+
return protein
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def read_sdf_gz_3d(path):
|
| 77 |
+
inf = gzip.open(path)
|
| 78 |
+
with Chem.ForwardSDMolSupplier(inf, removeHs=False, sanitize=False) as gzsuppl:
|
| 79 |
+
ms = [add_charges(x) for x in gzsuppl if x is not None]
|
| 80 |
+
ms = [rdMolStandardize.Uncharger().uncharge(Chem.RemoveHs(m)) for m in ms if m is not None]
|
| 81 |
+
return ms
|
| 82 |
+
|
| 83 |
+
def add_charges(m):
|
| 84 |
+
m.UpdatePropertyCache(strict=False)
|
| 85 |
+
ps = Chem.DetectChemistryProblems(m)
|
| 86 |
+
if not ps:
|
| 87 |
+
Chem.SanitizeMol(m)
|
| 88 |
+
return m
|
| 89 |
+
for p in ps:
|
| 90 |
+
if p.GetType()=='AtomValenceException':
|
| 91 |
+
at = m.GetAtomWithIdx(p.GetAtomIdx())
|
| 92 |
+
if at.GetAtomicNum()==7 and at.GetFormalCharge()==0 and at.GetExplicitValence()==4:
|
| 93 |
+
at.SetFormalCharge(1)
|
| 94 |
+
if at.GetAtomicNum()==6 and at.GetExplicitValence()==5:
|
| 95 |
+
#remove a bond
|
| 96 |
+
for b in at.GetBonds():
|
| 97 |
+
if b.GetBondType()==Chem.rdchem.BondType.DOUBLE:
|
| 98 |
+
b.SetBondType(Chem.rdchem.BondType.SINGLE)
|
| 99 |
+
break
|
| 100 |
+
if at.GetAtomicNum()==8 and at.GetFormalCharge()==0 and at.GetExplicitValence()==3:
|
| 101 |
+
at.SetFormalCharge(1)
|
| 102 |
+
if at.GetAtomicNum()==5 and at.GetFormalCharge()==0 and at.GetExplicitValence()==4:
|
| 103 |
+
at.SetFormalCharge(-1)
|
| 104 |
+
try:
|
| 105 |
+
Chem.SanitizeMol(m)
|
| 106 |
+
except:
|
| 107 |
+
return None
|
| 108 |
+
return m
|
| 109 |
+
|
| 110 |
+
def get_different_raid(protein, ligand, raid=6):
|
| 111 |
+
protein_coord = protein['coord']
|
| 112 |
+
ligand_coord = ligand['coord']
|
| 113 |
+
protein_residue_name = protein['residue_name']
|
| 114 |
+
pocket_residue = set()
|
| 115 |
+
for i in range(len(protein_coord)):
|
| 116 |
+
for j in range(len(ligand_coord)):
|
| 117 |
+
if np.linalg.norm(protein_coord[i] - ligand_coord[j]) < raid:
|
| 118 |
+
pocket_residue.add(protein_residue_name[i])
|
| 119 |
+
return pocket_residue
|
| 120 |
+
|
| 121 |
+
def read_mol2_ligand(path):
|
| 122 |
+
mol2_df = PandasMol2().read_mol2(path)
|
| 123 |
+
coord = mol2_df.df[['x', 'y', 'z']]
|
| 124 |
+
atom_type = mol2_df.df['atom_name']
|
| 125 |
+
ligand = {'coord': np.array(coord), 'atom_type': list(atom_type), 'mol': Chem.MolFromMol2File(path)}
|
| 126 |
+
return ligand
|
| 127 |
+
|
| 128 |
+
def read_smi_mol(path):
|
| 129 |
+
with open(path, 'r') as f:
|
| 130 |
+
mols_lines = list(f.readlines())
|
| 131 |
+
smis = [l.split(' ')[0] for l in mols_lines]
|
| 132 |
+
mols = [Chem.MolFromSmiles(m) for m in smis]
|
| 133 |
+
return mols
|
| 134 |
+
|
| 135 |
+
def parser(protein_path, mol_path, ligand_path, activity, pocket_index, raid=6):
|
| 136 |
+
protein = read_pdb(protein_path)
|
| 137 |
+
data_mols = read_smi_mol(mol_path)
|
| 138 |
+
|
| 139 |
+
ligand = read_mol2_ligand(ligand_path)
|
| 140 |
+
pocket_residue = get_different_raid(protein, ligand, raid=raid)
|
| 141 |
+
pocket_atom_idx = [i for i, r in enumerate(protein['residue_name']) if r in pocket_residue]
|
| 142 |
+
pocket_atom_type = [protein['atom_type'][i] for i in pocket_atom_idx]
|
| 143 |
+
pocket_coord = [protein['coord'][i] for i in pocket_atom_idx]
|
| 144 |
+
pocket_residue_type = [protein['residue_type'][i] for i in pocket_atom_idx]
|
| 145 |
+
pocket_name = protein_path.split('/')[-2]
|
| 146 |
+
pool = mp.Pool(6)
|
| 147 |
+
#mols = [convert_2Dmol_to_data(m) for m in data_mols if m is not None]
|
| 148 |
+
data_mols = [m for m in data_mols if m is not None]
|
| 149 |
+
mols = [m for m in tqdm.tqdm(pool.imap_unordered(convert_2Dmol_to_data, data_mols))]
|
| 150 |
+
mols = [m for m in mols if m is not None]
|
| 151 |
+
|
| 152 |
+
return [{'atoms': m['atom_types'],
|
| 153 |
+
'coordinates': m['coords'],
|
| 154 |
+
'smi': m['smi'],
|
| 155 |
+
'mol': ligand,
|
| 156 |
+
'pocket_name': pocket_name,
|
| 157 |
+
'pocket_index': pocket_index,
|
| 158 |
+
'activity': activity,
|
| 159 |
+
"pocket_atom_type": pocket_atom_type,
|
| 160 |
+
"pocket_coord": pocket_coord} for m in mols]
|
| 161 |
+
|
| 162 |
+
def mol_parser(mol_path, ligand_path, label):
|
| 163 |
+
data_mols = read_smi_mol(mol_path)
|
| 164 |
+
data_mols = [m for m in data_mols if m is not None]
|
| 165 |
+
ligand = read_mol2_ligand(ligand_path)
|
| 166 |
+
pool = mp.Pool(32)
|
| 167 |
+
mols = [m for m in tqdm.tqdm(pool.imap_unordered(convert_2Dmol_to_data, data_mols))]
|
| 168 |
+
mols = [m for m in mols if m is not None]
|
| 169 |
+
return [{'atoms': m['atom_types'],
|
| 170 |
+
'coordinates': m['coords'],
|
| 171 |
+
'smi': m['smi'],
|
| 172 |
+
'mol': m['mol'],
|
| 173 |
+
'label': label
|
| 174 |
+
} for m in mols]
|
| 175 |
+
|
| 176 |
+
def pocket_parser(protein_path, ligand_path, pocket_index, raid=6):
|
| 177 |
+
protein = read_pdb(protein_path)
|
| 178 |
+
ligand = read_mol2_ligand(ligand_path)
|
| 179 |
+
pocket_residue = get_different_raid(protein, ligand, raid=raid)
|
| 180 |
+
pocket_atom_idx = [i for i, r in enumerate(protein['residue_name']) if r in pocket_residue]
|
| 181 |
+
pocket_atom_type = [protein['atom_type'][i] for i in pocket_atom_idx]
|
| 182 |
+
pocket_coord = [protein['coord'][i] for i in pocket_atom_idx]
|
| 183 |
+
pocket_residue_type = [protein['residue_type'][i] for i in pocket_atom_idx]
|
| 184 |
+
pocket_name = protein_path.split('/')[-2]
|
| 185 |
+
return {'pocket': pocket_name,
|
| 186 |
+
'pocket_index': pocket_index,
|
| 187 |
+
"pocket_atoms": pocket_atom_type,
|
| 188 |
+
"pocket_coordinates": pocket_coord}
|
| 189 |
+
|
| 190 |
+
def write_lmdb(data, lmdb_path):
|
| 191 |
+
#resume
|
| 192 |
+
|
| 193 |
+
env = lmdb.open(lmdb_path, subdir=False, readonly=False, lock=False, readahead=False, meminit=False, map_size=1099511627776)
|
| 194 |
+
num = 0
|
| 195 |
+
with env.begin(write=True) as txn:
|
| 196 |
+
for d in data:
|
| 197 |
+
txn.put(str(num).encode('ascii'), pickle.dumps(d))
|
| 198 |
+
num += 1
|
| 199 |
+
|
| 200 |
+
if __name__ == '__main__':
|
| 201 |
+
protein_path = [os.path.join(args.mol_data_path, x, 'receptor.pdb') for x in os.listdir(args.mol_data_path)]
|
| 202 |
+
act_mol_path = [os.path.join(args.mol_data_path, x, 'actives_final.ism') for x in os.listdir(args.mol_data_path)]
|
| 203 |
+
decoy_mol_path = [os.path.join(args.mol_data_path, x, 'decoys_final.ism') for x in os.listdir(args.mol_data_path)]
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
for i, pocket in tqdm.tqdm(enumerate(protein_path)):
|
| 208 |
+
# acive mols
|
| 209 |
+
print(i, pocket)
|
| 210 |
+
data = []
|
| 211 |
+
d_active = (mol_parser(act_mol_path[i], pocket.replace('receptor.pdb', 'crystal_ligand.mol2'), 1))
|
| 212 |
+
|
| 213 |
+
data.extend(d_active)
|
| 214 |
+
|
| 215 |
+
# decoy mols
|
| 216 |
+
d_decoy = (mol_parser(decoy_mol_path[i], pocket.replace('receptor.pdb', 'crystal_ligand.mol2'), 0))
|
| 217 |
+
|
| 218 |
+
data.extend(d_decoy)
|
| 219 |
+
|
| 220 |
+
write_lmdb(data, pocket.replace('receptor.pdb', 'mols.lmdb'))
|
| 221 |
+
|
| 222 |
+
# write pocket
|
| 223 |
+
d = pocket_parser(pocket, pocket.replace('receptor.pdb', 'crystal_ligand.mol2'), i)
|
| 224 |
+
write_lmdb([d], pocket.replace('receptor.pdb', 'pocket.lmdb'))
|
| 225 |
+
|
| 226 |
+
# number of lines in actives_final.smi
|
| 227 |
+
with open(act_mol_path[i], 'r') as f:
|
| 228 |
+
mols_lines = list(f.readlines())
|
| 229 |
+
print("active", len(d_active), len(mols_lines))
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
with open(decoy_mol_path[i], 'r') as f:
|
| 234 |
+
mols_lines = list(f.readlines())
|
| 235 |
+
print("decoy", len(d_decoy), len(mols_lines))
|
| 236 |
+
|
| 237 |
+
|
data/retrieval.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
results_path="./test" # replace to your results path
|
| 2 |
+
batch_size=8
|
| 3 |
+
weight_path="ckpt/savedirrandom_zinc/checkpoint_best_seed-2025.pt"
|
| 4 |
+
MOL_PATH="retrieval/mols.lmdb" # path to the molecule file
|
| 5 |
+
POCKET_PATH="retrieval/pocket.lmdb" # path to the pocket file
|
| 6 |
+
EMB_DIR="retrieval/emb" # path to the cached mol embedding file
|
| 7 |
+
|
| 8 |
+
CUDA_VISIBLE_DEVICES="1" python ./unimol/retrieval.py --user-dir ./unimol $data_path "retrieval" --valid-subset test \
|
| 9 |
+
--results-path $results_path \
|
| 10 |
+
--num-workers 8 --ddp-backend=c10d --batch-size $batch_size \
|
| 11 |
+
--task drugclip --loss in_batch_softmax --arch drugclip \
|
| 12 |
+
--max-pocket-atoms 256 \
|
| 13 |
+
--fp16 --fp16-init-scale 4 --fp16-scale-window 256 --seed 1 \
|
| 14 |
+
--path $weight_path \
|
| 15 |
+
--log-interval 100 --log-format simple \
|
| 16 |
+
--mol-path $MOL_PATH \
|
| 17 |
+
--pocket-path $POCKET_PATH \
|
| 18 |
+
--emb-dir $EMB_DIR \
|
data/test.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
results_path="./test" # replace to your results path
|
| 2 |
+
batch_size=8
|
| 3 |
+
weight_path="checkpoint_best_seed.pt"
|
| 4 |
+
|
| 5 |
+
TASK="DUDE" # DUDE or PCBA
|
| 6 |
+
|
| 7 |
+
CUDA_LAUNCH_BLOCKING=1 PYTHONFAULTHANDLER=1 CUDA_VISIBLE_DEVICES="1" python ./unimol/test.py --user-dir ./unimol $data_path "./data" --valid-subset test \
|
| 8 |
+
--results-path $results_path \
|
| 9 |
+
--num-workers 0 --ddp-backend=c10d --batch-size $batch_size \
|
| 10 |
+
--task drugclip --loss in_batch_softmax --arch drugclip \
|
| 11 |
+
--fp16 --fp16-init-scale 4 --fp16-scale-window 256 --seed 1 \
|
| 12 |
+
--path $weight_path \
|
| 13 |
+
--log-interval 100 --log-format simple \
|
| 14 |
+
--max-pocket-atoms 511 \
|
| 15 |
+
--test-task $TASK \
|
data/unimol/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import unimol.tasks
|
| 3 |
+
import unimol.data
|
| 4 |
+
import unimol.models
|
| 5 |
+
import unimol.losses
|
| 6 |
+
import unimol.utils
|
data/unimol/data/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .key_dataset import KeyDataset, LengthDataset
|
| 2 |
+
from .normalize_dataset import (
|
| 3 |
+
NormalizeDataset,
|
| 4 |
+
NormalizeDockingPoseDataset,
|
| 5 |
+
)
|
| 6 |
+
from .remove_hydrogen_dataset import (
|
| 7 |
+
RemoveHydrogenDataset,
|
| 8 |
+
DockRemoveHydrogenDataset, ##
|
| 9 |
+
RemoveHydrogenResiduePocketDataset,
|
| 10 |
+
RemoveHydrogenPocketDataset,
|
| 11 |
+
)
|
| 12 |
+
from .tta_dataset import (
|
| 13 |
+
TTADataset,
|
| 14 |
+
TTADecoderDataset,
|
| 15 |
+
TTADockingPoseDataset,
|
| 16 |
+
)
|
| 17 |
+
from .cropping_dataset import (
|
| 18 |
+
CroppingDataset,
|
| 19 |
+
CroppingPocketDataset,
|
| 20 |
+
CroppingResiduePocketDataset,
|
| 21 |
+
CroppingPocketDockingPoseDataset,
|
| 22 |
+
CroppingPocketDockingPoseTestDataset,
|
| 23 |
+
)
|
| 24 |
+
from .atom_type_dataset import AtomTypeDataset
|
| 25 |
+
from .add_2d_conformer_dataset import Add2DConformerDataset
|
| 26 |
+
from .distance_dataset import (
|
| 27 |
+
DistanceDataset,
|
| 28 |
+
EdgeTypeDataset,
|
| 29 |
+
CrossDistanceDataset,
|
| 30 |
+
CrossEdgeTypeDataset
|
| 31 |
+
)
|
| 32 |
+
from .conformer_sample_dataset import (
|
| 33 |
+
ConformerSampleDataset,
|
| 34 |
+
ConformerSampleDecoderDataset,
|
| 35 |
+
ConformerSamplePocketDataset,
|
| 36 |
+
ConformerSamplePocketFinetuneDataset,
|
| 37 |
+
ConformerSampleConfGDataset,
|
| 38 |
+
ConformerSampleConfGV2Dataset,
|
| 39 |
+
ConformerSampleDockingPoseDataset,
|
| 40 |
+
)
|
| 41 |
+
from .mask_points_dataset import MaskPointsDataset, MaskPointsPocketDataset
|
| 42 |
+
from .coord_pad_dataset import RightPadDatasetCoord, RightPadDatasetCross2D
|
| 43 |
+
from .from_str_dataset import FromStrLabelDataset
|
| 44 |
+
from .lmdb_dataset import LMDBDataset
|
| 45 |
+
from .prepend_and_append_2d_dataset import PrependAndAppend2DDataset
|
| 46 |
+
from .affinity_dataset import AffinityDataset, AffinityTestDataset, AffinityValidDataset, AffinityMolDataset, AffinityPocketDataset, AffinityHNSDataset, AffinityAugDataset
|
| 47 |
+
from .pocket2mol_dataset import FragmentConformationDataset
|
| 48 |
+
from .vae_binding_dataset import VAEBindingDataset, VAEBindingTestDataset, VAEGenerationTestDataset
|
| 49 |
+
from .resampling_dataset import ResamplingDataset
|
| 50 |
+
from .complex_center_dataset import ComplexCenterDataset
|
| 51 |
+
__all__ = []
|
data/unimol/data/add_2d_conformer_dataset.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from unicore.data import BaseWrapperDataset
|
| 8 |
+
from rdkit import Chem
|
| 9 |
+
from rdkit.Chem import AllChem
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Add2DConformerDataset(BaseWrapperDataset):
|
| 13 |
+
def __init__(self, dataset, smi, atoms, coordinates):
|
| 14 |
+
self.dataset = dataset
|
| 15 |
+
self.smi = smi
|
| 16 |
+
self.atoms = atoms
|
| 17 |
+
self.coordinates = coordinates
|
| 18 |
+
self.set_epoch(None)
|
| 19 |
+
|
| 20 |
+
def set_epoch(self, epoch, **unused):
|
| 21 |
+
super().set_epoch(epoch)
|
| 22 |
+
self.epoch = epoch
|
| 23 |
+
|
| 24 |
+
@lru_cache(maxsize=16)
|
| 25 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 26 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 27 |
+
assert len(atoms) > 0
|
| 28 |
+
smi = self.dataset[index][self.smi]
|
| 29 |
+
coordinates_2d = smi2_2Dcoords(smi)
|
| 30 |
+
coordinates = self.dataset[index][self.coordinates]
|
| 31 |
+
coordinates.append(coordinates_2d)
|
| 32 |
+
return {"smi": smi, "atoms": atoms, "coordinates": coordinates}
|
| 33 |
+
|
| 34 |
+
def __getitem__(self, index: int):
|
| 35 |
+
return self.__cached_item__(index, self.epoch)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def smi2_2Dcoords(smi):
|
| 39 |
+
mol = Chem.MolFromSmiles(smi)
|
| 40 |
+
mol = AllChem.AddHs(mol)
|
| 41 |
+
AllChem.Compute2DCoords(mol)
|
| 42 |
+
coordinates = mol.GetConformer().GetPositions().astype(np.float32)
|
| 43 |
+
len(mol.GetAtoms()) == len(
|
| 44 |
+
coordinates
|
| 45 |
+
), "2D coordinates shape is not align with {}".format(smi)
|
| 46 |
+
return coordinates
|
data/unimol/data/affinity_dataset.py
ADDED
|
@@ -0,0 +1,567 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
from unicore.data import BaseWrapperDataset
|
| 10 |
+
|
| 11 |
+
from . import data_utils
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class AffinityDataset(BaseWrapperDataset):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
dataset,
|
| 18 |
+
seed,
|
| 19 |
+
atoms,
|
| 20 |
+
coordinates,
|
| 21 |
+
decoy_atoms,
|
| 22 |
+
decoy_coordinates,
|
| 23 |
+
docked_coordinates,
|
| 24 |
+
pocket_atoms,
|
| 25 |
+
pocket_coordinates,
|
| 26 |
+
affinity,
|
| 27 |
+
is_train=False,
|
| 28 |
+
pocket="pocket"
|
| 29 |
+
):
|
| 30 |
+
self.dataset = dataset
|
| 31 |
+
self.seed = seed
|
| 32 |
+
self.atoms = atoms
|
| 33 |
+
self.coordinates = coordinates
|
| 34 |
+
self.decoy_atoms = decoy_atoms
|
| 35 |
+
self.decoy_coordinates = decoy_coordinates
|
| 36 |
+
self.docked_coordinates = docked_coordinates
|
| 37 |
+
self.pocket_atoms = pocket_atoms
|
| 38 |
+
self.pocket_coordinates = pocket_coordinates
|
| 39 |
+
self.affinity = affinity
|
| 40 |
+
self.is_train = is_train
|
| 41 |
+
self.pocket=pocket
|
| 42 |
+
self.set_epoch(None)
|
| 43 |
+
|
| 44 |
+
def set_epoch(self, epoch, **unused):
|
| 45 |
+
super().set_epoch(epoch)
|
| 46 |
+
self.epoch = epoch
|
| 47 |
+
|
| 48 |
+
def pocket_atom(self, atom):
|
| 49 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 50 |
+
return atom[1]
|
| 51 |
+
else:
|
| 52 |
+
return atom[0]
|
| 53 |
+
|
| 54 |
+
@lru_cache(maxsize=16)
|
| 55 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 56 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 57 |
+
ori_mol_length = len(atoms)
|
| 58 |
+
size = len(self.dataset[index][self.coordinates])
|
| 59 |
+
if self.is_train:
|
| 60 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 61 |
+
sample_idx = np.random.randint(size)
|
| 62 |
+
else:
|
| 63 |
+
with data_utils.numpy_seed(self.seed, 1, index):
|
| 64 |
+
sample_idx = np.random.randint(size)
|
| 65 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 66 |
+
|
| 67 |
+
# docking
|
| 68 |
+
docked_coordinates = self.dataset[index][self.docked_coordinates]
|
| 69 |
+
# # fingerprints
|
| 70 |
+
scaffold_fp = self.dataset[index]["scaffold_fp"]
|
| 71 |
+
property_vec = self.dataset[index]["scaffold_fp"]
|
| 72 |
+
|
| 73 |
+
# # decoy using pool
|
| 74 |
+
# item = self.dataset[index]
|
| 75 |
+
# pool_atoms = item["hard_decoy_atoms"] # list, len = 10
|
| 76 |
+
# pool_coords = item["hard_decoy_coordinates"] # list of conf-list
|
| 77 |
+
# pool_fp = item["hard_decoy_scaffold_fp"] # optional list
|
| 78 |
+
# pool_size = len(pool_atoms)
|
| 79 |
+
# if self.is_train:
|
| 80 |
+
# with data_utils.numpy_seed(self.seed, epoch, index):
|
| 81 |
+
# pool_idx = np.random.randint(pool_size)
|
| 82 |
+
# else:
|
| 83 |
+
# with data_utils.numpy_seed(self.seed, 1, index):
|
| 84 |
+
# pool_idx = np.random.randint(pool_size)
|
| 85 |
+
# decoy_atoms = np.array(pool_atoms[pool_idx])
|
| 86 |
+
# decoy_num_conf = len(pool_coords[pool_idx])
|
| 87 |
+
# if self.is_train:
|
| 88 |
+
# with data_utils.numpy_seed(self.seed, epoch, index, pool_idx):
|
| 89 |
+
# decoy_conf_idx = np.random.randint(decoy_num_conf)
|
| 90 |
+
# else:
|
| 91 |
+
# with data_utils.numpy_seed(self.seed, 1, index, pool_idx):
|
| 92 |
+
# decoy_conf_idx = np.random.randint(decoy_num_conf)
|
| 93 |
+
|
| 94 |
+
# decoy_coordinates = pool_coords[pool_idx][decoy_conf_idx]
|
| 95 |
+
# decoy_scaffold_fp = pool_fp[pool_idx]
|
| 96 |
+
# decoy_property_vec = decoy_scaffold_fp
|
| 97 |
+
|
| 98 |
+
decoy_atoms = np.array(self.dataset[index][self.decoy_atoms])
|
| 99 |
+
decoy_num_conf = len(self.dataset[index][self.decoy_coordinates])
|
| 100 |
+
if self.is_train:
|
| 101 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 102 |
+
decoy_conf_idx = np.random.randint(decoy_num_conf)
|
| 103 |
+
else:
|
| 104 |
+
with data_utils.numpy_seed(self.seed, 1, index):
|
| 105 |
+
decoy_conf_idx = np.random.randint(decoy_num_conf)
|
| 106 |
+
decoy_coordinates = self.dataset[index][self.decoy_coordinates][decoy_conf_idx]
|
| 107 |
+
decoy_scaffold_fp = self.dataset[index]["hard_decoy_scaffold_fp"]
|
| 108 |
+
decoy_property_vec = self.dataset[index]["hard_decoy_scaffold_fp"]
|
| 109 |
+
# decoy_scaffold_fp = self.dataset[index]["decoy_scaffold_fp"]
|
| 110 |
+
# decoy_property_vec = self.dataset[index]["decoy_scaffold_fp"]
|
| 111 |
+
|
| 112 |
+
pocket_atoms = np.array(
|
| 113 |
+
[self.pocket_atom(item) for item in self.dataset[index][self.pocket_atoms]]
|
| 114 |
+
)
|
| 115 |
+
ori_pocket_length = len(pocket_atoms)
|
| 116 |
+
pocket_coordinates = np.stack(self.dataset[index][self.pocket_coordinates])
|
| 117 |
+
|
| 118 |
+
smi = self.dataset[index]["smi"]
|
| 119 |
+
hard_label = self.dataset[index]["hard_is_random"]
|
| 120 |
+
pocket = self.dataset[index][self.pocket]
|
| 121 |
+
if self.affinity in self.dataset[index]:
|
| 122 |
+
affinity = float(self.dataset[index][self.affinity])
|
| 123 |
+
else:
|
| 124 |
+
affinity = 1
|
| 125 |
+
return {
|
| 126 |
+
"atoms": atoms,
|
| 127 |
+
"coordinates": coordinates.astype(np.float32),
|
| 128 |
+
|
| 129 |
+
"decoy_atoms": decoy_atoms,
|
| 130 |
+
"decoy_coordinates": np.array(decoy_coordinates, dtype=np.float32),
|
| 131 |
+
"docked_coordinates": docked_coordinates.astype(np.float32),
|
| 132 |
+
"scaffold_fp": scaffold_fp,
|
| 133 |
+
"decoy_scaffold_fp": decoy_scaffold_fp,
|
| 134 |
+
"property_vec": property_vec,
|
| 135 |
+
"decoy_property_vec": decoy_property_vec,
|
| 136 |
+
'hard_label':hard_label,
|
| 137 |
+
|
| 138 |
+
"holo_coordinates": coordinates.astype(np.float32),#placeholder
|
| 139 |
+
"pocket_atoms": pocket_atoms,
|
| 140 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 141 |
+
"holo_pocket_coordinates": pocket_coordinates.astype(np.float32),#placeholder
|
| 142 |
+
"smi": smi,
|
| 143 |
+
"pocket": pocket,
|
| 144 |
+
"affinity": affinity,
|
| 145 |
+
"ori_mol_length": ori_mol_length,
|
| 146 |
+
"ori_pocket_length": ori_pocket_length
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
def __getitem__(self, index: int):
|
| 150 |
+
return self.__cached_item__(index, self.epoch)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class AffinityAugDataset(BaseWrapperDataset):
|
| 154 |
+
def __init__(
|
| 155 |
+
self,
|
| 156 |
+
dataset,
|
| 157 |
+
seed,
|
| 158 |
+
atoms,
|
| 159 |
+
coordinates,
|
| 160 |
+
pocket_atoms,
|
| 161 |
+
pocket_coordinates,
|
| 162 |
+
affinity,
|
| 163 |
+
is_train=False,
|
| 164 |
+
pocket="pocket_id"
|
| 165 |
+
):
|
| 166 |
+
self.dataset = dataset
|
| 167 |
+
self.seed = seed
|
| 168 |
+
self.atoms = atoms
|
| 169 |
+
self.coordinates = coordinates
|
| 170 |
+
self.pocket_atoms = pocket_atoms
|
| 171 |
+
self.pocket_coordinates = pocket_coordinates
|
| 172 |
+
self.affinity = affinity
|
| 173 |
+
self.is_train = is_train
|
| 174 |
+
self.pocket=pocket
|
| 175 |
+
self.set_epoch(None)
|
| 176 |
+
|
| 177 |
+
def set_epoch(self, epoch, **unused):
|
| 178 |
+
super().set_epoch(epoch)
|
| 179 |
+
self.epoch = epoch
|
| 180 |
+
|
| 181 |
+
def pocket_atom(self, atom):
|
| 182 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 183 |
+
return atom[1]
|
| 184 |
+
else:
|
| 185 |
+
return atom[0]
|
| 186 |
+
|
| 187 |
+
@lru_cache(maxsize=16)
|
| 188 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 189 |
+
#mol_atoms_list = self.dataset[index][self.atoms]
|
| 190 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 191 |
+
mol_idx = np.random.randint(len(self.dataset[index][self.atoms]))
|
| 192 |
+
atoms = np.array(self.dataset[index][self.atoms][mol_idx])
|
| 193 |
+
ori_mol_length = len(atoms)
|
| 194 |
+
#coordinates = self.dataset[index][self.coordinates]
|
| 195 |
+
size = len(self.dataset[index][self.coordinates][mol_idx])
|
| 196 |
+
if self.is_train:
|
| 197 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 198 |
+
sample_idx = np.random.randint(size)
|
| 199 |
+
else:
|
| 200 |
+
with data_utils.numpy_seed(self.seed, 1, index):
|
| 201 |
+
sample_idx = np.random.randint(size)
|
| 202 |
+
#print(len(self.dataset[index][self.coordinates][sample_idx]))
|
| 203 |
+
coordinates = self.dataset[index][self.coordinates][mol_idx][sample_idx]
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
#pocket_list = self.dataset[index][self.pocket_atoms]
|
| 207 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 208 |
+
pocket_idx = np.random.randint(len(self.dataset[index][self.pocket_atoms]))
|
| 209 |
+
pocket_atoms = np.array(
|
| 210 |
+
[self.pocket_atom(item) for item in self.dataset[index][self.pocket_atoms][pocket_idx]]
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
ori_pocket_length = len(pocket_atoms)
|
| 214 |
+
pocket_coordinates = np.stack(self.dataset[index][self.pocket_coordinates][pocket_idx])
|
| 215 |
+
|
| 216 |
+
smi = self.dataset[index]["smiles"][mol_idx]
|
| 217 |
+
pocket = self.dataset[index][self.pocket][0]
|
| 218 |
+
if self.affinity in self.dataset[index]:
|
| 219 |
+
affinity = float(self.dataset[index][self.affinity])
|
| 220 |
+
else:
|
| 221 |
+
affinity = 1
|
| 222 |
+
return {
|
| 223 |
+
"atoms": atoms,
|
| 224 |
+
"coordinates": coordinates.astype(np.float32),
|
| 225 |
+
"holo_coordinates": coordinates.astype(np.float32),#placeholder
|
| 226 |
+
"pocket_atoms": pocket_atoms,
|
| 227 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 228 |
+
"holo_pocket_coordinates": pocket_coordinates.astype(np.float32),#placeholder
|
| 229 |
+
"smi": smi,
|
| 230 |
+
"pocket": pocket,
|
| 231 |
+
"affinity": affinity,
|
| 232 |
+
"ori_mol_length": ori_mol_length,
|
| 233 |
+
"ori_pocket_length": ori_pocket_length
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
def __getitem__(self, index: int):
|
| 237 |
+
return self.__cached_item__(index, self.epoch)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class AffinityHNSDataset(BaseWrapperDataset):
|
| 241 |
+
def __init__(
|
| 242 |
+
self,
|
| 243 |
+
dataset,
|
| 244 |
+
seed,
|
| 245 |
+
atoms,
|
| 246 |
+
coordinates,
|
| 247 |
+
atoms_hns,
|
| 248 |
+
coordinates_hns,
|
| 249 |
+
pocket_atoms,
|
| 250 |
+
pocket_coordinates,
|
| 251 |
+
affinity,
|
| 252 |
+
is_train=False,
|
| 253 |
+
pocket="pocket"
|
| 254 |
+
):
|
| 255 |
+
self.dataset = dataset
|
| 256 |
+
self.seed = seed
|
| 257 |
+
self.atoms = atoms
|
| 258 |
+
self.coordinates = coordinates
|
| 259 |
+
self.atoms_hns = atoms_hns
|
| 260 |
+
self.coordinates_hns = coordinates_hns
|
| 261 |
+
self.pocket_atoms = pocket_atoms
|
| 262 |
+
self.pocket_coordinates = pocket_coordinates
|
| 263 |
+
self.affinity = affinity
|
| 264 |
+
self.is_train = is_train
|
| 265 |
+
self.pocket=pocket
|
| 266 |
+
self.set_epoch(None)
|
| 267 |
+
|
| 268 |
+
def set_epoch(self, epoch, **unused):
|
| 269 |
+
super().set_epoch(epoch)
|
| 270 |
+
self.epoch = epoch
|
| 271 |
+
|
| 272 |
+
def pocket_atom(self, atom):
|
| 273 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 274 |
+
return atom[1]
|
| 275 |
+
else:
|
| 276 |
+
return atom[0]
|
| 277 |
+
|
| 278 |
+
@lru_cache(maxsize=16)
|
| 279 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 280 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 281 |
+
ori_mol_length = len(atoms)
|
| 282 |
+
#coordinates = self.dataset[index][self.coordinates]
|
| 283 |
+
size = len(self.dataset[index][self.coordinates])
|
| 284 |
+
if self.is_train:
|
| 285 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 286 |
+
sample_idx = np.random.randint(size)
|
| 287 |
+
else:
|
| 288 |
+
with data_utils.numpy_seed(self.seed, 1, index):
|
| 289 |
+
sample_idx = np.random.randint(size)
|
| 290 |
+
#print(len(self.dataset[index][self.coordinates][sample_idx]))
|
| 291 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 292 |
+
atoms_hns = np.array(self.dataset[index][self.atoms_hns])
|
| 293 |
+
coordinates_hns = self.dataset[index][self.coordinates_hns][0]
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
pocket_atoms = np.array(
|
| 298 |
+
[self.pocket_atom(item) for item in self.dataset[index][self.pocket_atoms]]
|
| 299 |
+
)
|
| 300 |
+
ori_pocket_length = len(pocket_atoms)
|
| 301 |
+
pocket_coordinates = np.stack(self.dataset[index][self.pocket_coordinates])
|
| 302 |
+
|
| 303 |
+
smi = self.dataset[index]["smi"]
|
| 304 |
+
pocket = self.dataset[index][self.pocket]
|
| 305 |
+
if self.affinity in self.dataset[index]:
|
| 306 |
+
affinity = float(self.dataset[index][self.affinity])
|
| 307 |
+
else:
|
| 308 |
+
affinity = 1
|
| 309 |
+
return {
|
| 310 |
+
"atoms": atoms,
|
| 311 |
+
"coordinates": coordinates.astype(np.float32),
|
| 312 |
+
"atoms_hns": atoms_hns,
|
| 313 |
+
"coordinates_hns": coordinates_hns.astype(np.float32),
|
| 314 |
+
"holo_coordinates": coordinates.astype(np.float32),#placeholder
|
| 315 |
+
"pocket_atoms": pocket_atoms,
|
| 316 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 317 |
+
"holo_pocket_coordinates": pocket_coordinates.astype(np.float32),#placeholder
|
| 318 |
+
"smi": smi,
|
| 319 |
+
"pocket": pocket,
|
| 320 |
+
"affinity": affinity,
|
| 321 |
+
"ori_mol_length": ori_mol_length,
|
| 322 |
+
"ori_pocket_length": ori_pocket_length
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
def __getitem__(self, index: int):
|
| 326 |
+
return self.__cached_item__(index, self.epoch)
|
| 327 |
+
|
| 328 |
+
class AffinityTestDataset(BaseWrapperDataset):
|
| 329 |
+
def __init__(
|
| 330 |
+
self,
|
| 331 |
+
dataset,
|
| 332 |
+
seed,
|
| 333 |
+
atoms,
|
| 334 |
+
coordinates,
|
| 335 |
+
pocket_atoms,
|
| 336 |
+
pocket_coordinates,
|
| 337 |
+
affinity=None,
|
| 338 |
+
is_train=False,
|
| 339 |
+
pocket="pocket"
|
| 340 |
+
):
|
| 341 |
+
self.dataset = dataset
|
| 342 |
+
self.seed = seed
|
| 343 |
+
self.atoms = atoms
|
| 344 |
+
self.coordinates = coordinates
|
| 345 |
+
self.pocket_atoms = pocket_atoms
|
| 346 |
+
self.pocket_coordinates = pocket_coordinates
|
| 347 |
+
self.affinity = affinity
|
| 348 |
+
self.is_train = is_train
|
| 349 |
+
self.pocket=pocket
|
| 350 |
+
self.set_epoch(None)
|
| 351 |
+
|
| 352 |
+
def set_epoch(self, epoch, **unused):
|
| 353 |
+
super().set_epoch(epoch)
|
| 354 |
+
self.epoch = epoch
|
| 355 |
+
|
| 356 |
+
def pocket_atom(self, atom):
|
| 357 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 358 |
+
return atom[1]
|
| 359 |
+
else:
|
| 360 |
+
return atom[0]
|
| 361 |
+
|
| 362 |
+
@lru_cache(maxsize=16)
|
| 363 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 364 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 365 |
+
ori_length = len(atoms)
|
| 366 |
+
#coordinates = self.dataset[index][self.coordinates]
|
| 367 |
+
size = len(self.dataset[index][self.coordinates])
|
| 368 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 369 |
+
sample_idx = np.random.randint(size)
|
| 370 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 371 |
+
pocket_atoms = np.array(
|
| 372 |
+
[self.pocket_atom(item) for item in self.dataset[index][self.pocket_atoms]]
|
| 373 |
+
)
|
| 374 |
+
#print(len(self.dataset[index][self.pocket_coordinates]))
|
| 375 |
+
pocket_coordinates = np.stack(self.dataset[index][self.pocket_coordinates])
|
| 376 |
+
|
| 377 |
+
smi = self.dataset[index]["smi"]
|
| 378 |
+
pocket = self.dataset[index][self.pocket]
|
| 379 |
+
affinity = self.dataset[index][self.affinity]
|
| 380 |
+
return {
|
| 381 |
+
"atoms": atoms,
|
| 382 |
+
"coordinates": coordinates.astype(np.float32),
|
| 383 |
+
"holo_coordinates": coordinates.astype(np.float32),#placeholder
|
| 384 |
+
"pocket_atoms": pocket_atoms,
|
| 385 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 386 |
+
"holo_pocket_coordinates": pocket_coordinates.astype(np.float32),#placeholder
|
| 387 |
+
"smi": smi,
|
| 388 |
+
"pocket": pocket,
|
| 389 |
+
"affinity": affinity.astype(np.float32),
|
| 390 |
+
"ori_length": ori_length
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
def __getitem__(self, index: int):
|
| 394 |
+
return self.__cached_item__(index, self.epoch)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
class AffinityMolDataset(BaseWrapperDataset):
|
| 398 |
+
def __init__(
|
| 399 |
+
self,
|
| 400 |
+
dataset,
|
| 401 |
+
seed,
|
| 402 |
+
atoms,
|
| 403 |
+
coordinates,
|
| 404 |
+
is_train=False,
|
| 405 |
+
):
|
| 406 |
+
self.dataset = dataset
|
| 407 |
+
self.seed = seed
|
| 408 |
+
self.atoms = atoms
|
| 409 |
+
self.coordinates = coordinates
|
| 410 |
+
self.is_train = is_train
|
| 411 |
+
self.set_epoch(None)
|
| 412 |
+
|
| 413 |
+
def set_epoch(self, epoch, **unused):
|
| 414 |
+
super().set_epoch(epoch)
|
| 415 |
+
self.epoch = epoch
|
| 416 |
+
|
| 417 |
+
def pocket_atom(self, atom):
|
| 418 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 419 |
+
return atom[1]
|
| 420 |
+
else:
|
| 421 |
+
return atom[0]
|
| 422 |
+
|
| 423 |
+
@lru_cache(maxsize=16)
|
| 424 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 425 |
+
#print(self.dataset[index])
|
| 426 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 427 |
+
ori_length = len(atoms)
|
| 428 |
+
#coordinates = self.dataset[index][self.coordinates]
|
| 429 |
+
size = len(self.dataset[index][self.coordinates])
|
| 430 |
+
#print(size)
|
| 431 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 432 |
+
sample_idx = np.random.randint(size)
|
| 433 |
+
# check coordinates is 2 dimension or not
|
| 434 |
+
if len(self.dataset[index][self.coordinates][sample_idx].shape) == 2:
|
| 435 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 436 |
+
else:
|
| 437 |
+
coordinates = self.dataset[index][self.coordinates]
|
| 438 |
+
#coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 439 |
+
#coordinates = self.dataset[index][self.coordinates]
|
| 440 |
+
|
| 441 |
+
smi = self.dataset[index]["smi"]
|
| 442 |
+
return {
|
| 443 |
+
"atoms": atoms,
|
| 444 |
+
"coordinates": coordinates.astype(np.float32),
|
| 445 |
+
"holo_coordinates": coordinates.astype(np.float32),#placeholder
|
| 446 |
+
"smi": smi,
|
| 447 |
+
"ori_length": ori_length
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
def __getitem__(self, index: int):
|
| 451 |
+
return self.__cached_item__(index, self.epoch)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
class AffinityPocketDataset(BaseWrapperDataset):
|
| 455 |
+
def __init__(
|
| 456 |
+
self,
|
| 457 |
+
dataset,
|
| 458 |
+
seed,
|
| 459 |
+
pocket_atoms,
|
| 460 |
+
pocket_coordinates,
|
| 461 |
+
is_train=False,
|
| 462 |
+
pocket="pocket"
|
| 463 |
+
):
|
| 464 |
+
self.dataset = dataset
|
| 465 |
+
self.seed = seed
|
| 466 |
+
self.pocket_atoms = pocket_atoms
|
| 467 |
+
self.pocket_coordinates = pocket_coordinates
|
| 468 |
+
self.is_train = is_train
|
| 469 |
+
self.pocket=pocket
|
| 470 |
+
self.set_epoch(None)
|
| 471 |
+
|
| 472 |
+
def set_epoch(self, epoch, **unused):
|
| 473 |
+
super().set_epoch(epoch)
|
| 474 |
+
self.epoch = epoch
|
| 475 |
+
|
| 476 |
+
def pocket_atom(self, atom):
|
| 477 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 478 |
+
return atom[1]
|
| 479 |
+
else:
|
| 480 |
+
return atom[0]
|
| 481 |
+
|
| 482 |
+
@lru_cache(maxsize=16)
|
| 483 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 484 |
+
pocket_atoms = np.array(
|
| 485 |
+
[self.pocket_atom(item) for item in self.dataset[index][self.pocket_atoms]]
|
| 486 |
+
)
|
| 487 |
+
ori_length = len(pocket_atoms)
|
| 488 |
+
pocket_coordinates = np.stack(self.dataset[index][self.pocket_coordinates])
|
| 489 |
+
if self.pocket in self.dataset[index]:
|
| 490 |
+
pocket = self.dataset[index][self.pocket]
|
| 491 |
+
else:
|
| 492 |
+
pocket = ""
|
| 493 |
+
return {
|
| 494 |
+
"pocket_atoms": pocket_atoms,
|
| 495 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 496 |
+
"holo_pocket_coordinates": pocket_coordinates.astype(np.float32),#placeholder
|
| 497 |
+
"pocket": pocket,
|
| 498 |
+
"ori_length": ori_length
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
def __getitem__(self, index: int):
|
| 502 |
+
return self.__cached_item__(index, self.epoch)
|
| 503 |
+
|
| 504 |
+
class AffinityValidDataset(BaseWrapperDataset):
|
| 505 |
+
def __init__(
|
| 506 |
+
self,
|
| 507 |
+
dataset,
|
| 508 |
+
seed,
|
| 509 |
+
atoms,
|
| 510 |
+
coordinates,
|
| 511 |
+
pocket_atoms,
|
| 512 |
+
pocket_coordinates,
|
| 513 |
+
pocket="pocket"
|
| 514 |
+
):
|
| 515 |
+
self.dataset = dataset
|
| 516 |
+
self.seed = seed
|
| 517 |
+
self.atoms = atoms
|
| 518 |
+
self.coordinates = coordinates
|
| 519 |
+
self.pocket_atoms = pocket_atoms
|
| 520 |
+
self.pocket_coordinates = pocket_coordinates
|
| 521 |
+
self.pocket=pocket
|
| 522 |
+
self.set_epoch(None)
|
| 523 |
+
|
| 524 |
+
def set_epoch(self, epoch, **unused):
|
| 525 |
+
super().set_epoch(epoch)
|
| 526 |
+
self.epoch = epoch
|
| 527 |
+
|
| 528 |
+
def pocket_atom(self, atom):
|
| 529 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 530 |
+
return atom[1]
|
| 531 |
+
else:
|
| 532 |
+
return atom[0]
|
| 533 |
+
|
| 534 |
+
@lru_cache(maxsize=16)
|
| 535 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 536 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 537 |
+
ori_mol_length = len(atoms)
|
| 538 |
+
#coordinates = self.dataset[index][self.coordinates]
|
| 539 |
+
|
| 540 |
+
size = len(self.dataset[index][self.coordinates])
|
| 541 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 542 |
+
sample_idx = np.random.randint(size)
|
| 543 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 544 |
+
pocket_atoms = np.array(
|
| 545 |
+
[self.pocket_atom(item) for item in self.dataset[index][self.pocket_atoms]]
|
| 546 |
+
)
|
| 547 |
+
ori_pocket_length = len(pocket_atoms)
|
| 548 |
+
pocket_coordinates = np.stack(self.dataset[index][self.pocket_coordinates])
|
| 549 |
+
|
| 550 |
+
smi = self.dataset[index]["smi"]
|
| 551 |
+
pocket = self.dataset[index][self.pocket]
|
| 552 |
+
return {
|
| 553 |
+
"atoms": atoms,
|
| 554 |
+
"coordinates": coordinates.astype(np.float32),
|
| 555 |
+
"coordinates": coordinates.astype(np.float32),
|
| 556 |
+
"holo_coordinates": coordinates.astype(np.float32),#placeholder
|
| 557 |
+
"pocket_atoms": pocket_atoms,
|
| 558 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 559 |
+
"holo_pocket_coordinates": pocket_coordinates.astype(np.float32),#placeholder
|
| 560 |
+
"smi": smi,
|
| 561 |
+
"pocket": pocket,
|
| 562 |
+
"ori_mol_length": ori_mol_length,
|
| 563 |
+
"ori_pocket_length": ori_pocket_length
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
def __getitem__(self, index: int):
|
| 567 |
+
return self.__cached_item__(index, self.epoch)
|
data/unimol/data/atom_type_dataset.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from unicore.data import BaseWrapperDataset
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class AtomTypeDataset(BaseWrapperDataset):
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
raw_dataset,
|
| 13 |
+
dataset,
|
| 14 |
+
smi="smi",
|
| 15 |
+
atoms="atoms",
|
| 16 |
+
):
|
| 17 |
+
self.raw_dataset = raw_dataset
|
| 18 |
+
self.dataset = dataset
|
| 19 |
+
self.smi = smi
|
| 20 |
+
self.atoms = atoms
|
| 21 |
+
|
| 22 |
+
@lru_cache(maxsize=16)
|
| 23 |
+
def __getitem__(self, index: int):
|
| 24 |
+
# for low rdkit version
|
| 25 |
+
if len(self.dataset[index]["atoms"]) != len(self.dataset[index]["coordinates"]):
|
| 26 |
+
min_len = min(
|
| 27 |
+
len(self.dataset[index]["atoms"]),
|
| 28 |
+
len(self.dataset[index]["coordinates"]),
|
| 29 |
+
)
|
| 30 |
+
self.dataset[index]["atoms"] = self.dataset[index]["atoms"][:min_len]
|
| 31 |
+
self.dataset[index]["coordinates"] = self.dataset[index]["coordinates"][
|
| 32 |
+
:min_len
|
| 33 |
+
]
|
| 34 |
+
return self.dataset[index]
|
data/unimol/data/complex_center_dataset.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from unicore.data import BaseWrapperDataset
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ComplexCenterDataset(BaseWrapperDataset):
|
| 11 |
+
"""
|
| 12 |
+
compute COM for duffsion
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
dataset,
|
| 18 |
+
lig_coord_key="coordinates",
|
| 19 |
+
pocket_coord_key="pocket_coordinates",
|
| 20 |
+
out_lig_key="lig_coord_com",
|
| 21 |
+
out_pocket_key="pocket_coord_com",
|
| 22 |
+
):
|
| 23 |
+
self.dataset = dataset
|
| 24 |
+
self.lig_coord_key = lig_coord_key
|
| 25 |
+
self.pocket_coord_key = pocket_coord_key
|
| 26 |
+
self.out_lig_key = out_lig_key
|
| 27 |
+
self.out_pocket_key = out_pocket_key
|
| 28 |
+
self.set_epoch(None)
|
| 29 |
+
|
| 30 |
+
def set_epoch(self, epoch, **unused):
|
| 31 |
+
super().set_epoch(epoch)
|
| 32 |
+
self.epoch = epoch
|
| 33 |
+
|
| 34 |
+
@lru_cache(maxsize=16)
|
| 35 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 36 |
+
|
| 37 |
+
dd = self.dataset[index].copy()
|
| 38 |
+
|
| 39 |
+
lig = dd[self.lig_coord_key] # (N_lig, 3)
|
| 40 |
+
poc = dd[self.pocket_coord_key] # (N_poc, 3)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# if lig.size == 0 and poc.size == 0:
|
| 44 |
+
# return dd
|
| 45 |
+
|
| 46 |
+
# if lig.size == 0:
|
| 47 |
+
# all_pos = poc
|
| 48 |
+
# elif poc.size == 0:
|
| 49 |
+
# all_pos = lig
|
| 50 |
+
# else:
|
| 51 |
+
# all_pos = np.concatenate([lig, poc], axis=0) # (N_lig+N_poc, 3)
|
| 52 |
+
#using pocket coordinates to compute COM
|
| 53 |
+
all_pos = poc
|
| 54 |
+
center = all_pos.mean(axis=0, keepdims=True) # (1, 3)
|
| 55 |
+
|
| 56 |
+
lig_centered = lig - center
|
| 57 |
+
poc_centered = poc - center
|
| 58 |
+
|
| 59 |
+
dd[self.out_lig_key] = lig_centered.astype(np.float32)
|
| 60 |
+
dd[self.out_pocket_key] = poc_centered.astype(np.float32)
|
| 61 |
+
|
| 62 |
+
return dd
|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the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from unicore.data import BaseWrapperDataset
|
| 8 |
+
from . import data_utils
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ConformerSampleDataset(BaseWrapperDataset):
|
| 12 |
+
def __init__(self, dataset, seed, atoms, coordinates):
|
| 13 |
+
self.dataset = dataset
|
| 14 |
+
self.seed = seed
|
| 15 |
+
self.atoms = atoms
|
| 16 |
+
self.coordinates = coordinates
|
| 17 |
+
self.set_epoch(None)
|
| 18 |
+
|
| 19 |
+
def set_epoch(self, epoch, **unused):
|
| 20 |
+
super().set_epoch(epoch)
|
| 21 |
+
self.epoch = epoch
|
| 22 |
+
|
| 23 |
+
@lru_cache(maxsize=16)
|
| 24 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 25 |
+
#print(index,self.dataset[index])
|
| 26 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 27 |
+
assert len(atoms) > 0
|
| 28 |
+
size = len(self.dataset[index][self.coordinates])
|
| 29 |
+
#print(size)
|
| 30 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 31 |
+
sample_idx = np.random.randint(size)
|
| 32 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 33 |
+
return {"atoms": atoms, "coordinates": coordinates.astype(np.float32)}
|
| 34 |
+
|
| 35 |
+
def __getitem__(self, index: int):
|
| 36 |
+
return self.__cached_item__(index, self.epoch)
|
| 37 |
+
|
| 38 |
+
class ConformerSampleDecoderDataset(BaseWrapperDataset):
|
| 39 |
+
def __init__(self, dataset, seed, atoms, coordinates, selfies):
|
| 40 |
+
self.dataset = dataset
|
| 41 |
+
self.seed = seed
|
| 42 |
+
self.atoms = atoms
|
| 43 |
+
self.coordinates = coordinates
|
| 44 |
+
self.selfies = selfies
|
| 45 |
+
self.set_epoch(None)
|
| 46 |
+
|
| 47 |
+
def set_epoch(self, epoch, **unused):
|
| 48 |
+
super().set_epoch(epoch)
|
| 49 |
+
self.epoch = epoch
|
| 50 |
+
|
| 51 |
+
@lru_cache(maxsize=16)
|
| 52 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 53 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 54 |
+
assert len(atoms) > 0
|
| 55 |
+
# print("self.dataset[index][self.atoms]")
|
| 56 |
+
# print(self.dataset[index][self.atoms])
|
| 57 |
+
# print("self.dataset[index][self.selfies]")
|
| 58 |
+
# print(self.dataset[index][self.selfies])
|
| 59 |
+
selfies = np.array(self.dataset[index][self.selfies])
|
| 60 |
+
assert len(selfies) > 0
|
| 61 |
+
size = len(self.dataset[index][self.coordinates])
|
| 62 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 63 |
+
sample_idx = np.random.randint(size)
|
| 64 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 65 |
+
return {"atoms": atoms, "selfies": selfies, "coordinates": coordinates.astype(np.float32)}
|
| 66 |
+
|
| 67 |
+
def __getitem__(self, index: int):
|
| 68 |
+
return self.__cached_item__(index, self.epoch)
|
| 69 |
+
|
| 70 |
+
class ConformerSamplePocketDataset(BaseWrapperDataset):
|
| 71 |
+
def __init__(self, dataset, seed, atoms, coordinates, dict_name):
|
| 72 |
+
self.dataset = dataset
|
| 73 |
+
self.seed = seed
|
| 74 |
+
self.atoms = atoms
|
| 75 |
+
self.dict_name = dict_name
|
| 76 |
+
self.coordinates = coordinates
|
| 77 |
+
self.set_epoch(None)
|
| 78 |
+
|
| 79 |
+
def set_epoch(self, epoch, **unused):
|
| 80 |
+
super().set_epoch(epoch)
|
| 81 |
+
self.epoch = epoch
|
| 82 |
+
|
| 83 |
+
@lru_cache(maxsize=16)
|
| 84 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 85 |
+
if self.dict_name == "dict_coarse.txt":
|
| 86 |
+
atoms = np.array([a[0] for a in self.dataset[index][self.atoms]])
|
| 87 |
+
elif self.dict_name == "dict_fine.txt":
|
| 88 |
+
atoms = np.array(
|
| 89 |
+
[
|
| 90 |
+
a[0] if len(a) == 1 or a[0] == "H" else a[:2]
|
| 91 |
+
for a in self.dataset[index][self.atoms]
|
| 92 |
+
]
|
| 93 |
+
)
|
| 94 |
+
assert len(atoms) > 0
|
| 95 |
+
size = len(self.dataset[index][self.coordinates])
|
| 96 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 97 |
+
sample_idx = np.random.randint(size)
|
| 98 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 99 |
+
residue = np.array(self.dataset[index]["residue"])
|
| 100 |
+
score = np.float(self.dataset[index]["meta_info"]["fpocket"]["Score"])
|
| 101 |
+
return {
|
| 102 |
+
"atoms": atoms,
|
| 103 |
+
"coordinates": coordinates.astype(np.float32),
|
| 104 |
+
"residue": residue,
|
| 105 |
+
"score": score,
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
def __getitem__(self, index: int):
|
| 109 |
+
return self.__cached_item__(index, self.epoch)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class ConformerSamplePocketFinetuneDataset(BaseWrapperDataset):
|
| 113 |
+
def __init__(self, dataset, seed, atoms, residues, coordinates):
|
| 114 |
+
self.dataset = dataset
|
| 115 |
+
self.seed = seed
|
| 116 |
+
self.atoms = atoms
|
| 117 |
+
self.residues = residues
|
| 118 |
+
self.coordinates = coordinates
|
| 119 |
+
self.set_epoch(None)
|
| 120 |
+
|
| 121 |
+
def set_epoch(self, epoch, **unused):
|
| 122 |
+
super().set_epoch(epoch)
|
| 123 |
+
self.epoch = epoch
|
| 124 |
+
|
| 125 |
+
@lru_cache(maxsize=16)
|
| 126 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 127 |
+
atoms = np.array(
|
| 128 |
+
[a[0] for a in self.dataset[index][self.atoms]]
|
| 129 |
+
) # only 'C H O N S'
|
| 130 |
+
assert len(atoms) > 0
|
| 131 |
+
# This judgment is reserved for possible future expansion.
|
| 132 |
+
# The number of pocket conformations is 1, and the 'sample' does not work.
|
| 133 |
+
if isinstance(self.dataset[index][self.coordinates], list):
|
| 134 |
+
size = len(self.dataset[index][self.coordinates])
|
| 135 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 136 |
+
sample_idx = np.random.randint(size)
|
| 137 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 138 |
+
else:
|
| 139 |
+
coordinates = self.dataset[index][self.coordinates]
|
| 140 |
+
|
| 141 |
+
if self.residues in self.dataset[index]:
|
| 142 |
+
residues = np.array(self.dataset[index][self.residues])
|
| 143 |
+
else:
|
| 144 |
+
residues = None
|
| 145 |
+
assert len(atoms) == len(coordinates)
|
| 146 |
+
return {
|
| 147 |
+
self.atoms: atoms,
|
| 148 |
+
self.coordinates: coordinates.astype(np.float32),
|
| 149 |
+
self.residues: residues,
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
def __getitem__(self, index: int):
|
| 153 |
+
return self.__cached_item__(index, self.epoch)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class ConformerSampleConfGDataset(BaseWrapperDataset):
|
| 157 |
+
def __init__(self, dataset, seed, atoms, coordinates, tgt_coordinates):
|
| 158 |
+
self.dataset = dataset
|
| 159 |
+
self.seed = seed
|
| 160 |
+
self.atoms = atoms
|
| 161 |
+
self.coordinates = coordinates
|
| 162 |
+
self.tgt_coordinates = tgt_coordinates
|
| 163 |
+
self.set_epoch(None)
|
| 164 |
+
|
| 165 |
+
def set_epoch(self, epoch, **unused):
|
| 166 |
+
super().set_epoch(epoch)
|
| 167 |
+
self.epoch = epoch
|
| 168 |
+
|
| 169 |
+
@lru_cache(maxsize=16)
|
| 170 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 171 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 172 |
+
assert len(atoms) > 0
|
| 173 |
+
size = len(self.dataset[index][self.coordinates])
|
| 174 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 175 |
+
sample_idx = np.random.randint(size)
|
| 176 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 177 |
+
tgt_coordinates = self.dataset[index][self.tgt_coordinates]
|
| 178 |
+
return {
|
| 179 |
+
self.atoms: atoms,
|
| 180 |
+
self.coordinates: coordinates.astype(np.float32),
|
| 181 |
+
self.tgt_coordinates: tgt_coordinates.astype(np.float32),
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
def __getitem__(self, index: int):
|
| 185 |
+
return self.__cached_item__(index, self.epoch)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class ConformerSampleConfGV2Dataset(BaseWrapperDataset):
|
| 189 |
+
def __init__(
|
| 190 |
+
self,
|
| 191 |
+
dataset,
|
| 192 |
+
seed,
|
| 193 |
+
atoms,
|
| 194 |
+
coordinates,
|
| 195 |
+
tgt_coordinates,
|
| 196 |
+
beta=1.0,
|
| 197 |
+
smooth=0.1,
|
| 198 |
+
topN=10,
|
| 199 |
+
):
|
| 200 |
+
self.dataset = dataset
|
| 201 |
+
self.seed = seed
|
| 202 |
+
self.atoms = atoms
|
| 203 |
+
self.coordinates = coordinates
|
| 204 |
+
self.tgt_coordinates = tgt_coordinates
|
| 205 |
+
self.beta = beta
|
| 206 |
+
self.smooth = smooth
|
| 207 |
+
self.topN = topN
|
| 208 |
+
self.set_epoch(None)
|
| 209 |
+
|
| 210 |
+
def set_epoch(self, epoch, **unused):
|
| 211 |
+
super().set_epoch(epoch)
|
| 212 |
+
self.epoch = epoch
|
| 213 |
+
|
| 214 |
+
@lru_cache(maxsize=16)
|
| 215 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 216 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 217 |
+
assert len(atoms) > 0
|
| 218 |
+
meta_df = self.dataset[index]["meta"]
|
| 219 |
+
tgt_conf_ids = meta_df["gid"].unique()
|
| 220 |
+
# randomly choose one conf
|
| 221 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 222 |
+
conf_id = np.random.choice(tgt_conf_ids)
|
| 223 |
+
conf_df = meta_df[meta_df["gid"] == conf_id]
|
| 224 |
+
conf_df = conf_df.sort_values("score").reset_index(drop=False)[
|
| 225 |
+
: self.topN
|
| 226 |
+
] # only use top 5 confs for sampling...
|
| 227 |
+
# importance sampling with rmsd inverse score
|
| 228 |
+
|
| 229 |
+
def normalize(x, beta=1.0, smooth=0.1):
|
| 230 |
+
x = 1.0 / (x**beta + smooth)
|
| 231 |
+
return x / x.sum()
|
| 232 |
+
|
| 233 |
+
rmsd_score = conf_df["score"].values
|
| 234 |
+
weight = normalize(
|
| 235 |
+
rmsd_score, beta=self.beta, smooth=self.smooth
|
| 236 |
+
) # for smoothing purpose
|
| 237 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 238 |
+
idx = np.random.choice(len(conf_df), 1, replace=False, p=weight)
|
| 239 |
+
# idx = [np.argmax(weight)]
|
| 240 |
+
coordinates = conf_df.iloc[idx]["rdkit_coords"].values[0]
|
| 241 |
+
tgt_coordinates = conf_df.iloc[idx]["tgt_coords"].values[0]
|
| 242 |
+
return {
|
| 243 |
+
self.atoms: atoms,
|
| 244 |
+
self.coordinates: coordinates.astype(np.float32),
|
| 245 |
+
self.tgt_coordinates: tgt_coordinates.astype(np.float32),
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
def __getitem__(self, index: int):
|
| 249 |
+
return self.__cached_item__(index, self.epoch)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class ConformerSampleDockingPoseDataset(BaseWrapperDataset):
|
| 253 |
+
def __init__(
|
| 254 |
+
self,
|
| 255 |
+
dataset,
|
| 256 |
+
seed,
|
| 257 |
+
atoms,
|
| 258 |
+
coordinates,
|
| 259 |
+
pocket_atoms,
|
| 260 |
+
pocket_coordinates,
|
| 261 |
+
holo_coordinates,
|
| 262 |
+
holo_pocket_coordinates,
|
| 263 |
+
is_train=True,
|
| 264 |
+
):
|
| 265 |
+
self.dataset = dataset
|
| 266 |
+
self.seed = seed
|
| 267 |
+
self.atoms = atoms
|
| 268 |
+
self.coordinates = coordinates
|
| 269 |
+
self.pocket_atoms = pocket_atoms
|
| 270 |
+
self.pocket_coordinates = pocket_coordinates
|
| 271 |
+
self.holo_coordinates = holo_coordinates
|
| 272 |
+
self.holo_pocket_coordinates = holo_pocket_coordinates
|
| 273 |
+
self.is_train = is_train
|
| 274 |
+
self.set_epoch(None)
|
| 275 |
+
|
| 276 |
+
def set_epoch(self, epoch, **unused):
|
| 277 |
+
super().set_epoch(epoch)
|
| 278 |
+
self.epoch = epoch
|
| 279 |
+
|
| 280 |
+
@lru_cache(maxsize=16)
|
| 281 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 282 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 283 |
+
size = len(self.dataset[index][self.coordinates])
|
| 284 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 285 |
+
sample_idx = np.random.randint(size)
|
| 286 |
+
coordinates = self.dataset[index][self.coordinates][sample_idx]
|
| 287 |
+
pocket_atoms = np.array(
|
| 288 |
+
[item[0] for item in self.dataset[index][self.pocket_atoms]]
|
| 289 |
+
)
|
| 290 |
+
pocket_coordinates = self.dataset[index][self.pocket_coordinates][0]
|
| 291 |
+
if self.is_train:
|
| 292 |
+
holo_coordinates = self.dataset[index][self.holo_coordinates][0]
|
| 293 |
+
holo_pocket_coordinates = self.dataset[index][self.holo_pocket_coordinates][
|
| 294 |
+
0
|
| 295 |
+
]
|
| 296 |
+
else:
|
| 297 |
+
holo_coordinates = coordinates
|
| 298 |
+
holo_pocket_coordinates = pocket_coordinates
|
| 299 |
+
|
| 300 |
+
smi = self.dataset[index]["smi"]
|
| 301 |
+
pocket = self.dataset[index]["pocket"]
|
| 302 |
+
|
| 303 |
+
return {
|
| 304 |
+
"atoms": atoms,
|
| 305 |
+
"coordinates": coordinates.astype(np.float32),
|
| 306 |
+
"pocket_atoms": pocket_atoms,
|
| 307 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 308 |
+
"holo_coordinates": holo_coordinates.astype(np.float32),
|
| 309 |
+
"holo_pocket_coordinates": holo_pocket_coordinates.astype(np.float32),
|
| 310 |
+
"smi": smi,
|
| 311 |
+
"pocket": pocket,
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
def __getitem__(self, index: int):
|
| 315 |
+
return self.__cached_item__(index, self.epoch)
|
data/unimol/data/coord_pad_dataset.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
from unicore.data import BaseWrapperDataset
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def collate_tokens_coords(
|
| 9 |
+
values,
|
| 10 |
+
pad_idx,
|
| 11 |
+
left_pad=False,
|
| 12 |
+
pad_to_length=None,
|
| 13 |
+
pad_to_multiple=1,
|
| 14 |
+
):
|
| 15 |
+
"""Convert a list of 1d tensors into a padded 2d tensor."""
|
| 16 |
+
size = max(v.size(0) for v in values)
|
| 17 |
+
size = size if pad_to_length is None else max(size, pad_to_length)
|
| 18 |
+
if pad_to_multiple != 1 and size % pad_to_multiple != 0:
|
| 19 |
+
size = int(((size - 0.1) // pad_to_multiple + 1) * pad_to_multiple)
|
| 20 |
+
res = values[0].new(len(values), size, 3).fill_(pad_idx)
|
| 21 |
+
|
| 22 |
+
def copy_tensor(src, dst):
|
| 23 |
+
assert dst.numel() == src.numel()
|
| 24 |
+
dst.copy_(src)
|
| 25 |
+
|
| 26 |
+
for i, v in enumerate(values):
|
| 27 |
+
copy_tensor(v, res[i][size - len(v) :, :] if left_pad else res[i][: len(v), :])
|
| 28 |
+
return res
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class RightPadDatasetCoord(BaseWrapperDataset):
|
| 32 |
+
def __init__(self, dataset, pad_idx, left_pad=False):
|
| 33 |
+
super().__init__(dataset)
|
| 34 |
+
self.pad_idx = pad_idx
|
| 35 |
+
self.left_pad = left_pad
|
| 36 |
+
|
| 37 |
+
def collater(self, samples):
|
| 38 |
+
return collate_tokens_coords(
|
| 39 |
+
samples, self.pad_idx, left_pad=self.left_pad, pad_to_multiple=8
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def collate_cross_2d(
|
| 44 |
+
values,
|
| 45 |
+
pad_idx,
|
| 46 |
+
left_pad=False,
|
| 47 |
+
pad_to_length=None,
|
| 48 |
+
pad_to_multiple=1,
|
| 49 |
+
):
|
| 50 |
+
"""Convert a list of 2d tensors into a padded 2d tensor."""
|
| 51 |
+
size_h = max(v.size(0) for v in values)
|
| 52 |
+
size_w = max(v.size(1) for v in values)
|
| 53 |
+
if pad_to_multiple != 1 and size_h % pad_to_multiple != 0:
|
| 54 |
+
size_h = int(((size_h - 0.1) // pad_to_multiple + 1) * pad_to_multiple)
|
| 55 |
+
if pad_to_multiple != 1 and size_w % pad_to_multiple != 0:
|
| 56 |
+
size_w = int(((size_w - 0.1) // pad_to_multiple + 1) * pad_to_multiple)
|
| 57 |
+
res = values[0].new(len(values), size_h, size_w).fill_(pad_idx)
|
| 58 |
+
|
| 59 |
+
def copy_tensor(src, dst):
|
| 60 |
+
assert dst.numel() == src.numel()
|
| 61 |
+
dst.copy_(src)
|
| 62 |
+
|
| 63 |
+
for i, v in enumerate(values):
|
| 64 |
+
copy_tensor(
|
| 65 |
+
v,
|
| 66 |
+
res[i][size_h - v.size(0) :, size_w - v.size(1) :]
|
| 67 |
+
if left_pad
|
| 68 |
+
else res[i][: v.size(0), : v.size(1)],
|
| 69 |
+
)
|
| 70 |
+
return res
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class RightPadDatasetCross2D(BaseWrapperDataset):
|
| 74 |
+
def __init__(self, dataset, pad_idx, left_pad=False):
|
| 75 |
+
super().__init__(dataset)
|
| 76 |
+
self.pad_idx = pad_idx
|
| 77 |
+
self.left_pad = left_pad
|
| 78 |
+
|
| 79 |
+
def collater(self, samples):
|
| 80 |
+
return collate_cross_2d(
|
| 81 |
+
samples, self.pad_idx, left_pad=self.left_pad, pad_to_multiple=8
|
| 82 |
+
)
|
data/unimol/data/cropping_dataset.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
import logging
|
| 8 |
+
from unicore.data import BaseWrapperDataset
|
| 9 |
+
from . import data_utils
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class CroppingDataset(BaseWrapperDataset):
|
| 15 |
+
def __init__(self, dataset, seed, atoms, coordinates, max_atoms=256):
|
| 16 |
+
self.dataset = dataset
|
| 17 |
+
self.seed = seed
|
| 18 |
+
self.atoms = atoms
|
| 19 |
+
self.coordinates = coordinates
|
| 20 |
+
self.max_atoms = max_atoms
|
| 21 |
+
self.set_epoch(None)
|
| 22 |
+
|
| 23 |
+
def set_epoch(self, epoch, **unused):
|
| 24 |
+
super().set_epoch(epoch)
|
| 25 |
+
self.epoch = epoch
|
| 26 |
+
|
| 27 |
+
@lru_cache(maxsize=16)
|
| 28 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 29 |
+
dd = self.dataset[index].copy()
|
| 30 |
+
atoms = dd[self.atoms]
|
| 31 |
+
coordinates = dd[self.coordinates]
|
| 32 |
+
if self.max_atoms and len(atoms) > self.max_atoms:
|
| 33 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 34 |
+
index = np.random.choice(len(atoms), self.max_atoms, replace=False)
|
| 35 |
+
atoms = np.array(atoms)[index]
|
| 36 |
+
coordinates = coordinates[index]
|
| 37 |
+
dd[self.atoms] = atoms
|
| 38 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 39 |
+
return dd
|
| 40 |
+
|
| 41 |
+
def __getitem__(self, index: int):
|
| 42 |
+
return self.__cached_item__(index, self.epoch)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class CroppingPocketDataset(BaseWrapperDataset):
|
| 46 |
+
def __init__(self, dataset, seed, atoms, coordinates, max_atoms=256):
|
| 47 |
+
self.dataset = dataset
|
| 48 |
+
self.seed = seed
|
| 49 |
+
self.atoms = atoms
|
| 50 |
+
self.coordinates = coordinates
|
| 51 |
+
self.max_atoms = (
|
| 52 |
+
max_atoms # max number of atoms in a molecule, None indicates no limit.
|
| 53 |
+
)
|
| 54 |
+
self.set_epoch(None)
|
| 55 |
+
|
| 56 |
+
def set_epoch(self, epoch, **unused):
|
| 57 |
+
super().set_epoch(epoch)
|
| 58 |
+
self.epoch = epoch
|
| 59 |
+
|
| 60 |
+
@lru_cache(maxsize=16)
|
| 61 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 62 |
+
dd = self.dataset[index].copy()
|
| 63 |
+
atoms = dd[self.atoms]
|
| 64 |
+
coordinates = dd[self.coordinates]
|
| 65 |
+
#residue = dd["residue"]
|
| 66 |
+
|
| 67 |
+
# crop atoms according to their distance to the center of pockets
|
| 68 |
+
if self.max_atoms and len(atoms) > self.max_atoms:
|
| 69 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 70 |
+
distance = np.linalg.norm(
|
| 71 |
+
coordinates - coordinates.mean(axis=0), axis=1
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def softmax(x):
|
| 75 |
+
x -= np.max(x)
|
| 76 |
+
x = np.exp(x) / np.sum(np.exp(x))
|
| 77 |
+
return x
|
| 78 |
+
|
| 79 |
+
distance += 1 # prevent inf
|
| 80 |
+
weight = softmax(np.reciprocal(distance))
|
| 81 |
+
index = np.random.choice(
|
| 82 |
+
len(atoms), self.max_atoms, replace=False, p=weight
|
| 83 |
+
)
|
| 84 |
+
atoms = atoms[index]
|
| 85 |
+
coordinates = coordinates[index]
|
| 86 |
+
#residue = residue[index]
|
| 87 |
+
|
| 88 |
+
dd[self.atoms] = atoms
|
| 89 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 90 |
+
#dd["residue"] = residue
|
| 91 |
+
return dd
|
| 92 |
+
|
| 93 |
+
def __getitem__(self, index: int):
|
| 94 |
+
return self.__cached_item__(index, self.epoch)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class CroppingResiduePocketDataset(BaseWrapperDataset):
|
| 98 |
+
def __init__(self, dataset, seed, atoms, residues, coordinates, max_atoms=256):
|
| 99 |
+
self.dataset = dataset
|
| 100 |
+
self.seed = seed
|
| 101 |
+
self.atoms = atoms
|
| 102 |
+
self.residues = residues
|
| 103 |
+
self.coordinates = coordinates
|
| 104 |
+
self.max_atoms = (
|
| 105 |
+
max_atoms # max number of atoms in a molecule, None indicates no limit.
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
self.set_epoch(None)
|
| 109 |
+
|
| 110 |
+
def set_epoch(self, epoch, **unused):
|
| 111 |
+
super().set_epoch(epoch)
|
| 112 |
+
self.epoch = epoch
|
| 113 |
+
|
| 114 |
+
@lru_cache(maxsize=16)
|
| 115 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 116 |
+
dd = self.dataset[index].copy()
|
| 117 |
+
atoms = dd[self.atoms]
|
| 118 |
+
residues = dd[self.residues]
|
| 119 |
+
coordinates = dd[self.coordinates]
|
| 120 |
+
|
| 121 |
+
residues_distance_map = {}
|
| 122 |
+
|
| 123 |
+
# crop atoms according to their distance to the center of pockets
|
| 124 |
+
if self.max_atoms and len(atoms) > self.max_atoms:
|
| 125 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 126 |
+
distance = np.linalg.norm(
|
| 127 |
+
coordinates - coordinates.mean(axis=0), axis=1
|
| 128 |
+
)
|
| 129 |
+
residues_ids, residues_distance = [], []
|
| 130 |
+
for res in residues:
|
| 131 |
+
if res not in residues_ids:
|
| 132 |
+
residues_ids.append(res)
|
| 133 |
+
residues_distance.append(distance[residues == res].mean())
|
| 134 |
+
residues_ids = np.array(residues_ids)
|
| 135 |
+
residues_distance = np.array(residues_distance)
|
| 136 |
+
|
| 137 |
+
def softmax(x):
|
| 138 |
+
x -= np.max(x)
|
| 139 |
+
x = np.exp(x) / np.sum(np.exp(x))
|
| 140 |
+
return x
|
| 141 |
+
|
| 142 |
+
residues_distance += 1 # prevent inf and smoothing out the distance
|
| 143 |
+
weight = softmax(np.reciprocal(residues_distance))
|
| 144 |
+
max_residues = self.max_atoms // (len(atoms) // (len(residues_ids) + 1))
|
| 145 |
+
if max_residues < 1:
|
| 146 |
+
max_residues += 1
|
| 147 |
+
max_residues = min(max_residues, len(residues_ids))
|
| 148 |
+
residue_index = np.random.choice(
|
| 149 |
+
len(residues_ids), max_residues, replace=False, p=weight
|
| 150 |
+
)
|
| 151 |
+
index = [
|
| 152 |
+
i
|
| 153 |
+
for i in range(len(atoms))
|
| 154 |
+
if residues[i] in residues_ids[residue_index]
|
| 155 |
+
]
|
| 156 |
+
atoms = atoms[index]
|
| 157 |
+
coordinates = coordinates[index]
|
| 158 |
+
residues = residues[index]
|
| 159 |
+
|
| 160 |
+
dd[self.atoms] = atoms
|
| 161 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 162 |
+
dd[self.residues] = residues
|
| 163 |
+
return dd
|
| 164 |
+
|
| 165 |
+
def __getitem__(self, index: int):
|
| 166 |
+
return self.__cached_item__(index, self.epoch)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class CroppingPocketDockingPoseDataset(BaseWrapperDataset):
|
| 170 |
+
def __init__(
|
| 171 |
+
self, dataset, seed, atoms, coordinates, holo_coordinates, max_atoms=256
|
| 172 |
+
):
|
| 173 |
+
self.dataset = dataset
|
| 174 |
+
self.seed = seed
|
| 175 |
+
self.atoms = atoms
|
| 176 |
+
self.coordinates = coordinates
|
| 177 |
+
self.max_atoms = max_atoms
|
| 178 |
+
|
| 179 |
+
self.set_epoch(None)
|
| 180 |
+
|
| 181 |
+
def set_epoch(self, epoch, **unused):
|
| 182 |
+
super().set_epoch(epoch)
|
| 183 |
+
self.epoch = epoch
|
| 184 |
+
|
| 185 |
+
@lru_cache(maxsize=16)
|
| 186 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 187 |
+
dd = self.dataset[index].copy()
|
| 188 |
+
atoms = dd[self.atoms]
|
| 189 |
+
coordinates = dd[self.coordinates]
|
| 190 |
+
holo_coordinates = dd[self.holo_coordinates]
|
| 191 |
+
|
| 192 |
+
# crop atoms according to their distance to the center of pockets
|
| 193 |
+
#print(len(atoms))
|
| 194 |
+
if self.max_atoms and len(atoms) > self.max_atoms:
|
| 195 |
+
with data_utils.numpy_seed(self.seed, 1):
|
| 196 |
+
distance = np.linalg.norm(
|
| 197 |
+
coordinates - coordinates.mean(axis=0), axis=1
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
def softmax(x):
|
| 201 |
+
x -= np.max(x)
|
| 202 |
+
x = np.exp(x) / np.sum(np.exp(x))
|
| 203 |
+
return x
|
| 204 |
+
|
| 205 |
+
distance += 1 # prevent inf
|
| 206 |
+
weight = softmax(np.reciprocal(distance))
|
| 207 |
+
index = np.random.choice(
|
| 208 |
+
len(atoms), self.max_atoms, replace=False, p=weight
|
| 209 |
+
)
|
| 210 |
+
atoms = atoms[index]
|
| 211 |
+
coordinates = coordinates[index]
|
| 212 |
+
holo_coordinates = holo_coordinates[index]
|
| 213 |
+
|
| 214 |
+
dd[self.atoms] = atoms
|
| 215 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 216 |
+
dd[self.holo_coordinates] = holo_coordinates.astype(np.float32)
|
| 217 |
+
return dd
|
| 218 |
+
|
| 219 |
+
def __getitem__(self, index: int):
|
| 220 |
+
return self.__cached_item__(index, self.epoch)
|
| 221 |
+
|
| 222 |
+
class CroppingPocketDockingPoseTestDataset(BaseWrapperDataset):
|
| 223 |
+
def __init__(
|
| 224 |
+
self, dataset, seed, atoms, coordinates, max_atoms=256
|
| 225 |
+
):
|
| 226 |
+
self.dataset = dataset
|
| 227 |
+
self.seed = seed
|
| 228 |
+
self.atoms = atoms
|
| 229 |
+
self.coordinates = coordinates
|
| 230 |
+
self.max_atoms = max_atoms
|
| 231 |
+
|
| 232 |
+
self.set_epoch(None)
|
| 233 |
+
|
| 234 |
+
def set_epoch(self, epoch, **unused):
|
| 235 |
+
super().set_epoch(epoch)
|
| 236 |
+
self.epoch = epoch
|
| 237 |
+
|
| 238 |
+
@lru_cache(maxsize=16)
|
| 239 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 240 |
+
dd = self.dataset[index].copy()
|
| 241 |
+
atoms = dd[self.atoms]
|
| 242 |
+
coordinates = dd[self.coordinates]
|
| 243 |
+
|
| 244 |
+
# crop atoms according to their distance to the center of pockets
|
| 245 |
+
if self.max_atoms and len(atoms) > self.max_atoms:
|
| 246 |
+
with data_utils.numpy_seed(1, 1):
|
| 247 |
+
distance = np.linalg.norm(
|
| 248 |
+
coordinates - coordinates.mean(axis=0), axis=1
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
def softmax(x):
|
| 252 |
+
x -= np.max(x)
|
| 253 |
+
x = np.exp(x) / np.sum(np.exp(x))
|
| 254 |
+
return x
|
| 255 |
+
|
| 256 |
+
distance += 1 # prevent inf
|
| 257 |
+
weight = softmax(np.reciprocal(distance))
|
| 258 |
+
index = np.random.choice(
|
| 259 |
+
len(atoms), self.max_atoms, replace=False, p=weight
|
| 260 |
+
)
|
| 261 |
+
atoms = atoms[index]
|
| 262 |
+
coordinates = coordinates[index]
|
| 263 |
+
|
| 264 |
+
dd[self.atoms] = atoms
|
| 265 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 266 |
+
return dd
|
| 267 |
+
|
| 268 |
+
def __getitem__(self, index: int):
|
| 269 |
+
return self.__cached_item__(index, self.epoch)
|
data/unimol/data/data_utils.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import contextlib
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@contextlib.contextmanager
|
| 10 |
+
def numpy_seed(seed, *addl_seeds):
|
| 11 |
+
"""Context manager which seeds the NumPy PRNG with the specified seed and
|
| 12 |
+
restores the state afterward"""
|
| 13 |
+
if seed is None:
|
| 14 |
+
yield
|
| 15 |
+
return
|
| 16 |
+
if len(addl_seeds) > 0:
|
| 17 |
+
seed = int(hash((seed, *addl_seeds)) % 1e6)
|
| 18 |
+
state = np.random.get_state()
|
| 19 |
+
np.random.seed(seed)
|
| 20 |
+
try:
|
| 21 |
+
yield
|
| 22 |
+
finally:
|
| 23 |
+
np.random.set_state(state)
|
data/unimol/data/dictionary.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
|
| 11 |
+
|
| 12 |
+
class DecoderDictionary:
|
| 13 |
+
"""A mapping from symbols to consecutive integers"""
|
| 14 |
+
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
*, # begin keyword-only arguments
|
| 18 |
+
bos="[CLS]",
|
| 19 |
+
pad="[PAD]",
|
| 20 |
+
eos="[SEP]",
|
| 21 |
+
unk="[UNK]",
|
| 22 |
+
extra_special_symbols=None,
|
| 23 |
+
):
|
| 24 |
+
self.bos_word, self.unk_word, self.pad_word, self.eos_word = bos, unk, pad, eos
|
| 25 |
+
self.symbols = []
|
| 26 |
+
self.count = []
|
| 27 |
+
self.indices = {}
|
| 28 |
+
self.idx2sym = {}
|
| 29 |
+
self.specials = set()
|
| 30 |
+
self.specials.add(bos)
|
| 31 |
+
self.specials.add(unk)
|
| 32 |
+
self.specials.add(pad)
|
| 33 |
+
self.specials.add(eos)
|
| 34 |
+
|
| 35 |
+
def __eq__(self, other):
|
| 36 |
+
return self.indices == other.indices
|
| 37 |
+
|
| 38 |
+
def __getitem__(self, idx):
|
| 39 |
+
if idx < len(self.symbols):
|
| 40 |
+
return self.symbols[idx]
|
| 41 |
+
return self.unk_word
|
| 42 |
+
|
| 43 |
+
def __len__(self):
|
| 44 |
+
"""Returns the number of symbols in the dictionary"""
|
| 45 |
+
return len(self.symbols)
|
| 46 |
+
|
| 47 |
+
def __contains__(self, sym):
|
| 48 |
+
return sym in self.indices
|
| 49 |
+
|
| 50 |
+
def vec_index(self, a):
|
| 51 |
+
return np.vectorize(self.index)(a)
|
| 52 |
+
|
| 53 |
+
def index(self, sym):
|
| 54 |
+
"""Returns the index of the specified symbol"""
|
| 55 |
+
assert isinstance(sym, str)
|
| 56 |
+
if sym in self.indices:
|
| 57 |
+
return self.indices[sym]
|
| 58 |
+
return self.indices[self.unk_word]
|
| 59 |
+
|
| 60 |
+
def index2symbol(self, idx):
|
| 61 |
+
"""Returns the corresponding symbol of the specified index"""
|
| 62 |
+
assert isinstance(idx, int)
|
| 63 |
+
if idx in self.idx2sym:
|
| 64 |
+
return self.idx2sym[idx]
|
| 65 |
+
return self.unk_word
|
| 66 |
+
|
| 67 |
+
def special_index(self):
|
| 68 |
+
return [self.index(x) for x in self.specials]
|
| 69 |
+
|
| 70 |
+
def add_symbol(self, word, n=1, overwrite=False, is_special=False):
|
| 71 |
+
"""Adds a word to the dictionary"""
|
| 72 |
+
if is_special:
|
| 73 |
+
self.specials.add(word)
|
| 74 |
+
if word in self.indices and not overwrite:
|
| 75 |
+
idx = self.indices[word]
|
| 76 |
+
self.count[idx] = self.count[idx] + n
|
| 77 |
+
return idx
|
| 78 |
+
else:
|
| 79 |
+
idx = len(self.symbols)
|
| 80 |
+
self.indices[word] = idx
|
| 81 |
+
self.idx2sym[idx] = word
|
| 82 |
+
self.symbols.append(word)
|
| 83 |
+
self.count.append(n)
|
| 84 |
+
return idx
|
| 85 |
+
|
| 86 |
+
def bos(self):
|
| 87 |
+
"""Helper to get index of beginning-of-sentence symbol"""
|
| 88 |
+
return self.index(self.bos_word)
|
| 89 |
+
|
| 90 |
+
def pad(self):
|
| 91 |
+
"""Helper to get index of pad symbol"""
|
| 92 |
+
return self.index(self.pad_word)
|
| 93 |
+
|
| 94 |
+
def eos(self):
|
| 95 |
+
"""Helper to get index of end-of-sentence symbol"""
|
| 96 |
+
return self.index(self.eos_word)
|
| 97 |
+
|
| 98 |
+
def unk(self):
|
| 99 |
+
"""Helper to get index of unk symbol"""
|
| 100 |
+
return self.index(self.unk_word)
|
| 101 |
+
|
| 102 |
+
@classmethod
|
| 103 |
+
def load(cls, f):
|
| 104 |
+
"""Loads the dictionary from a text file with the format:
|
| 105 |
+
|
| 106 |
+
```
|
| 107 |
+
<symbol0> <count0>
|
| 108 |
+
<symbol1> <count1>
|
| 109 |
+
...
|
| 110 |
+
```
|
| 111 |
+
"""
|
| 112 |
+
d = cls()
|
| 113 |
+
d.add_from_file(f)
|
| 114 |
+
return d
|
| 115 |
+
|
| 116 |
+
def add_from_file(self, f):
|
| 117 |
+
"""
|
| 118 |
+
Loads a pre-existing dictionary from a text file and adds its symbols
|
| 119 |
+
to this instance.
|
| 120 |
+
"""
|
| 121 |
+
if isinstance(f, str):
|
| 122 |
+
try:
|
| 123 |
+
with open(f, "r", encoding="utf-8") as fd:
|
| 124 |
+
self.add_from_file(fd)
|
| 125 |
+
except FileNotFoundError as fnfe:
|
| 126 |
+
raise fnfe
|
| 127 |
+
except UnicodeError:
|
| 128 |
+
raise Exception(
|
| 129 |
+
"Incorrect encoding detected in {}, please "
|
| 130 |
+
"rebuild the dataset".format(f)
|
| 131 |
+
)
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
lines = f.readlines()
|
| 135 |
+
|
| 136 |
+
for line_idx, line in enumerate(lines):
|
| 137 |
+
try:
|
| 138 |
+
splits = line.rstrip().rsplit(" ", 1)
|
| 139 |
+
line = splits[0]
|
| 140 |
+
field = splits[1] if len(splits) > 1 else str(len(lines) - line_idx)
|
| 141 |
+
if field == "#overwrite":
|
| 142 |
+
overwrite = True
|
| 143 |
+
line, field = line.rsplit(" ", 1)
|
| 144 |
+
else:
|
| 145 |
+
overwrite = False
|
| 146 |
+
count = int(field)
|
| 147 |
+
word = line
|
| 148 |
+
if word in self and not overwrite:
|
| 149 |
+
logger.info(
|
| 150 |
+
"Duplicate word found when loading Dictionary: '{}', index is {}.".format(word, self.indices[word])
|
| 151 |
+
)
|
| 152 |
+
else:
|
| 153 |
+
self.add_symbol(word, n=count, overwrite=overwrite)
|
| 154 |
+
except ValueError:
|
| 155 |
+
raise ValueError(
|
| 156 |
+
"Incorrect dictionary format, expected '<token> <cnt> [flags]'"
|
| 157 |
+
)
|
data/unimol/data/distance_dataset.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from scipy.spatial import distance_matrix
|
| 8 |
+
from functools import lru_cache
|
| 9 |
+
from unicore.data import BaseWrapperDataset
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class DistanceDataset(BaseWrapperDataset):
|
| 13 |
+
def __init__(self, dataset):
|
| 14 |
+
super().__init__(dataset)
|
| 15 |
+
self.dataset = dataset
|
| 16 |
+
|
| 17 |
+
@lru_cache(maxsize=16)
|
| 18 |
+
def __getitem__(self, idx):
|
| 19 |
+
pos = self.dataset[idx].view(-1, 3).numpy()
|
| 20 |
+
dist = distance_matrix(pos, pos).astype(np.float32)
|
| 21 |
+
return torch.from_numpy(dist)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class EdgeTypeDataset(BaseWrapperDataset):
|
| 25 |
+
def __init__(self, dataset: torch.utils.data.Dataset, num_types: int):
|
| 26 |
+
self.dataset = dataset
|
| 27 |
+
self.num_types = num_types
|
| 28 |
+
|
| 29 |
+
@lru_cache(maxsize=16)
|
| 30 |
+
def __getitem__(self, index: int):
|
| 31 |
+
node_input = self.dataset[index].clone()
|
| 32 |
+
offset = node_input.view(-1, 1) * self.num_types + node_input.view(1, -1)
|
| 33 |
+
return offset
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CrossDistanceDataset(BaseWrapperDataset):
|
| 37 |
+
def __init__(self, mol_dataset, pocket_dataset):
|
| 38 |
+
super().__init__(mol_dataset)
|
| 39 |
+
self.dataset = mol_dataset
|
| 40 |
+
self.mol_dataset = mol_dataset
|
| 41 |
+
self.pocket_dataset = pocket_dataset
|
| 42 |
+
|
| 43 |
+
@lru_cache(maxsize=16)
|
| 44 |
+
def __getitem__(self, idx):
|
| 45 |
+
mol_pos = self.mol_dataset[idx].view(-1, 3).numpy()
|
| 46 |
+
pocket_pos = self.pocket_dataset[idx].view(-1, 3).numpy()
|
| 47 |
+
dist = distance_matrix(mol_pos, pocket_pos).astype(np.float32)
|
| 48 |
+
assert dist.shape[0] == self.mol_dataset[idx].shape[0]
|
| 49 |
+
assert dist.shape[1] == self.pocket_dataset[idx].shape[0]
|
| 50 |
+
return torch.from_numpy(dist)
|
| 51 |
+
|
| 52 |
+
class CrossEdgeTypeDataset(BaseWrapperDataset):
|
| 53 |
+
def __init__(self, mol_dataset, pocket_dataset, num_types: int):
|
| 54 |
+
self.dataset = mol_dataset
|
| 55 |
+
self.mol_dataset = mol_dataset
|
| 56 |
+
self.pocket_dataset = pocket_dataset
|
| 57 |
+
self.num_types = num_types
|
| 58 |
+
|
| 59 |
+
@lru_cache(maxsize=16)
|
| 60 |
+
def __getitem__(self, index: int):
|
| 61 |
+
mol_node_input = self.mol_dataset[index].clone()
|
| 62 |
+
pocket_node_input = self.pocket_dataset[index].clone()
|
| 63 |
+
offset = mol_node_input.view(-1, 1) * self.num_types + pocket_node_input.view(1, -1)
|
| 64 |
+
return offset
|
data/unimol/data/from_str_dataset.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from unicore.data import UnicoreDataset
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class FromStrLabelDataset(UnicoreDataset):
|
| 7 |
+
def __init__(self, labels):
|
| 8 |
+
super().__init__()
|
| 9 |
+
self.labels = labels
|
| 10 |
+
|
| 11 |
+
@lru_cache(maxsize=16)
|
| 12 |
+
def __getitem__(self, index):
|
| 13 |
+
return self.labels[index]
|
| 14 |
+
|
| 15 |
+
def __len__(self):
|
| 16 |
+
return len(self.labels)
|
| 17 |
+
|
| 18 |
+
def collater(self, samples):
|
| 19 |
+
return torch.tensor(list(map(float, samples)))
|
data/unimol/data/key_dataset.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from unicore.data import BaseWrapperDataset
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class KeyDataset(BaseWrapperDataset):
|
| 10 |
+
def __init__(self, dataset, key):
|
| 11 |
+
self.dataset = dataset
|
| 12 |
+
self.key = key
|
| 13 |
+
|
| 14 |
+
def __len__(self):
|
| 15 |
+
return len(self.dataset)
|
| 16 |
+
|
| 17 |
+
@lru_cache(maxsize=16)
|
| 18 |
+
def __getitem__(self, idx):
|
| 19 |
+
return self.dataset[idx][self.key]
|
| 20 |
+
|
| 21 |
+
class LengthDataset(BaseWrapperDataset):
|
| 22 |
+
|
| 23 |
+
def __init__(self, dataset):
|
| 24 |
+
super().__init__(dataset)
|
| 25 |
+
|
| 26 |
+
@lru_cache(maxsize=16)
|
| 27 |
+
def __getitem__(self, idx):
|
| 28 |
+
item = self.dataset[idx]
|
| 29 |
+
return len(item)
|
data/unimol/data/lmdb_dataset.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
import lmdb
|
| 7 |
+
import os
|
| 8 |
+
import pickle
|
| 9 |
+
from functools import lru_cache
|
| 10 |
+
import logging
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class LMDBDataset:
|
| 16 |
+
def __init__(self, db_path):
|
| 17 |
+
self.db_path = db_path
|
| 18 |
+
assert os.path.isfile(self.db_path), "{} not found".format(self.db_path)
|
| 19 |
+
env = self.connect_db(self.db_path)
|
| 20 |
+
with env.begin() as txn:
|
| 21 |
+
self._keys = list(txn.cursor().iternext(values=False))
|
| 22 |
+
|
| 23 |
+
def connect_db(self, lmdb_path, save_to_self=False):
|
| 24 |
+
env = lmdb.open(
|
| 25 |
+
lmdb_path,
|
| 26 |
+
subdir=False,
|
| 27 |
+
readonly=True,
|
| 28 |
+
lock=False,
|
| 29 |
+
readahead=False,
|
| 30 |
+
meminit=False,
|
| 31 |
+
max_readers=256,
|
| 32 |
+
)
|
| 33 |
+
if not save_to_self:
|
| 34 |
+
return env
|
| 35 |
+
else:
|
| 36 |
+
self.env = env
|
| 37 |
+
|
| 38 |
+
def __len__(self):
|
| 39 |
+
return len(self._keys)
|
| 40 |
+
|
| 41 |
+
@lru_cache(maxsize=16)
|
| 42 |
+
def __getitem__(self, idx):
|
| 43 |
+
if not hasattr(self, "env"):
|
| 44 |
+
self.connect_db(self.db_path, save_to_self=True)
|
| 45 |
+
#datapoint_pickled = self.env.begin().get(f"{idx}".encode("ascii"))
|
| 46 |
+
#print(idx)
|
| 47 |
+
datapoint_pickled = self.env.begin().get(f"{idx}".encode("ascii"))
|
| 48 |
+
data = pickle.loads(datapoint_pickled)
|
| 49 |
+
return data
|
data/unimol/data/mask_points_dataset.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from unicore.data import Dictionary
|
| 10 |
+
from unicore.data import BaseWrapperDataset
|
| 11 |
+
from . import data_utils
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class MaskPointsDataset(BaseWrapperDataset):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
dataset: torch.utils.data.Dataset,
|
| 18 |
+
coord_dataset: torch.utils.data.Dataset,
|
| 19 |
+
vocab: Dictionary,
|
| 20 |
+
pad_idx: int,
|
| 21 |
+
mask_idx: int,
|
| 22 |
+
noise_type: str,
|
| 23 |
+
noise: float = 1.0,
|
| 24 |
+
seed: int = 1,
|
| 25 |
+
mask_prob: float = 0.15,
|
| 26 |
+
leave_unmasked_prob: float = 0.1,
|
| 27 |
+
random_token_prob: float = 0.1,
|
| 28 |
+
):
|
| 29 |
+
assert 0.0 < mask_prob < 1.0
|
| 30 |
+
assert 0.0 <= random_token_prob <= 1.0
|
| 31 |
+
assert 0.0 <= leave_unmasked_prob <= 1.0
|
| 32 |
+
assert random_token_prob + leave_unmasked_prob <= 1.0
|
| 33 |
+
|
| 34 |
+
self.dataset = dataset
|
| 35 |
+
self.coord_dataset = coord_dataset
|
| 36 |
+
self.vocab = vocab
|
| 37 |
+
self.pad_idx = pad_idx
|
| 38 |
+
self.mask_idx = mask_idx
|
| 39 |
+
self.noise_type = noise_type
|
| 40 |
+
self.noise = noise
|
| 41 |
+
self.seed = seed
|
| 42 |
+
self.mask_prob = mask_prob
|
| 43 |
+
self.leave_unmasked_prob = leave_unmasked_prob
|
| 44 |
+
self.random_token_prob = random_token_prob
|
| 45 |
+
|
| 46 |
+
if random_token_prob > 0.0:
|
| 47 |
+
weights = np.ones(len(self.vocab))
|
| 48 |
+
weights[vocab.special_index()] = 0
|
| 49 |
+
self.weights = weights / weights.sum()
|
| 50 |
+
|
| 51 |
+
self.epoch = None
|
| 52 |
+
if self.noise_type == "trunc_normal":
|
| 53 |
+
self.noise_f = lambda num_mask: np.clip(
|
| 54 |
+
np.random.randn(num_mask, 3) * self.noise,
|
| 55 |
+
a_min=-self.noise * 2.0,
|
| 56 |
+
a_max=self.noise * 2.0,
|
| 57 |
+
)
|
| 58 |
+
elif self.noise_type == "normal":
|
| 59 |
+
self.noise_f = lambda num_mask: np.random.randn(num_mask, 3) * self.noise
|
| 60 |
+
elif self.noise_type == "uniform":
|
| 61 |
+
self.noise_f = lambda num_mask: np.random.uniform(
|
| 62 |
+
low=-self.noise, high=self.noise, size=(num_mask, 3)
|
| 63 |
+
)
|
| 64 |
+
else:
|
| 65 |
+
self.noise_f = lambda num_mask: 0.0
|
| 66 |
+
|
| 67 |
+
def set_epoch(self, epoch, **unused):
|
| 68 |
+
super().set_epoch(epoch)
|
| 69 |
+
self.coord_dataset.set_epoch(epoch)
|
| 70 |
+
self.dataset.set_epoch(epoch)
|
| 71 |
+
self.epoch = epoch
|
| 72 |
+
|
| 73 |
+
def __getitem__(self, index: int):
|
| 74 |
+
return self.__getitem_cached__(self.epoch, index)
|
| 75 |
+
|
| 76 |
+
@lru_cache(maxsize=16)
|
| 77 |
+
def __getitem_cached__(self, epoch: int, index: int):
|
| 78 |
+
ret = {}
|
| 79 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 80 |
+
item = self.dataset[index]
|
| 81 |
+
coord = self.coord_dataset[index]
|
| 82 |
+
sz = len(item)
|
| 83 |
+
# don't allow empty sequence
|
| 84 |
+
assert sz > 0
|
| 85 |
+
# decide elements to mask
|
| 86 |
+
num_mask = int(
|
| 87 |
+
# add a random number for probabilistic rounding
|
| 88 |
+
self.mask_prob * sz
|
| 89 |
+
+ np.random.rand()
|
| 90 |
+
)
|
| 91 |
+
mask_idc = np.random.choice(sz, num_mask, replace=False)
|
| 92 |
+
mask = np.full(sz, False)
|
| 93 |
+
mask[mask_idc] = True
|
| 94 |
+
ret["targets"] = np.full(len(mask), self.pad_idx)
|
| 95 |
+
ret["targets"][mask] = item[mask]
|
| 96 |
+
ret["targets"] = torch.from_numpy(ret["targets"]).long()
|
| 97 |
+
# decide unmasking and random replacement
|
| 98 |
+
rand_or_unmask_prob = self.random_token_prob + self.leave_unmasked_prob
|
| 99 |
+
if rand_or_unmask_prob > 0.0:
|
| 100 |
+
rand_or_unmask = mask & (np.random.rand(sz) < rand_or_unmask_prob)
|
| 101 |
+
if self.random_token_prob == 0.0:
|
| 102 |
+
unmask = rand_or_unmask
|
| 103 |
+
rand_mask = None
|
| 104 |
+
elif self.leave_unmasked_prob == 0.0:
|
| 105 |
+
unmask = None
|
| 106 |
+
rand_mask = rand_or_unmask
|
| 107 |
+
else:
|
| 108 |
+
unmask_prob = self.leave_unmasked_prob / rand_or_unmask_prob
|
| 109 |
+
decision = np.random.rand(sz) < unmask_prob
|
| 110 |
+
unmask = rand_or_unmask & decision
|
| 111 |
+
rand_mask = rand_or_unmask & (~decision)
|
| 112 |
+
else:
|
| 113 |
+
unmask = rand_mask = None
|
| 114 |
+
|
| 115 |
+
if unmask is not None:
|
| 116 |
+
mask = mask ^ unmask
|
| 117 |
+
|
| 118 |
+
new_item = np.copy(item)
|
| 119 |
+
new_item[mask] = self.mask_idx
|
| 120 |
+
|
| 121 |
+
num_mask = mask.astype(np.int32).sum()
|
| 122 |
+
new_coord = np.copy(coord)
|
| 123 |
+
new_coord[mask, :] += self.noise_f(num_mask)
|
| 124 |
+
|
| 125 |
+
if rand_mask is not None:
|
| 126 |
+
num_rand = rand_mask.sum()
|
| 127 |
+
if num_rand > 0:
|
| 128 |
+
new_item[rand_mask] = np.random.choice(
|
| 129 |
+
len(self.vocab),
|
| 130 |
+
num_rand,
|
| 131 |
+
p=self.weights,
|
| 132 |
+
)
|
| 133 |
+
ret["atoms"] = torch.from_numpy(new_item).long()
|
| 134 |
+
ret["coordinates"] = torch.from_numpy(new_coord).float()
|
| 135 |
+
return ret
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class MaskPointsPocketDataset(BaseWrapperDataset):
|
| 139 |
+
def __init__(
|
| 140 |
+
self,
|
| 141 |
+
dataset: torch.utils.data.Dataset,
|
| 142 |
+
coord_dataset: torch.utils.data.Dataset,
|
| 143 |
+
residue_dataset: torch.utils.data.Dataset,
|
| 144 |
+
vocab: Dictionary,
|
| 145 |
+
pad_idx: int,
|
| 146 |
+
mask_idx: int,
|
| 147 |
+
noise_type: str,
|
| 148 |
+
noise: float = 1.0,
|
| 149 |
+
seed: int = 1,
|
| 150 |
+
mask_prob: float = 0.15,
|
| 151 |
+
leave_unmasked_prob: float = 0.1,
|
| 152 |
+
random_token_prob: float = 0.1,
|
| 153 |
+
):
|
| 154 |
+
assert 0.0 < mask_prob < 1.0
|
| 155 |
+
assert 0.0 <= random_token_prob <= 1.0
|
| 156 |
+
assert 0.0 <= leave_unmasked_prob <= 1.0
|
| 157 |
+
assert random_token_prob + leave_unmasked_prob <= 1.0
|
| 158 |
+
|
| 159 |
+
self.dataset = dataset
|
| 160 |
+
self.coord_dataset = coord_dataset
|
| 161 |
+
self.residue_dataset = residue_dataset
|
| 162 |
+
self.vocab = vocab
|
| 163 |
+
self.pad_idx = pad_idx
|
| 164 |
+
self.mask_idx = mask_idx
|
| 165 |
+
self.noise_type = noise_type
|
| 166 |
+
self.noise = noise
|
| 167 |
+
self.seed = seed
|
| 168 |
+
self.mask_prob = mask_prob
|
| 169 |
+
self.leave_unmasked_prob = leave_unmasked_prob
|
| 170 |
+
self.random_token_prob = random_token_prob
|
| 171 |
+
|
| 172 |
+
if random_token_prob > 0.0:
|
| 173 |
+
weights = np.ones(len(self.vocab))
|
| 174 |
+
weights[vocab.special_index()] = 0
|
| 175 |
+
self.weights = weights / weights.sum()
|
| 176 |
+
|
| 177 |
+
self.epoch = None
|
| 178 |
+
if self.noise_type == "trunc_normal":
|
| 179 |
+
self.noise_f = lambda num_mask: np.clip(
|
| 180 |
+
np.random.randn(num_mask, 3) * self.noise,
|
| 181 |
+
a_min=-self.noise * 2.0,
|
| 182 |
+
a_max=self.noise * 2.0,
|
| 183 |
+
)
|
| 184 |
+
elif self.noise_type == "normal":
|
| 185 |
+
self.noise_f = lambda num_mask: np.random.randn(num_mask, 3) * self.noise
|
| 186 |
+
elif self.noise_type == "uniform":
|
| 187 |
+
self.noise_f = lambda num_mask: np.random.uniform(
|
| 188 |
+
low=-self.noise, high=self.noise, size=(num_mask, 3)
|
| 189 |
+
)
|
| 190 |
+
else:
|
| 191 |
+
self.noise_f = lambda num_mask: 0.0
|
| 192 |
+
|
| 193 |
+
def set_epoch(self, epoch, **unused):
|
| 194 |
+
super().set_epoch(epoch)
|
| 195 |
+
self.coord_dataset.set_epoch(epoch)
|
| 196 |
+
self.dataset.set_epoch(epoch)
|
| 197 |
+
self.epoch = epoch
|
| 198 |
+
|
| 199 |
+
def __getitem__(self, index: int):
|
| 200 |
+
return self.__getitem_cached__(self.epoch, index)
|
| 201 |
+
|
| 202 |
+
@lru_cache(maxsize=16)
|
| 203 |
+
def __getitem_cached__(self, epoch: int, index: int):
|
| 204 |
+
ret = {}
|
| 205 |
+
with data_utils.numpy_seed(self.seed, epoch, index):
|
| 206 |
+
item = self.dataset[index]
|
| 207 |
+
coord = self.coord_dataset[index]
|
| 208 |
+
sz = len(item)
|
| 209 |
+
# don't allow empty sequence
|
| 210 |
+
assert sz > 0
|
| 211 |
+
|
| 212 |
+
# mask on the level of residues
|
| 213 |
+
residue = self.residue_dataset[index]
|
| 214 |
+
res_list = list(set(residue))
|
| 215 |
+
res_sz = len(res_list)
|
| 216 |
+
|
| 217 |
+
# decide elements to mask
|
| 218 |
+
num_mask = int(
|
| 219 |
+
# add a random number for probabilistic rounding
|
| 220 |
+
self.mask_prob * res_sz
|
| 221 |
+
+ np.random.rand()
|
| 222 |
+
)
|
| 223 |
+
mask_res = np.random.choice(res_list, num_mask, replace=False).tolist()
|
| 224 |
+
mask = np.isin(residue, mask_res)
|
| 225 |
+
|
| 226 |
+
ret["targets"] = np.full(len(mask), self.pad_idx)
|
| 227 |
+
ret["targets"][mask] = item[mask]
|
| 228 |
+
ret["targets"] = torch.from_numpy(ret["targets"]).long()
|
| 229 |
+
# decide unmasking and random replacement
|
| 230 |
+
rand_or_unmask_prob = self.random_token_prob + self.leave_unmasked_prob
|
| 231 |
+
if rand_or_unmask_prob > 0.0:
|
| 232 |
+
rand_or_unmask = mask & (np.random.rand(sz) < rand_or_unmask_prob)
|
| 233 |
+
if self.random_token_prob == 0.0:
|
| 234 |
+
unmask = rand_or_unmask
|
| 235 |
+
rand_mask = None
|
| 236 |
+
elif self.leave_unmasked_prob == 0.0:
|
| 237 |
+
unmask = None
|
| 238 |
+
rand_mask = rand_or_unmask
|
| 239 |
+
else:
|
| 240 |
+
unmask_prob = self.leave_unmasked_prob / rand_or_unmask_prob
|
| 241 |
+
decision = np.random.rand(sz) < unmask_prob
|
| 242 |
+
unmask = rand_or_unmask & decision
|
| 243 |
+
rand_mask = rand_or_unmask & (~decision)
|
| 244 |
+
else:
|
| 245 |
+
unmask = rand_mask = None
|
| 246 |
+
|
| 247 |
+
if unmask is not None:
|
| 248 |
+
mask = mask ^ unmask
|
| 249 |
+
|
| 250 |
+
new_item = np.copy(item)
|
| 251 |
+
new_item[mask] = self.mask_idx
|
| 252 |
+
|
| 253 |
+
num_mask = mask.astype(np.int32).sum()
|
| 254 |
+
new_coord = np.copy(coord)
|
| 255 |
+
new_coord[mask, :] += self.noise_f(num_mask)
|
| 256 |
+
|
| 257 |
+
if rand_mask is not None:
|
| 258 |
+
num_rand = rand_mask.sum()
|
| 259 |
+
if num_rand > 0:
|
| 260 |
+
new_item[rand_mask] = np.random.choice(
|
| 261 |
+
len(self.vocab),
|
| 262 |
+
num_rand,
|
| 263 |
+
p=self.weights,
|
| 264 |
+
)
|
| 265 |
+
ret["atoms"] = torch.from_numpy(new_item).long()
|
| 266 |
+
ret["coordinates"] = torch.from_numpy(new_coord).float()
|
| 267 |
+
return ret
|
data/unimol/data/normalize_dataset.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from unicore.data import BaseWrapperDataset
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class NormalizeDataset(BaseWrapperDataset):
|
| 11 |
+
def __init__(self, dataset, coordinates, normalize_coord=True):
|
| 12 |
+
self.dataset = dataset
|
| 13 |
+
self.coordinates = coordinates
|
| 14 |
+
self.normalize_coord = normalize_coord # normalize the coordinates.
|
| 15 |
+
self.set_epoch(None)
|
| 16 |
+
|
| 17 |
+
def set_epoch(self, epoch, **unused):
|
| 18 |
+
super().set_epoch(epoch)
|
| 19 |
+
self.epoch = epoch
|
| 20 |
+
|
| 21 |
+
@lru_cache(maxsize=16)
|
| 22 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 23 |
+
dd = self.dataset[index].copy()
|
| 24 |
+
coordinates = dd[self.coordinates]
|
| 25 |
+
# normalize
|
| 26 |
+
if self.normalize_coord:
|
| 27 |
+
coordinates = coordinates - coordinates.mean(axis=0)
|
| 28 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 29 |
+
return dd
|
| 30 |
+
|
| 31 |
+
def __getitem__(self, index: int):
|
| 32 |
+
return self.__cached_item__(index, self.epoch)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class NormalizeDockingPoseDataset(BaseWrapperDataset):
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
dataset,
|
| 39 |
+
coordinates,
|
| 40 |
+
pocket_coordinates,
|
| 41 |
+
center_coordinates="center_coordinates",
|
| 42 |
+
):
|
| 43 |
+
self.dataset = dataset
|
| 44 |
+
self.coordinates = coordinates
|
| 45 |
+
self.pocket_coordinates = pocket_coordinates
|
| 46 |
+
self.center_coordinates = center_coordinates
|
| 47 |
+
self.set_epoch(None)
|
| 48 |
+
|
| 49 |
+
def set_epoch(self, epoch, **unused):
|
| 50 |
+
super().set_epoch(epoch)
|
| 51 |
+
self.epoch = epoch
|
| 52 |
+
|
| 53 |
+
@lru_cache(maxsize=16)
|
| 54 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 55 |
+
dd = self.dataset[index].copy()
|
| 56 |
+
coordinates = dd[self.coordinates]
|
| 57 |
+
pocket_coordinates = dd[self.pocket_coordinates]
|
| 58 |
+
# normalize coordinates and pocket coordinates ,align with pocket center coordinates
|
| 59 |
+
center_coordinates = pocket_coordinates.mean(axis=0)
|
| 60 |
+
coordinates = coordinates - center_coordinates
|
| 61 |
+
pocket_coordinates = pocket_coordinates - center_coordinates
|
| 62 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 63 |
+
dd[self.pocket_coordinates] = pocket_coordinates.astype(np.float32)
|
| 64 |
+
dd[self.center_coordinates] = center_coordinates.astype(np.float32)
|
| 65 |
+
return dd
|
| 66 |
+
|
| 67 |
+
def __getitem__(self, index: int):
|
| 68 |
+
return self.__cached_item__(index, self.epoch)
|
data/unimol/data/plasma_utils.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import json
|
| 3 |
+
import subprocess
|
| 4 |
+
import tempfile
|
| 5 |
+
from typing import Hashable
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
import pyarrow.plasma as plasma
|
| 9 |
+
|
| 10 |
+
PYARROW_AVAILABLE = True
|
| 11 |
+
except ImportError:
|
| 12 |
+
plasma = None
|
| 13 |
+
PYARROW_AVAILABLE = False
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class PlasmaArray:
|
| 17 |
+
"""
|
| 18 |
+
Wrapper around numpy arrays that automatically moves the data to shared
|
| 19 |
+
memory upon serialization. This is particularly helpful when passing numpy
|
| 20 |
+
arrays through multiprocessing, so that data is not unnecessarily
|
| 21 |
+
duplicated or pickled.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, array):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.array = array
|
| 27 |
+
self.disable = array.nbytes < 134217728 # disable for arrays <128MB
|
| 28 |
+
self.object_id = None
|
| 29 |
+
self.path = None
|
| 30 |
+
|
| 31 |
+
# variables with underscores shouldn't be pickled
|
| 32 |
+
self._client = None
|
| 33 |
+
self._server = None
|
| 34 |
+
self._server_tmp = None
|
| 35 |
+
self._plasma = None
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def plasma(self):
|
| 39 |
+
if self._plasma is None and not self.disable:
|
| 40 |
+
self._plasma = plasma
|
| 41 |
+
return self._plasma
|
| 42 |
+
|
| 43 |
+
def start_server(self):
|
| 44 |
+
if self.plasma is None or self._server is not None:
|
| 45 |
+
return
|
| 46 |
+
assert self.object_id is None
|
| 47 |
+
assert self.path is None
|
| 48 |
+
self._server_tmp = tempfile.NamedTemporaryFile()
|
| 49 |
+
self.path = self._server_tmp.name
|
| 50 |
+
self._server = subprocess.Popen(
|
| 51 |
+
["plasma_store", "-m", str(int(1.05 * self.array.nbytes)), "-s", self.path]
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
@property
|
| 55 |
+
def client(self):
|
| 56 |
+
if self._client is None:
|
| 57 |
+
assert self.path is not None
|
| 58 |
+
self._client = self.plasma.connect(self.path, num_retries=200)
|
| 59 |
+
return self._client
|
| 60 |
+
|
| 61 |
+
def __getstate__(self):
|
| 62 |
+
"""Called on pickle load"""
|
| 63 |
+
if self.plasma is None:
|
| 64 |
+
return self.__dict__
|
| 65 |
+
if self.object_id is None:
|
| 66 |
+
self.start_server()
|
| 67 |
+
self.object_id = self.client.put(self.array)
|
| 68 |
+
state = self.__dict__.copy()
|
| 69 |
+
del state["array"]
|
| 70 |
+
state["_client"] = None
|
| 71 |
+
state["_server"] = None
|
| 72 |
+
state["_server_tmp"] = None
|
| 73 |
+
state["_plasma"] = None
|
| 74 |
+
return state
|
| 75 |
+
|
| 76 |
+
def __setstate__(self, state):
|
| 77 |
+
"""Called on pickle save"""
|
| 78 |
+
self.__dict__.update(state)
|
| 79 |
+
if self.plasma is None:
|
| 80 |
+
return
|
| 81 |
+
self.array = self.client.get(self.object_id)
|
| 82 |
+
|
| 83 |
+
def __del__(self):
|
| 84 |
+
if self._server is not None:
|
| 85 |
+
self._server.kill()
|
| 86 |
+
self._server = None
|
| 87 |
+
self._server_tmp.close()
|
| 88 |
+
self._server_tmp = None
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
DEFAULT_PLASMA_PATH = "/tmp/plasma"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class PlasmaView:
|
| 95 |
+
"""Interface to write and read from shared memory. Whereas PlasmaArray writes to plasma on serialization,
|
| 96 |
+
PlasmaView writes to shared memory on instantiation."""
|
| 97 |
+
|
| 98 |
+
def __init__(self, array, split_path: str, hash_data: Hashable, plasma_path=None):
|
| 99 |
+
"""
|
| 100 |
+
Args:
|
| 101 |
+
array: numpy array to store. This can be read with ``PlasmaView().array``
|
| 102 |
+
split_path: the path whence the data was read, used for hashing
|
| 103 |
+
hash_data: other metadata about the array that can be used to create a unique key.
|
| 104 |
+
as of writing, the 3 callers in ``TokenBlockDataset`` use::
|
| 105 |
+
hash_data = ((block_size, document_sep_len, str(break_mode), len(dataset)), 0|1|2)
|
| 106 |
+
"""
|
| 107 |
+
assert PYARROW_AVAILABLE
|
| 108 |
+
assert split_path is not None
|
| 109 |
+
if plasma_path is None:
|
| 110 |
+
plasma_path = DEFAULT_PLASMA_PATH
|
| 111 |
+
|
| 112 |
+
self.path = plasma_path
|
| 113 |
+
self.split_path = split_path
|
| 114 |
+
self._client = None # Initialize lazily for pickle. plasma clients should not be deep copied or serialized.
|
| 115 |
+
self._n = None
|
| 116 |
+
|
| 117 |
+
self.object_id = self.get_object_id(self.split_path, hash_data)
|
| 118 |
+
try:
|
| 119 |
+
self.client.put(array, object_id=self.object_id)
|
| 120 |
+
except plasma.PlasmaObjectExists:
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def client(self):
|
| 125 |
+
if self._client is None:
|
| 126 |
+
self._client = plasma.connect(self.path, num_retries=200)
|
| 127 |
+
return self._client
|
| 128 |
+
|
| 129 |
+
@property
|
| 130 |
+
def array(self):
|
| 131 |
+
"""Fetch a read only view of an np.array, stored in plasma."""
|
| 132 |
+
ret = self.client.get(self.object_id)
|
| 133 |
+
return ret
|
| 134 |
+
|
| 135 |
+
@staticmethod
|
| 136 |
+
def get_object_id(split_path: str, hash_data: Hashable):
|
| 137 |
+
"""Returns plasma.ObjectID from hashing split_path and object_num."""
|
| 138 |
+
hash = hashlib.blake2b(bytes(split_path, "utf-8"), digest_size=20)
|
| 139 |
+
harg = json.dumps(hash_data).encode("utf-8")
|
| 140 |
+
hash.update(harg)
|
| 141 |
+
return plasma.ObjectID(hash.digest())
|
| 142 |
+
|
| 143 |
+
def __getstate__(self):
|
| 144 |
+
"""Called on pickle save"""
|
| 145 |
+
self.disconnect()
|
| 146 |
+
state = self.__dict__.copy()
|
| 147 |
+
assert state["_client"] is None
|
| 148 |
+
assert "object_id" in state
|
| 149 |
+
return state
|
| 150 |
+
|
| 151 |
+
def __setstate__(self, state):
|
| 152 |
+
"""Called on pickle load"""
|
| 153 |
+
self.__dict__.update(state)
|
| 154 |
+
|
| 155 |
+
def __del__(self):
|
| 156 |
+
self.disconnect()
|
| 157 |
+
|
| 158 |
+
def disconnect(self):
|
| 159 |
+
if self._client is not None:
|
| 160 |
+
self._client.disconnect()
|
| 161 |
+
self._client = None
|
| 162 |
+
|
| 163 |
+
def __len__(self):
|
| 164 |
+
"""Save reads by caching len"""
|
| 165 |
+
if self._n is None:
|
| 166 |
+
self._n = len(self.array)
|
| 167 |
+
return self._n
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
GB100 = (1024**3) * 100
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class PlasmaStore:
|
| 174 |
+
def __init__(self, path=DEFAULT_PLASMA_PATH, nbytes: int = GB100):
|
| 175 |
+
|
| 176 |
+
self.server = self.start(path, nbytes)
|
| 177 |
+
|
| 178 |
+
def __del__(self):
|
| 179 |
+
self.server.kill()
|
| 180 |
+
|
| 181 |
+
@staticmethod
|
| 182 |
+
def start(path=DEFAULT_PLASMA_PATH, nbytes: int = GB100) -> subprocess.Popen:
|
| 183 |
+
if not PYARROW_AVAILABLE:
|
| 184 |
+
raise ImportError("please run pip install pyarrow to use --use_plasma_view")
|
| 185 |
+
# best practice is to allocate more space than we need. The limitation seems to be the size of /dev/shm
|
| 186 |
+
_server = subprocess.Popen(["plasma_store", "-m", str(nbytes), "-s", path])
|
| 187 |
+
plasma.connect(path, num_retries=200) # If we can't connect we fail immediately
|
| 188 |
+
return _server
|
data/unimol/data/pocket2mol_dataset.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
import sys
|
| 3 |
+
import pickle
|
| 4 |
+
import random
|
| 5 |
+
import networkx as nx
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import rdkit
|
| 9 |
+
from rdkit import Chem
|
| 10 |
+
from rdkit.Chem import AllChem
|
| 11 |
+
sys.path.append('..')
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from unicore.data import BaseWrapperDataset
|
| 15 |
+
|
| 16 |
+
from . import data_utils
|
| 17 |
+
from unimol.utils import geom
|
| 18 |
+
|
| 19 |
+
def gen_conformation(mol, num_conf=20, num_worker=8, keepHs=False):
|
| 20 |
+
try:
|
| 21 |
+
mol = Chem.AddHs(mol)
|
| 22 |
+
AllChem.EmbedMultipleConfs(mol, numConfs=num_conf, numThreads=num_worker, pruneRmsThresh=0.1, maxAttempts=5, useRandomCoords=False)
|
| 23 |
+
AllChem.MMFFOptimizeMoleculeConfs(mol, numThreads=num_worker)
|
| 24 |
+
if not keepHs:
|
| 25 |
+
mol = Chem.RemoveHs(mol)
|
| 26 |
+
return mol
|
| 27 |
+
except:
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
class FragmentConformationDataset(BaseWrapperDataset):
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
dataset,
|
| 34 |
+
seed,
|
| 35 |
+
vocab,
|
| 36 |
+
conf_vocab,
|
| 37 |
+
use_pocket=True,
|
| 38 |
+
is_train=True
|
| 39 |
+
):
|
| 40 |
+
self.dataset = dataset
|
| 41 |
+
self.seed = seed
|
| 42 |
+
self.use_pocket = use_pocket
|
| 43 |
+
self.conf_vocab = Vocabulary(vocab, conf_vocab)
|
| 44 |
+
self.is_train = is_train
|
| 45 |
+
self.set_epoch(None)
|
| 46 |
+
|
| 47 |
+
def set_epoch(self, epoch, **unused):
|
| 48 |
+
super().set_epoch(epoch)
|
| 49 |
+
self.epoch = epoch
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def parse_frag_mol(self, frag_mol):
|
| 53 |
+
atom_types = [a.GetSymbol() for a in frag_mol.GetAtoms()]
|
| 54 |
+
atom_coords = np.array(frag_mol.GetConformer(0).GetPositions())
|
| 55 |
+
return {'atom_types': atom_types, 'atom_coords': atom_coords}
|
| 56 |
+
|
| 57 |
+
def parse_frag_idx(self, vocab_conf, full_mol, atom_map):
|
| 58 |
+
if vocab_conf.GetNumConformers() == 0:
|
| 59 |
+
smi = Chem.MolToSmiles(vocab_conf)
|
| 60 |
+
vocab_conf = Chem.MolFromSmiles(smi)
|
| 61 |
+
vocab_conf = gen_conformation(vocab_conf, num_conf=1, num_worker=1, keepHs=True)
|
| 62 |
+
mol = Chem.RWMol(full_mol)
|
| 63 |
+
atom_idx = list(range(full_mol.GetNumAtoms()))
|
| 64 |
+
for i, atom in enumerate(full_mol.GetAtoms()):
|
| 65 |
+
if atom.GetAtomMapNum() not in atom_map:
|
| 66 |
+
atom_idx[i] = -1
|
| 67 |
+
for i in range(len(atom_idx) - 1, -1, -1):
|
| 68 |
+
if atom_idx[i] == -1:
|
| 69 |
+
mol.RemoveAtom(i)
|
| 70 |
+
mol = mol.GetMol()
|
| 71 |
+
#mol = Chem.RemoveHs(mol)
|
| 72 |
+
smi = Chem.MolToSmiles(mol)
|
| 73 |
+
#find the map num in smiles
|
| 74 |
+
map_num = []
|
| 75 |
+
smi_p = smi.split('[')
|
| 76 |
+
for i in range(1, len(smi_p)):
|
| 77 |
+
if ':' in smi_p[i]:
|
| 78 |
+
end_idx = smi_p[i].split(':')[1].index(']')
|
| 79 |
+
map_num.append(int(smi_p[i].split(':')[1][:end_idx]))
|
| 80 |
+
|
| 81 |
+
vocab_conf = Chem.RemoveHs(vocab_conf)
|
| 82 |
+
for i, atom in enumerate(vocab_conf.GetAtoms()):
|
| 83 |
+
if atom.GetSymbol() != 'H':
|
| 84 |
+
atom.SetAtomMapNum(map_num[i])
|
| 85 |
+
vocab_conf = Chem.AddHs(vocab_conf, addCoords=True)
|
| 86 |
+
|
| 87 |
+
if torch.isnan(torch.from_numpy(np.array(vocab_conf.GetConformer(0).GetPositions()))).any():
|
| 88 |
+
vocab_conf = gen_conformation(vocab_conf, num_conf=1, num_worker=1, keepHs=True)
|
| 89 |
+
|
| 90 |
+
return vocab_conf
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def pocket_atom(self, atom):
|
| 94 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 95 |
+
return atom[1]
|
| 96 |
+
else:
|
| 97 |
+
return atom[0]
|
| 98 |
+
|
| 99 |
+
def check_leaf(self, edges, index):
|
| 100 |
+
out_degree = 0
|
| 101 |
+
for edge in edges:
|
| 102 |
+
if edge[0] == index:
|
| 103 |
+
out_degree += 1
|
| 104 |
+
if out_degree == 0:
|
| 105 |
+
return True
|
| 106 |
+
else:
|
| 107 |
+
return False
|
| 108 |
+
|
| 109 |
+
def pocket_atom(self, atom):
|
| 110 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 111 |
+
return atom[1]
|
| 112 |
+
else:
|
| 113 |
+
return atom[0]
|
| 114 |
+
|
| 115 |
+
def check_leaf(self, edges, index):
|
| 116 |
+
out_degree = 0
|
| 117 |
+
for edge in edges:
|
| 118 |
+
if edge[0] == index:
|
| 119 |
+
out_degree += 1
|
| 120 |
+
if out_degree == 0:
|
| 121 |
+
return True
|
| 122 |
+
else:
|
| 123 |
+
return False
|
| 124 |
+
|
| 125 |
+
@lru_cache(maxsize=16)
|
| 126 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 127 |
+
|
| 128 |
+
random.seed(self.seed + epoch)
|
| 129 |
+
#pocket
|
| 130 |
+
if self.use_pocket:
|
| 131 |
+
pocket_atoms = np.array(
|
| 132 |
+
[self.pocket_atom(item) for item in self.dataset[index]['pocket_atom']]
|
| 133 |
+
)
|
| 134 |
+
pocket_coordinates = np.stack(self.dataset[index]['pocket_coord'])
|
| 135 |
+
|
| 136 |
+
full_mol = self.dataset[index]['frags']['mol']
|
| 137 |
+
|
| 138 |
+
frag_graph = nx.Graph()
|
| 139 |
+
edges = self.dataset[index]['frags']['frag_edges']
|
| 140 |
+
frag_graph.add_edges_from(np.array(edges))
|
| 141 |
+
if len(edges) == 0:
|
| 142 |
+
frag_mol_idx = self.dataset[index]['frags']['frag_idx'][0]
|
| 143 |
+
frag_mol = self.conf_vocab.conf[frag_mol_idx]
|
| 144 |
+
f_mol_noH_num = len([atom for atom in frag_mol.GetAtoms() if atom.GetSymbol() != 'H'])
|
| 145 |
+
frag_mol = Chem.AddHs(frag_mol, addCoords=True)
|
| 146 |
+
frag_mol_data = self.parse_frag_mol(frag_mol)
|
| 147 |
+
return {
|
| 148 |
+
'atom_types': np.array([], dtype=str),
|
| 149 |
+
'atom_coords': np.zeros((1, 3), dtype=np.float32),
|
| 150 |
+
'focal_atom_local': 0,#place holder
|
| 151 |
+
'attach_atom_local': 0,#place holder
|
| 152 |
+
'focal_atom': 0,#place holder
|
| 153 |
+
'attach_atom': 0,#place holder
|
| 154 |
+
'frag_atom_types': frag_mol_data['atom_types'],
|
| 155 |
+
'frag_atom_coords': frag_mol_data['atom_coords'],
|
| 156 |
+
'end': True,
|
| 157 |
+
'torsion_output_prev': 0,#place holder
|
| 158 |
+
'coords_input_prev': frag_mol_data['atom_coords'],
|
| 159 |
+
'atom_types_withfocal': frag_mol_data['atom_types'],
|
| 160 |
+
'pocket_atoms': pocket_atoms,
|
| 161 |
+
'pocket_coordinates': pocket_coordinates,
|
| 162 |
+
'first': True,
|
| 163 |
+
'symmetric': True
|
| 164 |
+
}
|
| 165 |
+
bfs_edges = list(nx.bfs_edges(frag_graph, 0))
|
| 166 |
+
#reorder the link and local link
|
| 167 |
+
link = self.dataset[index]['frags']['links']
|
| 168 |
+
local_link = self.dataset[index]['frags']['links_local']
|
| 169 |
+
reorrder_link, reorrder_local_link = [], []
|
| 170 |
+
for i, b_edge in enumerate(bfs_edges):
|
| 171 |
+
for j, o_edge in enumerate(edges):
|
| 172 |
+
if b_edge[0] == o_edge[0] and b_edge[1] == o_edge[1]:
|
| 173 |
+
reorrder_link.append(link[j])
|
| 174 |
+
reorrder_local_link.append(local_link[j])
|
| 175 |
+
elif b_edge[0] == o_edge[1] and b_edge[1] == o_edge[0]:
|
| 176 |
+
reorrder_link.append([link[j][1], link[j][0]])
|
| 177 |
+
reorrder_local_link.append([local_link[j][1], local_link[j][0]])
|
| 178 |
+
self.dataset[index]['frags']['links'] = reorrder_link
|
| 179 |
+
self.dataset[index]['frags']['links_local'] = reorrder_local_link
|
| 180 |
+
#clip a random subgraph
|
| 181 |
+
bfs_edges_full = bfs_edges.copy()
|
| 182 |
+
clip_step = random.randint(0, len(bfs_edges))
|
| 183 |
+
#print('clip_step', clip_step)
|
| 184 |
+
start_frag = bfs_edges[0][0]
|
| 185 |
+
if clip_step != 0:
|
| 186 |
+
bfs_edges = bfs_edges[:clip_step]
|
| 187 |
+
focal_frag, attach_frag = bfs_edges[-1]
|
| 188 |
+
else:
|
| 189 |
+
focal_frag, attach_frag = bfs_edges[0]
|
| 190 |
+
|
| 191 |
+
for i, atom in enumerate(full_mol.GetAtoms()):
|
| 192 |
+
atom.SetAtomMapNum(i + 1)
|
| 193 |
+
|
| 194 |
+
end = (clip_step == len(bfs_edges_full))
|
| 195 |
+
if clip_step == 0:
|
| 196 |
+
#frag
|
| 197 |
+
#print('first frag')
|
| 198 |
+
frag_mol_idx = self.dataset[index]['frags']['frag_idx'][start_frag]
|
| 199 |
+
frag_mol = self.conf_vocab.conf[frag_mol_idx]
|
| 200 |
+
if frag_mol is None:
|
| 201 |
+
print(frag_mol_idx, 'is None')
|
| 202 |
+
frag_mol = self.parse_frag_idx(frag_mol, full_mol, self.dataset[index]['frags']['map'][start_frag])
|
| 203 |
+
frag_mol_data = self.parse_frag_mol(frag_mol)
|
| 204 |
+
return {
|
| 205 |
+
'atom_types': np.array([], dtype=str),
|
| 206 |
+
'atom_coords': np.zeros((1, 3), dtype=np.float32),
|
| 207 |
+
'focal_atom_local': 0,#place holder
|
| 208 |
+
'attach_atom_local': 0,#place holder
|
| 209 |
+
'focal_atom': 0,#place holder
|
| 210 |
+
'attach_atom': 0,#place holder
|
| 211 |
+
'frag_atom_types': frag_mol_data['atom_types'],
|
| 212 |
+
'frag_atom_coords': frag_mol_data['atom_coords'],
|
| 213 |
+
'end': end,
|
| 214 |
+
'torsion_output_prev': 0,#place holder
|
| 215 |
+
'coords_input_prev': frag_mol_data['atom_coords'],
|
| 216 |
+
'atom_types_withfocal': frag_mol_data['atom_types'],
|
| 217 |
+
'pocket_atoms': pocket_atoms,
|
| 218 |
+
'pocket_coordinates': pocket_coordinates,
|
| 219 |
+
'first': True,
|
| 220 |
+
'symmetric': True
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
clip_frag_idx = [e[0] for e in bfs_edges] + [e[1] for e in bfs_edges[:-1]]
|
| 225 |
+
clip_frag_idx = np.unique(clip_frag_idx)
|
| 226 |
+
frag_attach_idx = bfs_edges[-1][1]
|
| 227 |
+
clip_map = []
|
| 228 |
+
for i in range(len(clip_frag_idx)):
|
| 229 |
+
clip_map.extend(self.dataset[index]['frags']['map'][clip_frag_idx[i]])
|
| 230 |
+
clip_map_attach = clip_map + self.dataset[index]['frags']['map'][frag_attach_idx]
|
| 231 |
+
#print('frag_node_map', self.dataset[index]['frags']['map'])
|
| 232 |
+
|
| 233 |
+
#get part mol
|
| 234 |
+
part_mol = Chem.RWMol(full_mol)
|
| 235 |
+
atom_idx = list(range(full_mol.GetNumAtoms()))
|
| 236 |
+
for i, atom in enumerate(full_mol.GetAtoms()):
|
| 237 |
+
if atom.GetSymbol() == 'H':
|
| 238 |
+
#remove if neighbor is not in clip_map
|
| 239 |
+
neighbor_atom = [atom.GetAtomMapNum() for atom in part_mol.GetAtomWithIdx(i).GetNeighbors()]
|
| 240 |
+
neighbor_map = [atom.GetAtomMapNum() for atom in part_mol.GetAtomWithIdx(i).GetNeighbors()][0]
|
| 241 |
+
if neighbor_map not in clip_map:
|
| 242 |
+
atom_idx[i] = -1
|
| 243 |
+
if atom.GetAtomMapNum() not in clip_map:
|
| 244 |
+
atom_idx[i] = -1
|
| 245 |
+
else:
|
| 246 |
+
if atom.GetAtomMapNum() not in clip_map:
|
| 247 |
+
atom_idx[i] = -1
|
| 248 |
+
for i in range(len(atom_idx) - 1, -1, -1):
|
| 249 |
+
if atom_idx[i] == -1:
|
| 250 |
+
part_mol.RemoveAtom(i)
|
| 251 |
+
|
| 252 |
+
frag_exp_link = []
|
| 253 |
+
for i in range(len(clip_frag_idx)):
|
| 254 |
+
for e_d, e in enumerate(bfs_edges_full):
|
| 255 |
+
if e[0] == clip_frag_idx[i] and e[1] not in clip_frag_idx:
|
| 256 |
+
frag_exp_link.append(self.dataset[index]['frags']['links'][e_d][0])
|
| 257 |
+
for link_mp in frag_exp_link:
|
| 258 |
+
add_map = [i for i, atom in enumerate(part_mol.GetAtoms()) if atom.GetAtomMapNum() == link_mp][0]
|
| 259 |
+
part_mol.AddAtom(Chem.Atom(1))
|
| 260 |
+
part_mol.AddBond(add_map, part_mol.GetNumAtoms() - 1, Chem.rdchem.BondType.SINGLE)
|
| 261 |
+
part_mol = part_mol.GetMol()
|
| 262 |
+
part_mol = Chem.RemoveHs(part_mol)
|
| 263 |
+
part_mol = Chem.AddHs(part_mol, addCoords=True)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
part_mol_atom_types = [atom.GetSymbol() for atom in part_mol.GetAtoms()]
|
| 267 |
+
part_mol_atom_coords = np.array([part_mol.GetConformer().GetAtomPosition(i) for i in range(part_mol.GetNumAtoms())])
|
| 268 |
+
|
| 269 |
+
#get part mol with attach
|
| 270 |
+
part_mol_attach = Chem.RWMol(full_mol)
|
| 271 |
+
atom_idx = list(range(full_mol.GetNumAtoms()))
|
| 272 |
+
for i, atom in enumerate(full_mol.GetAtoms()):
|
| 273 |
+
if full_mol.GetAtomWithIdx(i).GetSymbol() == 'H':
|
| 274 |
+
#remove if neighbor is not in clip_map
|
| 275 |
+
neighbor = [atom.GetAtomMapNum() for atom in part_mol_attach.GetAtomWithIdx(i).GetNeighbors()][0]
|
| 276 |
+
if neighbor not in clip_map_attach:
|
| 277 |
+
atom_idx[i] = -1
|
| 278 |
+
else:
|
| 279 |
+
if atom.GetAtomMapNum() not in clip_map_attach:
|
| 280 |
+
atom_idx[i] = -1
|
| 281 |
+
#print([i for i, idx in enumerate(atom_idx) if idx == -1])
|
| 282 |
+
for i in range(len(atom_idx) - 1, -1, -1):
|
| 283 |
+
if atom_idx[i] == -1:
|
| 284 |
+
part_mol_attach.RemoveAtom(i)
|
| 285 |
+
#if not self.check_leaf(edges, frag_attach_idx):
|
| 286 |
+
frag_exp_link = []
|
| 287 |
+
clip_frag_attach_idx = list(clip_frag_idx) + [frag_attach_idx]
|
| 288 |
+
for i in range(len(clip_frag_attach_idx)):
|
| 289 |
+
for e_d, e in enumerate(bfs_edges_full):
|
| 290 |
+
if e[0] == clip_frag_attach_idx[i] and e[1] not in clip_frag_attach_idx:
|
| 291 |
+
frag_exp_link.append(self.dataset[index]['frags']['links'][e_d][0])
|
| 292 |
+
for link_mp in frag_exp_link:
|
| 293 |
+
add_map = [i for i, atom in enumerate(part_mol_attach.GetAtoms()) if atom.GetAtomMapNum() == link_mp][0]
|
| 294 |
+
part_mol_attach.AddAtom(Chem.Atom(1))
|
| 295 |
+
part_mol_attach.AddBond(add_map, part_mol_attach.GetNumAtoms() - 1, Chem.rdchem.BondType.SINGLE)
|
| 296 |
+
#print('add H atom symbol', part_mol_attach.GetAtomWithIdx(add_map).GetSymbol())
|
| 297 |
+
#else:
|
| 298 |
+
# print('leaf node')
|
| 299 |
+
part_mol_attach = part_mol_attach.GetMol()
|
| 300 |
+
part_mol_attach = Chem.RemoveHs(part_mol_attach)
|
| 301 |
+
part_mol_attach = Chem.AddHs(part_mol_attach, addCoords=True)
|
| 302 |
+
|
| 303 |
+
part_mol_attach_atom_types = [atom.GetSymbol() for atom in part_mol_attach.GetAtoms()]
|
| 304 |
+
part_mol_attach_atom_coords = np.array([part_mol_attach.GetConformer().GetAtomPosition(i) for i in range(part_mol_attach.GetNumAtoms())])
|
| 305 |
+
'''
|
| 306 |
+
part_mol_atom = [self.dataset[index]['frags']['map'][e[0]] for e in bfs_edges] + \
|
| 307 |
+
[self.dataset[index]['frags']['map'][e[1]] for e in bfs_edges[:-1]]
|
| 308 |
+
part_mol_atom = np.concatenate(part_mol_atom, axis=0)
|
| 309 |
+
part_mol_atom = np.unique(part_mol_atom)
|
| 310 |
+
part_mol_atom_types = self.dataset[index]['atom_types'][part_mol_atom]
|
| 311 |
+
part_mol_atom_coords = self.dataset[index]['atom_coords'][part_mol_atom]
|
| 312 |
+
'''
|
| 313 |
+
|
| 314 |
+
'''
|
| 315 |
+
#add focal atom
|
| 316 |
+
part_mol_atom_withfocal = [self.dataset[index]['frags']['map'][e[0]] for e in bfs_edges] + \
|
| 317 |
+
[self.dataset[index]['frags']['map'][e[1]] for e in bfs_edges]
|
| 318 |
+
part_mol_atom_withfocal = np.concatenate(part_mol_atom_withfocal, axis=0)
|
| 319 |
+
part_mol_atom_withfocal = np.unique(part_mol_atom_withfocal)
|
| 320 |
+
part_mol_atom_types_withfocal = self.dataset[index]['atom_types'][part_mol_atom_withfocal]
|
| 321 |
+
part_mol_atom_coords_withfocal = self.dataset[index]['atom_coords'][part_mol_atom_withfocal]
|
| 322 |
+
'''
|
| 323 |
+
focal_atom_local = [i for i, atom in enumerate(part_mol.GetAtoms()) if atom.GetAtomMapNum() == self.dataset[index]['frags']['links'][clip_step - 1][0]][0]
|
| 324 |
+
focal_atom = [i for i, atom in enumerate(part_mol_attach.GetAtoms()) if atom.GetAtomMapNum() == self.dataset[index]['frags']['links'][clip_step - 1][0]][0]
|
| 325 |
+
#focal_atom = self.dataset[index]['frags']['map'][focal_frag][focal_atom_local]
|
| 326 |
+
|
| 327 |
+
#frag
|
| 328 |
+
frag_mol_idx = self.dataset[index]['frags']['frag_idx'][attach_frag]
|
| 329 |
+
frag_mol = self.conf_vocab.conf[frag_mol_idx]
|
| 330 |
+
|
| 331 |
+
frag_mol = self.parse_frag_idx(frag_mol, self.dataset[index]['frags']['mol'], self.dataset[index]['frags']['map'][attach_frag])
|
| 332 |
+
frag_mol_data = self.parse_frag_mol(frag_mol)
|
| 333 |
+
|
| 334 |
+
if frag_mol is None:
|
| 335 |
+
print(frag_mol_idx, 'is None')
|
| 336 |
+
|
| 337 |
+
attach_atom_local = [i for i, atom in enumerate(frag_mol.GetAtoms()) if atom.GetAtomMapNum() == self.dataset[index]['frags']['links'][clip_step - 1][1]][0]
|
| 338 |
+
attach_atom = [i for i, atom in enumerate(part_mol_attach.GetAtoms()) if atom.GetAtomMapNum() == self.dataset[index]['frags']['links'][clip_step - 1][1]][0]
|
| 339 |
+
#attach_atom = self.dataset[index]['frags']['map'][bfs_edges[-1][1]][attach_atom_local]
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
#torsion angles
|
| 343 |
+
#prev_edge = bfs_edges[-1]
|
| 344 |
+
'''
|
| 345 |
+
prev_link_local = self.dataset[index]['frags']['link_atoms'][bfs_edges.index(prev_edge) - 1]
|
| 346 |
+
prev_link = (self.dataset[index]['frags']['map'][prev_edge[0]][prev_link_local[0]],
|
| 347 |
+
self.dataset[index]['frags']['map'][prev_edge[1]][prev_link_local[1]])
|
| 348 |
+
index_rotate = [prev_link[1]] + self.dataset[index]['frags']['map'][focal_frag]
|
| 349 |
+
index_parent = np.concatenate([self.dataset[index]['frags']['map'][e[0]] for e in bfs_edges[:-1]], axis=0) + [prev_link[0]]
|
| 350 |
+
'''
|
| 351 |
+
index_rotate = [i for i, atom in enumerate(part_mol_attach.GetAtoms()) if atom.GetAtomMapNum() in self.dataset[index]['frags']['map'][attach_frag]]
|
| 352 |
+
index_rotate.remove(attach_atom)
|
| 353 |
+
index_rotate = [attach_atom] + index_rotate
|
| 354 |
+
index_parent = []
|
| 355 |
+
for e in bfs_edges[:-1]:
|
| 356 |
+
index_parent += self.dataset[index]['frags']['map'][e[0]]
|
| 357 |
+
index_parent += self.dataset[index]['frags']['map'][e[1]]
|
| 358 |
+
index_parent += self.dataset[index]['frags']['map'][focal_frag]
|
| 359 |
+
index_parent = list(np.unique(index_parent))
|
| 360 |
+
index_parent = [i for i, atom in enumerate(part_mol_attach.GetAtoms()) if atom.GetAtomMapNum() in index_parent]
|
| 361 |
+
index_parent.remove(focal_atom)
|
| 362 |
+
index_parent = index_parent + [focal_atom]
|
| 363 |
+
#add hydrogen
|
| 364 |
+
# get the hydrogen that connects to the rotate atoms
|
| 365 |
+
index_rotate_h = []
|
| 366 |
+
for i in index_rotate:
|
| 367 |
+
for j in part_mol_attach.GetAtomWithIdx(i).GetNeighbors():
|
| 368 |
+
if j.GetAtomicNum() == 1:
|
| 369 |
+
index_rotate_h.append(j.GetIdx())
|
| 370 |
+
index_rotate += index_rotate_h
|
| 371 |
+
# get the hydrogen that connects to the parent atoms
|
| 372 |
+
index_parent_h = []
|
| 373 |
+
for i in index_parent:
|
| 374 |
+
for j in part_mol_attach.GetAtomWithIdx(i).GetNeighbors():
|
| 375 |
+
if j.GetAtomicNum() == 1:
|
| 376 |
+
index_parent_h.append(j.GetIdx())
|
| 377 |
+
index_parent = index_parent_h + index_parent
|
| 378 |
+
coords_input_prev, torsion_output_prev = geom.change_torsion(part_mol_attach_atom_coords, [index_parent, index_rotate])
|
| 379 |
+
symmetric = (len(index_rotate) == 0 )
|
| 380 |
+
|
| 381 |
+
return {
|
| 382 |
+
'atom_types': part_mol_atom_types,
|
| 383 |
+
'atom_coords': part_mol_atom_coords,
|
| 384 |
+
'focal_atom_local': focal_atom_local,
|
| 385 |
+
'attach_atom_local': attach_atom_local,
|
| 386 |
+
'focal_atom': focal_atom,
|
| 387 |
+
'attach_atom': attach_atom,
|
| 388 |
+
'frag_atom_types': frag_mol_data['atom_types'],
|
| 389 |
+
'frag_atom_coords': frag_mol_data['atom_coords'],
|
| 390 |
+
'end': end,
|
| 391 |
+
'torsion_output_prev': torsion_output_prev,
|
| 392 |
+
'coords_input_prev': coords_input_prev,
|
| 393 |
+
'atom_types_withfocal': part_mol_attach_atom_types,
|
| 394 |
+
'pocket_atoms': pocket_atoms,
|
| 395 |
+
'pocket_coordinates': pocket_coordinates,
|
| 396 |
+
'first': False,
|
| 397 |
+
'symmetric': symmetric
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
def __getitem__(self, index: int):
|
| 401 |
+
item = self.__cached_item__(index, self.epoch)
|
| 402 |
+
return item
|
| 403 |
+
|
data/unimol/data/prepend_and_append_2d_dataset.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from unicore.data import BaseWrapperDataset
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class PrependAndAppend2DDataset(BaseWrapperDataset):
|
| 11 |
+
def __init__(self, dataset, token=None):
|
| 12 |
+
super().__init__(dataset)
|
| 13 |
+
self.token = token
|
| 14 |
+
|
| 15 |
+
@lru_cache(maxsize=16)
|
| 16 |
+
def __getitem__(self, idx):
|
| 17 |
+
item = self.dataset[idx]
|
| 18 |
+
if self.token is not None:
|
| 19 |
+
h, w = item.size(-2), item.size(-1)
|
| 20 |
+
new_item = torch.full((h + 2, w + 2), self.token).type_as(item)
|
| 21 |
+
new_item[1:-1, 1:-1] = item
|
| 22 |
+
return new_item
|
| 23 |
+
return item
|
data/unimol/data/remove_hydrogen_dataset.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from unicore.data import BaseWrapperDataset
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class DockRemoveHydrogenDataset(BaseWrapperDataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
dataset,
|
| 14 |
+
atoms,
|
| 15 |
+
coordinates,
|
| 16 |
+
docked_coordinates,
|
| 17 |
+
remove_hydrogen=False,
|
| 18 |
+
remove_polar_hydrogen=False,
|
| 19 |
+
):
|
| 20 |
+
self.dataset = dataset
|
| 21 |
+
self.atoms = atoms
|
| 22 |
+
self.coordinates = coordinates
|
| 23 |
+
self.docked_coordinates = docked_coordinates
|
| 24 |
+
self.remove_hydrogen = remove_hydrogen
|
| 25 |
+
self.remove_polar_hydrogen = remove_polar_hydrogen
|
| 26 |
+
self.set_epoch(None)
|
| 27 |
+
|
| 28 |
+
def set_epoch(self, epoch, **unused):
|
| 29 |
+
super().set_epoch(epoch)
|
| 30 |
+
self.epoch = epoch
|
| 31 |
+
|
| 32 |
+
@lru_cache(maxsize=16)
|
| 33 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 34 |
+
dd = self.dataset[index].copy()
|
| 35 |
+
atoms = dd[self.atoms]
|
| 36 |
+
coordinates = dd[self.coordinates]
|
| 37 |
+
docked = dd[self.docked_coordinates]
|
| 38 |
+
|
| 39 |
+
if self.remove_hydrogen:
|
| 40 |
+
mask_hydrogen = atoms != "H"
|
| 41 |
+
atoms = atoms[mask_hydrogen]
|
| 42 |
+
#print(coordinates.shape)
|
| 43 |
+
coordinates = coordinates[mask_hydrogen]
|
| 44 |
+
docked = docked[mask_hydrogen]
|
| 45 |
+
if not self.remove_hydrogen and self.remove_polar_hydrogen:
|
| 46 |
+
end_idx = 0
|
| 47 |
+
for i, atom in enumerate(atoms[::-1]):
|
| 48 |
+
if atom != "H":
|
| 49 |
+
break
|
| 50 |
+
else:
|
| 51 |
+
end_idx = i + 1
|
| 52 |
+
if end_idx != 0:
|
| 53 |
+
atoms = atoms[:-end_idx]
|
| 54 |
+
coordinates = coordinates[:-end_idx]
|
| 55 |
+
docked = docked[:-end_idx]
|
| 56 |
+
dd[self.atoms] = atoms
|
| 57 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 58 |
+
dd[self.docked_coordinates] = docked.astype(np.float32)
|
| 59 |
+
return dd
|
| 60 |
+
|
| 61 |
+
def __getitem__(self, index: int):
|
| 62 |
+
return self.__cached_item__(index, self.epoch)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class RemoveHydrogenDataset(BaseWrapperDataset):
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
dataset,
|
| 70 |
+
atoms,
|
| 71 |
+
coordinates,
|
| 72 |
+
remove_hydrogen=False,
|
| 73 |
+
remove_polar_hydrogen=False,
|
| 74 |
+
):
|
| 75 |
+
self.dataset = dataset
|
| 76 |
+
self.atoms = atoms
|
| 77 |
+
self.coordinates = coordinates
|
| 78 |
+
self.remove_hydrogen = remove_hydrogen
|
| 79 |
+
self.remove_polar_hydrogen = remove_polar_hydrogen
|
| 80 |
+
self.set_epoch(None)
|
| 81 |
+
|
| 82 |
+
def set_epoch(self, epoch, **unused):
|
| 83 |
+
super().set_epoch(epoch)
|
| 84 |
+
self.epoch = epoch
|
| 85 |
+
|
| 86 |
+
@lru_cache(maxsize=16)
|
| 87 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 88 |
+
dd = self.dataset[index].copy()
|
| 89 |
+
atoms = dd[self.atoms]
|
| 90 |
+
coordinates = dd[self.coordinates]
|
| 91 |
+
|
| 92 |
+
if self.remove_hydrogen:
|
| 93 |
+
mask_hydrogen = atoms != "H"
|
| 94 |
+
atoms = atoms[mask_hydrogen]
|
| 95 |
+
#print(coordinates.shape)
|
| 96 |
+
coordinates = coordinates[mask_hydrogen]
|
| 97 |
+
if not self.remove_hydrogen and self.remove_polar_hydrogen:
|
| 98 |
+
end_idx = 0
|
| 99 |
+
for i, atom in enumerate(atoms[::-1]):
|
| 100 |
+
if atom != "H":
|
| 101 |
+
break
|
| 102 |
+
else:
|
| 103 |
+
end_idx = i + 1
|
| 104 |
+
if end_idx != 0:
|
| 105 |
+
atoms = atoms[:-end_idx]
|
| 106 |
+
coordinates = coordinates[:-end_idx]
|
| 107 |
+
dd[self.atoms] = atoms
|
| 108 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 109 |
+
return dd
|
| 110 |
+
|
| 111 |
+
def __getitem__(self, index: int):
|
| 112 |
+
return self.__cached_item__(index, self.epoch)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class RemoveHydrogenResiduePocketDataset(BaseWrapperDataset):
|
| 116 |
+
def __init__(self, dataset, atoms, residues, coordinates, remove_hydrogen=True):
|
| 117 |
+
self.dataset = dataset
|
| 118 |
+
self.atoms = atoms
|
| 119 |
+
self.residues = residues
|
| 120 |
+
self.coordinates = coordinates
|
| 121 |
+
self.remove_hydrogen = remove_hydrogen
|
| 122 |
+
self.set_epoch(None)
|
| 123 |
+
|
| 124 |
+
def set_epoch(self, epoch, **unused):
|
| 125 |
+
super().set_epoch(epoch)
|
| 126 |
+
self.epoch = epoch
|
| 127 |
+
|
| 128 |
+
@lru_cache(maxsize=16)
|
| 129 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 130 |
+
dd = self.dataset[index].copy()
|
| 131 |
+
atoms = dd[self.atoms]
|
| 132 |
+
residues = dd[self.residues]
|
| 133 |
+
coordinates = dd[self.coordinates]
|
| 134 |
+
if len(atoms) != len(residues):
|
| 135 |
+
min_len = min(len(atoms), len(residues))
|
| 136 |
+
atoms = atoms[:min_len]
|
| 137 |
+
residues = residues[:min_len]
|
| 138 |
+
coordinates = coordinates[:min_len, :]
|
| 139 |
+
|
| 140 |
+
if self.remove_hydrogen:
|
| 141 |
+
mask_hydrogen = atoms != "H"
|
| 142 |
+
atoms = atoms[mask_hydrogen]
|
| 143 |
+
residues = residues[mask_hydrogen]
|
| 144 |
+
coordinates = coordinates[mask_hydrogen]
|
| 145 |
+
|
| 146 |
+
dd[self.atoms] = atoms
|
| 147 |
+
dd[self.residues] = residues
|
| 148 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 149 |
+
return dd
|
| 150 |
+
|
| 151 |
+
def __getitem__(self, index: int):
|
| 152 |
+
return self.__cached_item__(index, self.epoch)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class RemoveHydrogenPocketDataset(BaseWrapperDataset):
|
| 156 |
+
def __init__(
|
| 157 |
+
self,
|
| 158 |
+
dataset,
|
| 159 |
+
atoms,
|
| 160 |
+
coordinates,
|
| 161 |
+
remove_hydrogen=True,
|
| 162 |
+
remove_polar_hydrogen=False,
|
| 163 |
+
):
|
| 164 |
+
self.dataset = dataset
|
| 165 |
+
self.atoms = atoms
|
| 166 |
+
self.coordinates = coordinates
|
| 167 |
+
self.remove_hydrogen = remove_hydrogen
|
| 168 |
+
self.remove_polar_hydrogen = remove_polar_hydrogen
|
| 169 |
+
self.set_epoch(None)
|
| 170 |
+
|
| 171 |
+
def set_epoch(self, epoch, **unused):
|
| 172 |
+
super().set_epoch(epoch)
|
| 173 |
+
self.epoch = epoch
|
| 174 |
+
|
| 175 |
+
@lru_cache(maxsize=16)
|
| 176 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 177 |
+
dd = self.dataset[index].copy()
|
| 178 |
+
atoms = dd[self.atoms]
|
| 179 |
+
coordinates = dd[self.coordinates]
|
| 180 |
+
|
| 181 |
+
if self.remove_hydrogen:
|
| 182 |
+
mask_hydrogen = atoms != "H"
|
| 183 |
+
atoms = atoms[mask_hydrogen]
|
| 184 |
+
coordinates = coordinates[mask_hydrogen]
|
| 185 |
+
if not self.remove_hydrogen and self.remove_polar_hydrogen:
|
| 186 |
+
end_idx = 0
|
| 187 |
+
for i, atom in enumerate(atoms[::-1]):
|
| 188 |
+
if atom != "H":
|
| 189 |
+
break
|
| 190 |
+
else:
|
| 191 |
+
end_idx = i + 1
|
| 192 |
+
if end_idx != 0:
|
| 193 |
+
atoms = atoms[:-end_idx]
|
| 194 |
+
coordinates = coordinates[:-end_idx]
|
| 195 |
+
dd[self.atoms] = atoms
|
| 196 |
+
dd[self.coordinates] = coordinates.astype(np.float32)
|
| 197 |
+
return dd
|
| 198 |
+
|
| 199 |
+
def __getitem__(self, index: int):
|
| 200 |
+
return self.__cached_item__(index, self.epoch)
|
data/unimol/data/resampling_dataset.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from unicore.data import BaseWrapperDataset
|
| 6 |
+
from .plasma_utils import PlasmaArray
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ResamplingDataset(BaseWrapperDataset):
|
| 13 |
+
"""Randomly samples from a given dataset at each epoch.
|
| 14 |
+
Sampling is done with or without replacement, depending on the "replace"
|
| 15 |
+
parameter.
|
| 16 |
+
Optionally, the epoch size can be rescaled. This is potentially desirable
|
| 17 |
+
to increase per-epoch coverage of the base dataset (since sampling with
|
| 18 |
+
replacement means that many items in the dataset will be left out). In the
|
| 19 |
+
case of sampling without replacement, size_ratio should be strictly less
|
| 20 |
+
than 1.
|
| 21 |
+
Args:
|
| 22 |
+
dataset (~torch.utils.data.Dataset): dataset on which to sample.
|
| 23 |
+
weights (List[float]): list of probability weights
|
| 24 |
+
(default: None, which corresponds to uniform sampling).
|
| 25 |
+
replace (bool): sampling mode; True for "with replacement", or False
|
| 26 |
+
for "without replacement" (default: True)
|
| 27 |
+
size_ratio (float): the ratio to subsample to; must be positive
|
| 28 |
+
(default: 1.0).
|
| 29 |
+
batch_by_size (bool): whether or not to batch by sequence length
|
| 30 |
+
(default: True).
|
| 31 |
+
seed (int): RNG seed to use (default: 0).
|
| 32 |
+
epoch (int): starting epoch number (default: 1).
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
dataset,
|
| 38 |
+
replace=False,
|
| 39 |
+
size_ratio=1.0,
|
| 40 |
+
batch_by_size=True,
|
| 41 |
+
seed=0,
|
| 42 |
+
epoch=1,
|
| 43 |
+
):
|
| 44 |
+
super().__init__(dataset)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
self.replace = replace
|
| 49 |
+
|
| 50 |
+
self.size_ratio = float(size_ratio)
|
| 51 |
+
self.actual_size = np.ceil(len(dataset) * self.size_ratio).astype(int)
|
| 52 |
+
|
| 53 |
+
self.seed = seed
|
| 54 |
+
|
| 55 |
+
self._cur_epoch = None
|
| 56 |
+
self._cur_indices = None
|
| 57 |
+
|
| 58 |
+
self.set_epoch(epoch)
|
| 59 |
+
|
| 60 |
+
def __getitem__(self, index):
|
| 61 |
+
return self.dataset[self._cur_indices.array[index]]
|
| 62 |
+
|
| 63 |
+
def __len__(self):
|
| 64 |
+
return self.actual_size
|
| 65 |
+
|
| 66 |
+
@property
|
| 67 |
+
def sizes(self):
|
| 68 |
+
if isinstance(self.dataset.sizes, list):
|
| 69 |
+
return [s[self._cur_indices.array] for s in self.dataset.sizes]
|
| 70 |
+
return self.dataset.sizes[self._cur_indices.array]
|
| 71 |
+
|
| 72 |
+
def num_tokens(self, index):
|
| 73 |
+
return self.dataset.num_tokens(self._cur_indices.array[index])
|
| 74 |
+
|
| 75 |
+
def size(self, index):
|
| 76 |
+
return self.dataset.size(self._cur_indices.array[index])
|
| 77 |
+
|
| 78 |
+
def ordered_indices(self):
|
| 79 |
+
return np.arange(len(self))
|
| 80 |
+
|
| 81 |
+
def prefetch(self, indices):
|
| 82 |
+
self.dataset.prefetch(self._cur_indices.array[indices])
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def can_reuse_epoch_itr_across_epochs(self):
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
def set_epoch(self, epoch):
|
| 89 |
+
# log
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
logger.info("ResamplingDataset.set_epoch: {}".format(epoch))
|
| 93 |
+
super().set_epoch(epoch)
|
| 94 |
+
|
| 95 |
+
if epoch == self._cur_epoch:
|
| 96 |
+
return
|
| 97 |
+
|
| 98 |
+
self._cur_epoch = epoch
|
| 99 |
+
|
| 100 |
+
# Generate a weighted sample of indices as a function of the
|
| 101 |
+
# random seed and the current epoch.
|
| 102 |
+
|
| 103 |
+
rng = np.random.RandomState(
|
| 104 |
+
[
|
| 105 |
+
42, # magic number
|
| 106 |
+
self.seed % (2**32), # global seed
|
| 107 |
+
self._cur_epoch, # epoch index
|
| 108 |
+
]
|
| 109 |
+
)
|
| 110 |
+
self._cur_indices = PlasmaArray(rng.choice(
|
| 111 |
+
len(self.dataset),
|
| 112 |
+
self.actual_size,
|
| 113 |
+
replace=self.replace,
|
| 114 |
+
p=(None),
|
| 115 |
+
)
|
| 116 |
+
)
|
| 117 |
+
#print(self._cur_epoch, self._cur_indices.array[:10])
|
data/unimol/data/tta_dataset.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from unicore.data import BaseWrapperDataset
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TTADataset(BaseWrapperDataset):
|
| 11 |
+
def __init__(self, dataset, seed, atoms, coordinates, conf_size=10):
|
| 12 |
+
self.dataset = dataset
|
| 13 |
+
self.seed = seed
|
| 14 |
+
self.atoms = atoms
|
| 15 |
+
self.coordinates = coordinates
|
| 16 |
+
self.conf_size = conf_size
|
| 17 |
+
self.set_epoch(None)
|
| 18 |
+
|
| 19 |
+
def set_epoch(self, epoch, **unused):
|
| 20 |
+
super().set_epoch(epoch)
|
| 21 |
+
self.epoch = epoch
|
| 22 |
+
|
| 23 |
+
def __len__(self):
|
| 24 |
+
return len(self.dataset) * self.conf_size
|
| 25 |
+
|
| 26 |
+
@lru_cache(maxsize=16)
|
| 27 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 28 |
+
smi_idx = index // self.conf_size
|
| 29 |
+
coord_idx = index % self.conf_size
|
| 30 |
+
atoms = np.array(self.dataset[smi_idx][self.atoms])
|
| 31 |
+
coordinates = np.array(self.dataset[smi_idx][self.coordinates][coord_idx])
|
| 32 |
+
smi = self.dataset[smi_idx]["smi"]
|
| 33 |
+
target = self.dataset[smi_idx]["target"]
|
| 34 |
+
return {
|
| 35 |
+
"atoms": atoms,
|
| 36 |
+
"coordinates": coordinates.astype(np.float32),
|
| 37 |
+
"smi": smi,
|
| 38 |
+
"target": target,
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
def __getitem__(self, index: int):
|
| 42 |
+
return self.__cached_item__(index, self.epoch)
|
| 43 |
+
|
| 44 |
+
class TTADecoderDataset(BaseWrapperDataset):
|
| 45 |
+
def __init__(self, dataset, seed, atoms, coordinates, selfies="selfies", conf_size=10):
|
| 46 |
+
self.dataset = dataset
|
| 47 |
+
self.seed = seed
|
| 48 |
+
self.atoms = atoms
|
| 49 |
+
self.coordinates = coordinates
|
| 50 |
+
self.selfies = selfies
|
| 51 |
+
self.conf_size = conf_size
|
| 52 |
+
self.set_epoch(None)
|
| 53 |
+
|
| 54 |
+
def set_epoch(self, epoch, **unused):
|
| 55 |
+
super().set_epoch(epoch)
|
| 56 |
+
self.epoch = epoch
|
| 57 |
+
|
| 58 |
+
def __len__(self):
|
| 59 |
+
return len(self.dataset) * self.conf_size
|
| 60 |
+
|
| 61 |
+
@lru_cache(maxsize=16)
|
| 62 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 63 |
+
smi_idx = index // self.conf_size
|
| 64 |
+
coord_idx = index % self.conf_size
|
| 65 |
+
atoms = np.array(self.dataset[smi_idx][self.atoms])
|
| 66 |
+
coordinates = np.array(self.dataset[smi_idx][self.coordinates][coord_idx])
|
| 67 |
+
selfies = np.array(self.dataset[smi_idx][self.selfies])
|
| 68 |
+
smi = self.dataset[smi_idx]["smi"]
|
| 69 |
+
target = self.dataset[smi_idx]["target"]
|
| 70 |
+
return {
|
| 71 |
+
"atoms": atoms,
|
| 72 |
+
"selfies": selfies,
|
| 73 |
+
"coordinates": coordinates.astype(np.float32),
|
| 74 |
+
"smi": smi,
|
| 75 |
+
"target": target,
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
def __getitem__(self, index: int):
|
| 79 |
+
return self.__cached_item__(index, self.epoch)
|
| 80 |
+
|
| 81 |
+
class TTADockingPoseDataset(BaseWrapperDataset):
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
dataset,
|
| 85 |
+
atoms,
|
| 86 |
+
coordinates,
|
| 87 |
+
pocket_atoms,
|
| 88 |
+
pocket_coordinates,
|
| 89 |
+
holo_coordinates,
|
| 90 |
+
holo_pocket_coordinates,
|
| 91 |
+
is_train=True,
|
| 92 |
+
conf_size=10,
|
| 93 |
+
):
|
| 94 |
+
self.dataset = dataset
|
| 95 |
+
self.atoms = atoms
|
| 96 |
+
self.coordinates = coordinates
|
| 97 |
+
self.pocket_atoms = pocket_atoms
|
| 98 |
+
self.pocket_coordinates = pocket_coordinates
|
| 99 |
+
self.holo_coordinates = holo_coordinates
|
| 100 |
+
self.holo_pocket_coordinates = holo_pocket_coordinates
|
| 101 |
+
self.is_train = is_train
|
| 102 |
+
self.conf_size = conf_size
|
| 103 |
+
self.set_epoch(None)
|
| 104 |
+
|
| 105 |
+
def set_epoch(self, epoch, **unused):
|
| 106 |
+
super().set_epoch(epoch)
|
| 107 |
+
self.epoch = epoch
|
| 108 |
+
|
| 109 |
+
def __len__(self):
|
| 110 |
+
return len(self.dataset) * self.conf_size
|
| 111 |
+
|
| 112 |
+
@lru_cache(maxsize=16)
|
| 113 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 114 |
+
smi_idx = index // self.conf_size
|
| 115 |
+
coord_idx = index % self.conf_size
|
| 116 |
+
atoms = np.array(self.dataset[smi_idx][self.atoms])
|
| 117 |
+
coordinates = np.array(self.dataset[smi_idx][self.coordinates][coord_idx])
|
| 118 |
+
pocket_atoms = np.array(
|
| 119 |
+
[item[0] for item in self.dataset[smi_idx][self.pocket_atoms]]
|
| 120 |
+
)
|
| 121 |
+
pocket_coordinates = np.array(self.dataset[smi_idx][self.pocket_coordinates][0])
|
| 122 |
+
if self.is_train:
|
| 123 |
+
holo_coordinates = np.array(self.dataset[smi_idx][self.holo_coordinates][0])
|
| 124 |
+
holo_pocket_coordinates = np.array(
|
| 125 |
+
self.dataset[smi_idx][self.holo_pocket_coordinates][0]
|
| 126 |
+
)
|
| 127 |
+
else:
|
| 128 |
+
holo_coordinates = coordinates
|
| 129 |
+
holo_pocket_coordinates = pocket_coordinates
|
| 130 |
+
|
| 131 |
+
smi = self.dataset[smi_idx]["smi"]
|
| 132 |
+
pocket = self.dataset[smi_idx]["pocket"]
|
| 133 |
+
|
| 134 |
+
return {
|
| 135 |
+
"atoms": atoms,
|
| 136 |
+
"coordinates": coordinates.astype(np.float32),
|
| 137 |
+
"pocket_atoms": pocket_atoms,
|
| 138 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 139 |
+
"holo_coordinates": holo_coordinates.astype(np.float32),
|
| 140 |
+
"holo_pocket_coordinates": holo_pocket_coordinates.astype(np.float32),
|
| 141 |
+
"smi": smi,
|
| 142 |
+
"pocket": pocket,
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
def __getitem__(self, index: int):
|
| 146 |
+
return self.__cached_item__(index, self.epoch)
|
data/unimol/data/vae_binding_dataset.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
from unicore.data import BaseWrapperDataset
|
| 10 |
+
|
| 11 |
+
from . import data_utils
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class VAEBindingDataset(BaseWrapperDataset):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
dataset,
|
| 18 |
+
seed,
|
| 19 |
+
atoms,
|
| 20 |
+
coordinates,
|
| 21 |
+
pocket_atoms,
|
| 22 |
+
pocket_coordinates,
|
| 23 |
+
selfies,
|
| 24 |
+
is_train=True,
|
| 25 |
+
):
|
| 26 |
+
self.dataset = dataset
|
| 27 |
+
self.seed = seed
|
| 28 |
+
self.atoms = atoms
|
| 29 |
+
self.coordinates = coordinates
|
| 30 |
+
self.pocket_atoms = pocket_atoms
|
| 31 |
+
self.pocket_coordinates = pocket_coordinates
|
| 32 |
+
self.selfies = selfies
|
| 33 |
+
self.is_train = is_train
|
| 34 |
+
self.set_epoch(None)
|
| 35 |
+
|
| 36 |
+
def set_epoch(self, epoch, **unused):
|
| 37 |
+
super().set_epoch(epoch)
|
| 38 |
+
self.epoch = epoch
|
| 39 |
+
|
| 40 |
+
def pocket_atom(self, atom):
|
| 41 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 42 |
+
return atom[1]
|
| 43 |
+
else:
|
| 44 |
+
return atom[0]
|
| 45 |
+
|
| 46 |
+
@lru_cache(maxsize=16)
|
| 47 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 48 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 49 |
+
coordinates = self.dataset[index][self.coordinates]
|
| 50 |
+
pocket_atoms = np.array(
|
| 51 |
+
[self.pocket_atom(item) for item in self.dataset[index][self.pocket_atoms]]
|
| 52 |
+
)
|
| 53 |
+
pocket_coordinates = np.stack(self.dataset[index][self.pocket_coordinates])
|
| 54 |
+
|
| 55 |
+
smi = self.dataset[index]["smi"]
|
| 56 |
+
pocket = self.dataset[index]["pocket"]
|
| 57 |
+
#affinity = self.dataset[index][self.affinity]
|
| 58 |
+
selfies = np.array(self.dataset[index][self.selfies])
|
| 59 |
+
return {
|
| 60 |
+
"atoms": atoms,
|
| 61 |
+
"coordinates": coordinates.astype(np.float32),
|
| 62 |
+
"holo_coordinates": coordinates.astype(np.float32),#placeholder
|
| 63 |
+
"pocket_atoms": pocket_atoms,
|
| 64 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 65 |
+
"holo_pocket_coordinates": pocket_coordinates.astype(np.float32),#placeholder
|
| 66 |
+
"smi": smi,
|
| 67 |
+
"pocket": pocket,
|
| 68 |
+
"selfies": selfies
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
def __getitem__(self, index: int):
|
| 72 |
+
return self.__cached_item__(index, self.epoch)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class VAEBindingTestDataset(BaseWrapperDataset):
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
dataset,
|
| 79 |
+
seed,
|
| 80 |
+
atoms,
|
| 81 |
+
coordinates,
|
| 82 |
+
pocket_atoms,
|
| 83 |
+
pocket_coordinates,
|
| 84 |
+
is_train=True,
|
| 85 |
+
):
|
| 86 |
+
self.dataset = dataset
|
| 87 |
+
self.seed = seed
|
| 88 |
+
self.atoms = atoms
|
| 89 |
+
self.coordinates = coordinates
|
| 90 |
+
self.pocket_atoms = pocket_atoms
|
| 91 |
+
self.pocket_coordinates = pocket_coordinates
|
| 92 |
+
self.is_train = is_train
|
| 93 |
+
self.set_epoch(None)
|
| 94 |
+
|
| 95 |
+
def set_epoch(self, epoch, **unused):
|
| 96 |
+
super().set_epoch(epoch)
|
| 97 |
+
self.epoch = epoch
|
| 98 |
+
|
| 99 |
+
def pocket_atom(self, atom):
|
| 100 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 101 |
+
return atom[1]
|
| 102 |
+
else:
|
| 103 |
+
return atom[0]
|
| 104 |
+
|
| 105 |
+
@lru_cache(maxsize=16)
|
| 106 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 107 |
+
atoms = np.array(self.dataset[index][self.atoms])
|
| 108 |
+
coordinates = self.dataset[index][self.coordinates]
|
| 109 |
+
pocket_atoms = np.array(
|
| 110 |
+
[self.pocket_atom(item) for item in self.dataset[index][self.pocket_atoms]]
|
| 111 |
+
)
|
| 112 |
+
pocket_coordinates = np.stack(self.dataset[index][self.pocket_coordinates])
|
| 113 |
+
|
| 114 |
+
smi = self.dataset[index]["smi"]
|
| 115 |
+
pocket = self.dataset[index]["pocket_name"]
|
| 116 |
+
lig = self.dataset[index]["lig_name"]
|
| 117 |
+
#affinity = self.dataset[index][self.affinity]
|
| 118 |
+
return {
|
| 119 |
+
"atoms": atoms,
|
| 120 |
+
"coordinates": coordinates.astype(np.float32),
|
| 121 |
+
"holo_coordinates": coordinates.astype(np.float32),#placeholder
|
| 122 |
+
"pocket_atoms": pocket_atoms,
|
| 123 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 124 |
+
"holo_pocket_coordinates": pocket_coordinates.astype(np.float32),#placeholder
|
| 125 |
+
"smi": smi,
|
| 126 |
+
"pocket": pocket,
|
| 127 |
+
"lig": lig
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
def __getitem__(self, index: int):
|
| 131 |
+
return self.__cached_item__(index, self.epoch)
|
| 132 |
+
|
| 133 |
+
class VAEGenerationTestDataset(BaseWrapperDataset):
|
| 134 |
+
def __init__(
|
| 135 |
+
self,
|
| 136 |
+
dataset,
|
| 137 |
+
seed,
|
| 138 |
+
pocket_atoms,
|
| 139 |
+
pocket_coordinates,
|
| 140 |
+
is_train=True,
|
| 141 |
+
):
|
| 142 |
+
self.dataset = dataset
|
| 143 |
+
self.seed = seed
|
| 144 |
+
self.pocket_atoms = pocket_atoms
|
| 145 |
+
self.pocket_coordinates = pocket_coordinates
|
| 146 |
+
self.is_train = is_train
|
| 147 |
+
self.set_epoch(None)
|
| 148 |
+
|
| 149 |
+
def set_epoch(self, epoch, **unused):
|
| 150 |
+
super().set_epoch(epoch)
|
| 151 |
+
self.epoch = epoch
|
| 152 |
+
|
| 153 |
+
def pocket_atom(self, atom):
|
| 154 |
+
if atom[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
| 155 |
+
return atom[1]
|
| 156 |
+
else:
|
| 157 |
+
return atom[0]
|
| 158 |
+
|
| 159 |
+
@lru_cache(maxsize=16)
|
| 160 |
+
def __cached_item__(self, index: int, epoch: int):
|
| 161 |
+
pocket_atoms = np.array(
|
| 162 |
+
[self.pocket_atom(item) for item in self.dataset[index][self.pocket_atoms]]
|
| 163 |
+
)
|
| 164 |
+
pocket_coordinates = np.stack(self.dataset[index][self.pocket_coordinates])
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
return {
|
| 168 |
+
"pocket_atoms": pocket_atoms,
|
| 169 |
+
"pocket_coordinates": pocket_coordinates.astype(np.float32),
|
| 170 |
+
"holo_pocket_coordinates": pocket_coordinates.astype(np.float32),#placeholder
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
def __getitem__(self, index: int):
|
| 174 |
+
return self.__cached_item__(index, self.epoch)
|
| 175 |
+
|
| 176 |
+
|
data/unimol/demo.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from unicore.data import LMDBDataset
|
| 2 |
+
|
| 3 |
+
path = "./data/DUD-E/raw/all/ada17/mols.lmdb" # 换成一个具体 target
|
| 4 |
+
print("open", path)
|
| 5 |
+
ds = LMDBDataset(path)
|
| 6 |
+
print("len =", len(ds))
|
| 7 |
+
|
| 8 |
+
for i in range(len(ds)):
|
| 9 |
+
if i % 1000 == 0:
|
| 10 |
+
print("index", i, "...")
|
| 11 |
+
ds[i] # 只要能成功 __getitem__ 就行
|
| 12 |
+
print("done")
|
data/unimol/encode_pocket_ligand.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3 -u
|
| 2 |
+
# Copyright (c) DP Techonology, Inc. and its affiliates.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
import pickle
|
| 11 |
+
import torch
|
| 12 |
+
from unicore import checkpoint_utils, distributed_utils, options, utils
|
| 13 |
+
from unicore.logging import progress_bar
|
| 14 |
+
from unicore import tasks
|
| 15 |
+
import numpy as np
|
| 16 |
+
from tqdm import tqdm
|
| 17 |
+
import unicore
|
| 18 |
+
import pandas as pd
|
| 19 |
+
|
| 20 |
+
logging.basicConfig(
|
| 21 |
+
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
| 22 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 23 |
+
level=os.environ.get("LOGLEVEL", "INFO").upper(),
|
| 24 |
+
stream=sys.stdout,
|
| 25 |
+
)
|
| 26 |
+
logger = logging.getLogger("unimol.inference")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main(args):
|
| 30 |
+
|
| 31 |
+
use_fp16 = args.fp16
|
| 32 |
+
use_cuda = torch.cuda.is_available() and not args.cpu
|
| 33 |
+
|
| 34 |
+
if use_cuda:
|
| 35 |
+
torch.cuda.set_device(args.device_id)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# Load model
|
| 39 |
+
logger.info("loading model(s) from {}".format(args.path))
|
| 40 |
+
state = checkpoint_utils.load_checkpoint_to_cpu(args.path)
|
| 41 |
+
task = tasks.setup_task(args)
|
| 42 |
+
model = task.build_model(args)
|
| 43 |
+
model.load_state_dict(state["model"], strict=False)
|
| 44 |
+
|
| 45 |
+
# Move models to GPU
|
| 46 |
+
if use_fp16:
|
| 47 |
+
model.half()
|
| 48 |
+
if use_cuda:
|
| 49 |
+
model.cuda()
|
| 50 |
+
|
| 51 |
+
# Print args
|
| 52 |
+
logger.info(args)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
model.eval()
|
| 56 |
+
|
| 57 |
+
root_dir = args.save_dir
|
| 58 |
+
|
| 59 |
+
# all_mols = []
|
| 60 |
+
# for dirpath, dirnames, filenames in os.walk(root_dir):
|
| 61 |
+
# for f in filenames:
|
| 62 |
+
# if f.endswith('_mols.lmdb'):
|
| 63 |
+
# all_mols.append(os.path.join(dirpath, f))
|
| 64 |
+
|
| 65 |
+
# for mol_path in tqdm(all_mols, desc="Encoding pocket-ligand pairs"):
|
| 66 |
+
# mol_files = [f for f in filenames if f.endswith('_mols.lmdb')]
|
| 67 |
+
|
| 68 |
+
# dirpath = os.path.dirname(mol_path)
|
| 69 |
+
# mol_file = os.path.basename(mol_path)
|
| 70 |
+
# prefix = mol_file.replace('_mols.lmdb', '')
|
| 71 |
+
# pocket_file = prefix + '_pocket10_pocket.lmdb'
|
| 72 |
+
# pocket_path = os.path.join(dirpath, pocket_file)
|
| 73 |
+
|
| 74 |
+
# try:
|
| 75 |
+
# # Encode ligand + pocket
|
| 76 |
+
# ligand_emb, pocket_emb = task.encode_pocket_and_ligand(
|
| 77 |
+
# model,
|
| 78 |
+
# mol_path,
|
| 79 |
+
# pocket_path,
|
| 80 |
+
# )
|
| 81 |
+
# except Exception as e:
|
| 82 |
+
# logger.error(f"Error encoding {mol_path} / {pocket_path}: {e}")
|
| 83 |
+
# continue
|
| 84 |
+
|
| 85 |
+
# save_dir = dirpath
|
| 86 |
+
# os.makedirs(save_dir, exist_ok=True)
|
| 87 |
+
|
| 88 |
+
# lig_path = os.path.join(save_dir, mol_file.replace('_mols.lmdb', '') + "_ligand_emb.pt")
|
| 89 |
+
# pkt_path = os.path.join(save_dir, pocket_file.replace('_pocket.lmdb', '') + "_pocket_emb.pt")
|
| 90 |
+
|
| 91 |
+
# torch.save(ligand_emb, lig_path)
|
| 92 |
+
# torch.save(pocket_emb, pkt_path)
|
| 93 |
+
ligand_lmdbs = []
|
| 94 |
+
for dirpath, dirnames, filenames in os.walk(root_dir):
|
| 95 |
+
for f in filenames:
|
| 96 |
+
if f.endswith(".lmdb"):
|
| 97 |
+
ligand_lmdbs.append(os.path.join(dirpath, f))
|
| 98 |
+
logger.info(f"Found {len(ligand_lmdbs)} ligand lmdb files under {root_dir}")
|
| 99 |
+
for lig_path in tqdm(ligand_lmdbs, desc="Encoding ligands"):
|
| 100 |
+
try:
|
| 101 |
+
ligand_emb = task.encode_ligand_cls(
|
| 102 |
+
model,
|
| 103 |
+
lig_path,
|
| 104 |
+
)
|
| 105 |
+
except Exception as e:
|
| 106 |
+
logger.error(f"Error encoding ligand {lig_path}: {e}")
|
| 107 |
+
continue
|
| 108 |
+
|
| 109 |
+
save_dir = os.path.dirname(lig_path)
|
| 110 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 111 |
+
|
| 112 |
+
prefix = os.path.splitext(os.path.basename(lig_path))[0]
|
| 113 |
+
out_path = os.path.join(save_dir, prefix + "_ligand_emb.pt")
|
| 114 |
+
|
| 115 |
+
torch.save(ligand_emb, out_path)
|
| 116 |
+
logger.info(f"Saved ligand embedding to {out_path}")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def cli_main():
|
| 121 |
+
# add args
|
| 122 |
+
parser = options.get_validation_parser()
|
| 123 |
+
parser.add_argument("--save-dir", type=str, default="", help="path for saved embedding data")
|
| 124 |
+
options.add_model_args(parser)
|
| 125 |
+
args = options.parse_args_and_arch(parser)
|
| 126 |
+
|
| 127 |
+
distributed_utils.call_main(args, main)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
cli_main()
|
data/unimol/losses/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import importlib
|
| 3 |
+
|
| 4 |
+
# automatically import any Python files in the criterions/ directory
|
| 5 |
+
for file in sorted(Path(__file__).parent.glob("*.py")):
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) DP Technology.
|
| 2 |
+
# This source code is licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from unicore import metrics
|
| 10 |
+
from unicore.losses import UnicoreLoss, register_loss
|
| 11 |
+
from unicore.losses.cross_entropy import CrossEntropyLoss
|
| 12 |
+
from sklearn.metrics import roc_auc_score, precision_score, recall_score, f1_score
|
| 13 |
+
import numpy as np
|
| 14 |
+
import warnings
|
| 15 |
+
from sklearn.metrics import top_k_accuracy_score
|
| 16 |
+
from rdkit.ML.Scoring.Scoring import CalcBEDROC
|
| 17 |
+
import scipy.stats as stats
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def calculate_bedroc(y_true, y_score, alpha):
|
| 21 |
+
"""
|
| 22 |
+
Calculate BEDROC score.
|
| 23 |
+
|
| 24 |
+
Parameters:
|
| 25 |
+
- y_true: true binary labels (0 or 1)
|
| 26 |
+
- y_score: predicted scores or probabilities
|
| 27 |
+
- alpha: parameter controlling the degree of early retrieval emphasis
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
- BEDROC score
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
# concate res_single and labels
|
| 34 |
+
scores = np.expand_dims(y_score, axis=1)
|
| 35 |
+
y_true = np.expand_dims(y_true, axis=1)
|
| 36 |
+
#print(scores.shape, y_true.shape)
|
| 37 |
+
scores = np.concatenate((scores, y_true), axis=1)
|
| 38 |
+
# inverse sort scores based on first column
|
| 39 |
+
scores = scores[scores[:,0].argsort()[::-1]]
|
| 40 |
+
bedroc = CalcBEDROC(scores, 1, 80.5)
|
| 41 |
+
return bedroc
|
| 42 |
+
|
| 43 |
+
@register_loss("decoder_loss")
|
| 44 |
+
class DecoderLoss(CrossEntropyLoss):
|
| 45 |
+
def __init__(self, task):
|
| 46 |
+
super().__init__(task)
|
| 47 |
+
|
| 48 |
+
def forward(self, model, sample, reduce=True, fix_encoder=False):
|
| 49 |
+
"""Compute the loss for the given sample.
|
| 50 |
+
|
| 51 |
+
Returns a tuple with three elements:
|
| 52 |
+
1) the loss
|
| 53 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 54 |
+
3) logging outputs to display while training
|
| 55 |
+
"""
|
| 56 |
+
net_output = model(
|
| 57 |
+
**sample["net_input"],
|
| 58 |
+
features_only=True,
|
| 59 |
+
classification_head_name=None,
|
| 60 |
+
fix_encoder=fix_encoder
|
| 61 |
+
)
|
| 62 |
+
loss = self.compute_loss(model, net_output, sample, reduce=reduce)
|
| 63 |
+
targets = sample["net_input"]["selfie_tokens"]
|
| 64 |
+
sample_size = targets.size(0)
|
| 65 |
+
|
| 66 |
+
lprobs = net_output[:,:,:targets.shape[-1]]
|
| 67 |
+
if not self.training:
|
| 68 |
+
logging_output = {
|
| 69 |
+
"loss": loss.data,
|
| 70 |
+
"prob": lprobs.data,
|
| 71 |
+
"target": targets.data,
|
| 72 |
+
"smi_name": sample["smi_name"],
|
| 73 |
+
"sample_size": sample_size,
|
| 74 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 75 |
+
}
|
| 76 |
+
else:
|
| 77 |
+
logging_output = {
|
| 78 |
+
"loss": loss.data,
|
| 79 |
+
"sample_size": sample_size,
|
| 80 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 81 |
+
}
|
| 82 |
+
return loss, sample_size, logging_output
|
| 83 |
+
|
| 84 |
+
def compute_loss(self, model, net_output, sample, reduce=True):
|
| 85 |
+
lprobs = net_output
|
| 86 |
+
targets = sample["net_input"]["selfie_tokens"]
|
| 87 |
+
lprobs = lprobs[:,:,:targets.shape[-1]]
|
| 88 |
+
# print("111", lprobs.shape, targets.shape, sample["target"]["finetune_target"].shape)
|
| 89 |
+
nll_loss = F.nll_loss(
|
| 90 |
+
lprobs,
|
| 91 |
+
targets,
|
| 92 |
+
reduction="sum" if reduce else "none",
|
| 93 |
+
) / lprobs.shape[-1]
|
| 94 |
+
|
| 95 |
+
loss = nll_loss
|
| 96 |
+
#print(loss.data, nll_loss.data, kld_loss.data)
|
| 97 |
+
return loss
|
| 98 |
+
|
| 99 |
+
@staticmethod
|
| 100 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 101 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 102 |
+
# if split == "valid":
|
| 103 |
+
# print("hi1")
|
| 104 |
+
loss = sum(log.get("loss", 0).float() for log in logging_outputs)
|
| 105 |
+
# if split == "valid":
|
| 106 |
+
# print("hi2")
|
| 107 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 108 |
+
# if split == "valid":
|
| 109 |
+
# print("hi3")
|
| 110 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 111 |
+
metrics.log_scalar(
|
| 112 |
+
"loss_all", loss / sample_size / math.log(2), sample_size, round=3
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
if "valid" in split or "test" in split:
|
| 116 |
+
|
| 117 |
+
prob_list = []
|
| 118 |
+
pred_list = []
|
| 119 |
+
target_list = []
|
| 120 |
+
for log in logging_outputs:
|
| 121 |
+
prob = log.get("prob")
|
| 122 |
+
prob = torch.transpose(prob, 1, 2)
|
| 123 |
+
prob = prob.reshape((-1, prob.shape[-1]))
|
| 124 |
+
prob_list.append(prob)
|
| 125 |
+
pred = log.get("prob").argmax(dim=1)
|
| 126 |
+
pred = pred.flatten()
|
| 127 |
+
pred_list.append(pred)
|
| 128 |
+
target = log.get("target")
|
| 129 |
+
target = target.flatten()
|
| 130 |
+
target_list.append(target)
|
| 131 |
+
|
| 132 |
+
preds = torch.cat(pred_list, dim=0)
|
| 133 |
+
targets = torch.cat(target_list, dim=0)
|
| 134 |
+
#print(preds.shape, targets.shape)
|
| 135 |
+
acc = (preds == targets).float().mean(dim=-1)
|
| 136 |
+
#print(acc.shape)
|
| 137 |
+
metrics.log_scalar(
|
| 138 |
+
f"{split}_acc", acc , sample_size, round=3
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@staticmethod
|
| 143 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 144 |
+
"""
|
| 145 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 146 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 147 |
+
to True will improves distributed training speed.
|
| 148 |
+
"""
|
| 149 |
+
return is_train
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@register_loss("decoder_vae_loss")
|
| 153 |
+
class DecoderVAELoss(CrossEntropyLoss):
|
| 154 |
+
def __init__(self, task):
|
| 155 |
+
super().__init__(task)
|
| 156 |
+
|
| 157 |
+
def forward(self, model, sample, candidate_reps, candidate_embs, candidate_smiles, reduce=True, fix_encoder=False):
|
| 158 |
+
"""Compute the loss for the given sample.
|
| 159 |
+
|
| 160 |
+
Returns a tuple with three elements:
|
| 161 |
+
1) the loss
|
| 162 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 163 |
+
3) logging outputs to display while training
|
| 164 |
+
"""
|
| 165 |
+
net_output = model(
|
| 166 |
+
**sample["net_input"],
|
| 167 |
+
candidate_reps=candidate_reps,
|
| 168 |
+
candidate_embs=candidate_embs,
|
| 169 |
+
candidate_smiles=candidate_smiles,
|
| 170 |
+
features_only=True,
|
| 171 |
+
classification_head_name=None,
|
| 172 |
+
fix_encoder=fix_encoder
|
| 173 |
+
)
|
| 174 |
+
loss, nll_loss, kld_loss = self.compute_loss(model, net_output, sample, reduce=reduce)
|
| 175 |
+
targets = sample["net_input"]["selfie_tokens"]
|
| 176 |
+
sample_size = targets.size(0)
|
| 177 |
+
|
| 178 |
+
lprobs = net_output[0][:,:,:targets.shape[-1]]
|
| 179 |
+
if not self.training:
|
| 180 |
+
logging_output = {
|
| 181 |
+
"loss": loss.data,
|
| 182 |
+
"kld_loss": kld_loss.data,
|
| 183 |
+
"nll_loss": nll_loss.data,
|
| 184 |
+
"prob": lprobs.data,
|
| 185 |
+
"target": targets.data,
|
| 186 |
+
"smi_name": sample["smi_name"],
|
| 187 |
+
"sample_size": sample_size,
|
| 188 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 189 |
+
}
|
| 190 |
+
else:
|
| 191 |
+
logging_output = {
|
| 192 |
+
"loss": loss.data,
|
| 193 |
+
"kld_loss": kld_loss.data,
|
| 194 |
+
"nll_loss": nll_loss.data,
|
| 195 |
+
"sample_size": sample_size,
|
| 196 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 197 |
+
}
|
| 198 |
+
return loss, sample_size, logging_output
|
| 199 |
+
|
| 200 |
+
def compute_loss(self, model, net_output, sample, reduce=True):
|
| 201 |
+
out, z, mu, log_var = net_output
|
| 202 |
+
lprobs = out
|
| 203 |
+
targets = sample["net_input"]["selfie_tokens"]
|
| 204 |
+
lprobs = lprobs[:,:,:targets.shape[-1]]
|
| 205 |
+
# print("111", lprobs.shape, targets.shape, sample["target"]["finetune_target"].shape)
|
| 206 |
+
nll_loss = F.nll_loss(
|
| 207 |
+
lprobs,
|
| 208 |
+
targets,
|
| 209 |
+
reduction="sum" if reduce else "none",
|
| 210 |
+
) / lprobs.shape[-1]
|
| 211 |
+
kld_loss = -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp()) / lprobs.shape[1]
|
| 212 |
+
p=0.2
|
| 213 |
+
loss = p * kld_loss + (1-p) * nll_loss
|
| 214 |
+
#print(loss.data, nll_loss.data, kld_loss.data)
|
| 215 |
+
return loss, nll_loss, kld_loss
|
| 216 |
+
|
| 217 |
+
@staticmethod
|
| 218 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 219 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 220 |
+
# if split == "valid":
|
| 221 |
+
# print("hi1")
|
| 222 |
+
loss_all = sum(log.get("loss", 0).float() for log in logging_outputs)
|
| 223 |
+
loss_kld = sum(log.get("kld_loss", 0).float() for log in logging_outputs)
|
| 224 |
+
loss_nll = sum(log.get("nll_loss", 0).float() for log in logging_outputs)
|
| 225 |
+
# if split == "valid":
|
| 226 |
+
# print("hi2")
|
| 227 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 228 |
+
# if split == "valid":
|
| 229 |
+
# print("hi3")
|
| 230 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 231 |
+
metrics.log_scalar(
|
| 232 |
+
"loss_all", loss_all / sample_size / math.log(2), sample_size, round=3
|
| 233 |
+
)
|
| 234 |
+
metrics.log_scalar(
|
| 235 |
+
"loss_kld", loss_kld / sample_size, sample_size, round=3
|
| 236 |
+
)
|
| 237 |
+
metrics.log_scalar(
|
| 238 |
+
"loss_nll", loss_nll / sample_size, sample_size, round=3
|
| 239 |
+
)
|
| 240 |
+
if "valid" in split or "test" in split:
|
| 241 |
+
|
| 242 |
+
prob_list = []
|
| 243 |
+
pred_list = []
|
| 244 |
+
target_list = []
|
| 245 |
+
for log in logging_outputs:
|
| 246 |
+
prob = log.get("prob")
|
| 247 |
+
prob = torch.transpose(prob, 1, 2)
|
| 248 |
+
prob = prob.reshape((-1, prob.shape[-1]))
|
| 249 |
+
prob_list.append(prob)
|
| 250 |
+
pred = log.get("prob").argmax(dim=1)
|
| 251 |
+
pred = pred.flatten()
|
| 252 |
+
pred_list.append(pred)
|
| 253 |
+
target = log.get("target")
|
| 254 |
+
target = target.flatten()
|
| 255 |
+
target_list.append(target)
|
| 256 |
+
|
| 257 |
+
probs = torch.cat(prob_list, dim=0)
|
| 258 |
+
preds = torch.cat(pred_list, dim=0)
|
| 259 |
+
targets = torch.cat(target_list, dim=0)
|
| 260 |
+
#print(preds.shape, targets.shape)
|
| 261 |
+
acc = (preds == targets).float().mean(dim=-1)
|
| 262 |
+
#print(acc.shape)
|
| 263 |
+
metrics.log_scalar(
|
| 264 |
+
f"{split}_acc", acc , sample_size, round=3
|
| 265 |
+
)
|
| 266 |
+
'''
|
| 267 |
+
# smi_list = [
|
| 268 |
+
# item for log in logging_outputs for item in log.get("smi_name")
|
| 269 |
+
# ]
|
| 270 |
+
probs = torch.exp(probs)
|
| 271 |
+
#prob_flat = prob_flat.reshape((-1, prob_flat.shape[-1]))
|
| 272 |
+
print(probs.shape)
|
| 273 |
+
|
| 274 |
+
#targets = targets.squeeze(dim=-1)
|
| 275 |
+
auc = roc_auc_score(targets.cpu(), probs.cpu(), multi_class="ovo", labels=torch.arange(probs.shape[-1]))
|
| 276 |
+
#df = df.groupby("smi").mean()
|
| 277 |
+
#agg_auc = roc_auc_score(df["targets"], df["probs"])
|
| 278 |
+
agg_auc = auc
|
| 279 |
+
|
| 280 |
+
metrics.log_scalar(f"{split}_auc", auc, sample_size, round=3)
|
| 281 |
+
metrics.log_scalar(f"{split}_agg_auc", agg_auc, sample_size, round=4)
|
| 282 |
+
'''
|
| 283 |
+
|
| 284 |
+
@staticmethod
|
| 285 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 286 |
+
"""
|
| 287 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 288 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 289 |
+
to True will improves distributed training speed.
|
| 290 |
+
"""
|
| 291 |
+
return is_train
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@register_loss("finetune_cross_entropy")
|
| 295 |
+
class FinetuneCrossEntropyLoss(CrossEntropyLoss):
|
| 296 |
+
def __init__(self, task):
|
| 297 |
+
super().__init__(task)
|
| 298 |
+
|
| 299 |
+
def forward(self, model, sample, reduce=True, fix_encoder=False):
|
| 300 |
+
"""Compute the loss for the given sample.
|
| 301 |
+
|
| 302 |
+
Returns a tuple with three elements:
|
| 303 |
+
1) the loss
|
| 304 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 305 |
+
3) logging outputs to display while training
|
| 306 |
+
"""
|
| 307 |
+
net_output = model(
|
| 308 |
+
**sample["net_input"],
|
| 309 |
+
features_only=True,
|
| 310 |
+
classification_head_name=self.args.classification_head_name,
|
| 311 |
+
fix_encoder=fix_encoder
|
| 312 |
+
)
|
| 313 |
+
logit_output = net_output[0]
|
| 314 |
+
loss = self.compute_loss(model, logit_output, sample, reduce=reduce)
|
| 315 |
+
sample_size = sample["target"]["finetune_target"].size(0)
|
| 316 |
+
if not self.training:
|
| 317 |
+
probs = F.softmax(logit_output.float(), dim=-1).view(
|
| 318 |
+
-1, logit_output.size(-1)
|
| 319 |
+
)
|
| 320 |
+
logging_output = {
|
| 321 |
+
"loss": loss.data,
|
| 322 |
+
"prob": probs.data,
|
| 323 |
+
"target": sample["target"]["finetune_target"].view(-1).data,
|
| 324 |
+
"smi_name": sample["smi_name"],
|
| 325 |
+
"sample_size": sample_size,
|
| 326 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 327 |
+
}
|
| 328 |
+
else:
|
| 329 |
+
logging_output = {
|
| 330 |
+
"loss": loss.data,
|
| 331 |
+
"sample_size": sample_size,
|
| 332 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 333 |
+
}
|
| 334 |
+
return loss, sample_size, logging_output
|
| 335 |
+
|
| 336 |
+
def compute_loss(self, model, net_output, sample, reduce=True):
|
| 337 |
+
lprobs = F.log_softmax(net_output.float(), dim=-1)
|
| 338 |
+
lprobs = lprobs.view(-1, lprobs.size(-1))
|
| 339 |
+
targets = sample["target"]["finetune_target"].view(-1)
|
| 340 |
+
# print("111", lprobs.shape, targets.shape, sample["target"]["finetune_target"].shape)
|
| 341 |
+
loss = F.nll_loss(
|
| 342 |
+
lprobs,
|
| 343 |
+
targets,
|
| 344 |
+
reduction="sum" if reduce else "none",
|
| 345 |
+
)
|
| 346 |
+
return loss
|
| 347 |
+
|
| 348 |
+
@staticmethod
|
| 349 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 350 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 351 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
| 352 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 353 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 354 |
+
metrics.log_scalar(
|
| 355 |
+
"loss", loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 356 |
+
)
|
| 357 |
+
if "valid" in split or "test" in split:
|
| 358 |
+
acc_sum = sum(
|
| 359 |
+
sum(log.get("prob").argmax(dim=-1) == log.get("target"))
|
| 360 |
+
for log in logging_outputs
|
| 361 |
+
)
|
| 362 |
+
probs = torch.cat([log.get("prob") for log in logging_outputs], dim=0)
|
| 363 |
+
metrics.log_scalar(
|
| 364 |
+
f"{split}_acc", acc_sum / sample_size, sample_size, round=3
|
| 365 |
+
)
|
| 366 |
+
if probs.size(-1) == 2:
|
| 367 |
+
# binary classification task, add auc score
|
| 368 |
+
targets = torch.cat(
|
| 369 |
+
[log.get("target", 0) for log in logging_outputs], dim=0
|
| 370 |
+
)
|
| 371 |
+
smi_list = [
|
| 372 |
+
item for log in logging_outputs for item in log.get("smi_name")
|
| 373 |
+
]
|
| 374 |
+
df = pd.DataFrame(
|
| 375 |
+
{
|
| 376 |
+
"probs": probs[:, 1].cpu(),
|
| 377 |
+
"targets": targets.cpu(),
|
| 378 |
+
"smi": smi_list,
|
| 379 |
+
}
|
| 380 |
+
)
|
| 381 |
+
auc = roc_auc_score(df["targets"], df["probs"])
|
| 382 |
+
df = df.groupby("smi").mean()
|
| 383 |
+
agg_auc = roc_auc_score(df["targets"], df["probs"])
|
| 384 |
+
metrics.log_scalar(f"{split}_auc", auc, sample_size, round=3)
|
| 385 |
+
metrics.log_scalar(f"{split}_agg_auc", agg_auc, sample_size, round=4)
|
| 386 |
+
|
| 387 |
+
@staticmethod
|
| 388 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 389 |
+
"""
|
| 390 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 391 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 392 |
+
to True will improves distributed training speed.
|
| 393 |
+
"""
|
| 394 |
+
return is_train
|
| 395 |
+
|
| 396 |
+
@register_loss("ce")
|
| 397 |
+
class CEntropyLoss(CrossEntropyLoss):
|
| 398 |
+
def __init__(self, task):
|
| 399 |
+
super().__init__(task)
|
| 400 |
+
|
| 401 |
+
def forward(self, model, sample, reduce=True, fix_encoder=False):
|
| 402 |
+
"""Compute the loss for the given sample.
|
| 403 |
+
|
| 404 |
+
Returns a tuple with three elements:
|
| 405 |
+
1) the loss
|
| 406 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 407 |
+
3) logging outputs to display while training
|
| 408 |
+
"""
|
| 409 |
+
net_output = model(
|
| 410 |
+
**sample["net_input"],
|
| 411 |
+
smi_list = sample["smi_name"],
|
| 412 |
+
pocket_list = sample["pocket_name"],
|
| 413 |
+
features_only=True,
|
| 414 |
+
fix_encoder=fix_encoder
|
| 415 |
+
)
|
| 416 |
+
logit_output = net_output
|
| 417 |
+
loss = self.compute_loss(model, logit_output, sample, reduce=reduce)
|
| 418 |
+
#print(sample["target"]["finetune_target"])
|
| 419 |
+
sample_size = sample["target"]["finetune_target"].size(0)
|
| 420 |
+
if not self.training:
|
| 421 |
+
probs = torch.sigmoid(logit_output.float())
|
| 422 |
+
logging_output = {
|
| 423 |
+
"loss": loss.data,
|
| 424 |
+
"prob": probs.data,
|
| 425 |
+
"target": sample["target"]["finetune_target"].view(-1).data,
|
| 426 |
+
"smi_name": sample["smi_name"],
|
| 427 |
+
"sample_size": sample_size,
|
| 428 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 429 |
+
}
|
| 430 |
+
else:
|
| 431 |
+
logging_output = {
|
| 432 |
+
"loss": loss.data,
|
| 433 |
+
"sample_size": sample_size,
|
| 434 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 435 |
+
}
|
| 436 |
+
return loss, sample_size, logging_output
|
| 437 |
+
|
| 438 |
+
def compute_loss(self, model, net_output, sample, reduce=True):
|
| 439 |
+
|
| 440 |
+
targets = sample["target"]["finetune_target"].view(-1)
|
| 441 |
+
# print("111", lprobs.shape, targets.shape, sample["target"]["finetune_target"].shape)
|
| 442 |
+
#print(net_output.shape, targets.shape)
|
| 443 |
+
loss = F.binary_cross_entropy_with_logits(
|
| 444 |
+
net_output.float(),
|
| 445 |
+
targets,
|
| 446 |
+
reduction="sum" if reduce else "none",
|
| 447 |
+
)
|
| 448 |
+
return loss
|
| 449 |
+
|
| 450 |
+
@staticmethod
|
| 451 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 452 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 453 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
| 454 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 455 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 456 |
+
metrics.log_scalar(
|
| 457 |
+
"loss", loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 458 |
+
)
|
| 459 |
+
if "valid" in split or "test" in split:
|
| 460 |
+
|
| 461 |
+
# get acc
|
| 462 |
+
acc_sum = 0
|
| 463 |
+
for log in logging_outputs:
|
| 464 |
+
probs = torch.sigmoid(log.get("prob"))
|
| 465 |
+
targets = log.get("target")
|
| 466 |
+
probs = probs > 0.5
|
| 467 |
+
# convert to int
|
| 468 |
+
probs = probs.long()
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
logs = [log.get("prob") for log in logging_outputs]
|
| 472 |
+
targets = torch.cat(
|
| 473 |
+
[log.get("target", 0) for log in logging_outputs], dim=0
|
| 474 |
+
)
|
| 475 |
+
probs = torch.cat([log.get("prob") for log in logging_outputs], dim=0)
|
| 476 |
+
#probs = torch.sigmoid(probs)
|
| 477 |
+
print(probs.shape, targets.shape)
|
| 478 |
+
print(probs[:10], targets[:10])
|
| 479 |
+
preds = probs > 0.5
|
| 480 |
+
# convert to int
|
| 481 |
+
preds = preds.long()
|
| 482 |
+
acc_sum = (preds == targets).sum()
|
| 483 |
+
metrics.log_scalar(
|
| 484 |
+
f"{split}_acc", acc_sum / sample_size, sample_size, round=3
|
| 485 |
+
)
|
| 486 |
+
# binary classification task, add auc score
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
smi_list = [
|
| 490 |
+
item for log in logging_outputs for item in log.get("smi_name")
|
| 491 |
+
]
|
| 492 |
+
df = pd.DataFrame(
|
| 493 |
+
{
|
| 494 |
+
"probs": probs.cpu(),
|
| 495 |
+
"targets": targets.cpu(),
|
| 496 |
+
"smi": smi_list,
|
| 497 |
+
}
|
| 498 |
+
)
|
| 499 |
+
# get values of df["targets"]
|
| 500 |
+
#
|
| 501 |
+
|
| 502 |
+
auc = roc_auc_score(df["targets"].values, df["probs"].values)
|
| 503 |
+
df = df.groupby("smi").mean()
|
| 504 |
+
agg_auc = roc_auc_score(df["targets"], df["probs"])
|
| 505 |
+
#print(df["targets"])
|
| 506 |
+
metrics.log_scalar(f"{split}_auc", auc, sample_size, round=3)
|
| 507 |
+
metrics.log_scalar(f"{split}_agg_auc", agg_auc, sample_size, round=4)
|
| 508 |
+
|
| 509 |
+
@staticmethod
|
| 510 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 511 |
+
"""
|
| 512 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 513 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 514 |
+
to True will improves distributed training speed.
|
| 515 |
+
"""
|
| 516 |
+
return is_train
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
@register_loss("in_batch_softmax")
|
| 520 |
+
class IBSLoss(CrossEntropyLoss):
|
| 521 |
+
def __init__(self, task):
|
| 522 |
+
super().__init__(task)
|
| 523 |
+
|
| 524 |
+
def set_num_updates(self, num_updates):
|
| 525 |
+
self.num_updates = 0
|
| 526 |
+
self.num_updates = num_updates
|
| 527 |
+
|
| 528 |
+
def forward(self, model, sample, reduce=True, fix_encoder=False):
|
| 529 |
+
"""Compute the loss for the given sample.
|
| 530 |
+
|
| 531 |
+
Returns a tuple with three elements:
|
| 532 |
+
1) the loss
|
| 533 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 534 |
+
3) logging outputs to display while training
|
| 535 |
+
"""
|
| 536 |
+
net_output = model(
|
| 537 |
+
**sample["net_input"],
|
| 538 |
+
smi_list = sample["smi_name"],
|
| 539 |
+
pocket_list = sample["pocket_name"],
|
| 540 |
+
features_only=True,
|
| 541 |
+
fix_encoder=fix_encoder,
|
| 542 |
+
is_train = self.training
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
logit_output = net_output[0]
|
| 546 |
+
loss_diff,_,_ = net_output[2]
|
| 547 |
+
loss = self.compute_loss(model, logit_output, sample, reduce=reduce)
|
| 548 |
+
#print(loss.item(), loss_diff.item()) 15:1.9
|
| 549 |
+
loss = loss + 0.5 * loss_diff
|
| 550 |
+
sample_size = logit_output.size(0)
|
| 551 |
+
targets = torch.arange(sample_size, dtype=torch.long).cuda()
|
| 552 |
+
affinities = sample["target"]["finetune_target"].view(-1)
|
| 553 |
+
if not self.training:
|
| 554 |
+
logit_output = logit_output[:,:sample_size]
|
| 555 |
+
probs = F.softmax(logit_output.float(), dim=-1).view(
|
| 556 |
+
-1, logit_output.size(-1)
|
| 557 |
+
)
|
| 558 |
+
logging_output = {
|
| 559 |
+
"loss": loss.data,
|
| 560 |
+
"prob": probs.data,
|
| 561 |
+
"target": targets,
|
| 562 |
+
"smi_name": sample["smi_name"],
|
| 563 |
+
"sample_size": sample_size,
|
| 564 |
+
"bsz": targets.size(0),
|
| 565 |
+
"scale": net_output[1].data,
|
| 566 |
+
"affinity": affinities,
|
| 567 |
+
}
|
| 568 |
+
else:
|
| 569 |
+
logging_output = {
|
| 570 |
+
"loss": loss.data,
|
| 571 |
+
"sample_size": sample_size,
|
| 572 |
+
"bsz": targets.size(0),
|
| 573 |
+
"scale": net_output[1].data
|
| 574 |
+
}
|
| 575 |
+
return loss, sample_size, logging_output
|
| 576 |
+
|
| 577 |
+
def compute_loss(self, model, net_output, sample, reduce=True):
|
| 578 |
+
logits = net_output.float()
|
| 579 |
+
B = logits.size(0)
|
| 580 |
+
lprobs_pocket = F.log_softmax(logits, dim=-1)
|
| 581 |
+
lprobs_pocket = lprobs_pocket.view(-1, lprobs_pocket.size(-1))
|
| 582 |
+
sample_size = lprobs_pocket.size(0)
|
| 583 |
+
targets= torch.arange(sample_size, dtype=torch.long).view(-1).cuda()
|
| 584 |
+
|
| 585 |
+
# pocket retrieve mol
|
| 586 |
+
loss_pocket = F.nll_loss(
|
| 587 |
+
lprobs_pocket,
|
| 588 |
+
targets,
|
| 589 |
+
reduction="sum" if reduce else "none",
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
logits_mol_side = logits[:, :B]
|
| 593 |
+
lprobs_mol = F.log_softmax(torch.transpose(logits_mol_side, 0, 1), dim=-1)
|
| 594 |
+
lprobs_mol = lprobs_mol.view(-1, lprobs_mol.size(-1))
|
| 595 |
+
lprobs_mol = lprobs_mol[:sample_size]
|
| 596 |
+
|
| 597 |
+
# mol retrieve pocket
|
| 598 |
+
loss_mol = F.nll_loss(
|
| 599 |
+
lprobs_mol,
|
| 600 |
+
targets,
|
| 601 |
+
reduction="sum" if reduce else "none",
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
loss = 0.5 * loss_pocket + 0.5 * loss_mol
|
| 605 |
+
return loss
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
@staticmethod
|
| 609 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 610 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 611 |
+
metrics.log_scalar("scale", logging_outputs[0].get("scale"), round=3)
|
| 612 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
| 613 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 614 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 615 |
+
metrics.log_scalar(
|
| 616 |
+
"loss", loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 617 |
+
)
|
| 618 |
+
if "valid" in split or "test" in split:
|
| 619 |
+
acc_sum = sum(
|
| 620 |
+
sum(log.get("prob").argmax(dim=-1) == log.get("target"))
|
| 621 |
+
for log in logging_outputs
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
prob_list = []
|
| 625 |
+
if len(logging_outputs) == 1:
|
| 626 |
+
prob_list.append(logging_outputs[0].get("prob"))
|
| 627 |
+
else:
|
| 628 |
+
for i in range(len(logging_outputs)-1):
|
| 629 |
+
prob_list.append(logging_outputs[i].get("prob"))
|
| 630 |
+
probs = torch.cat(prob_list, dim=0)
|
| 631 |
+
|
| 632 |
+
metrics.log_scalar(
|
| 633 |
+
f"{split}_acc", acc_sum / sample_size, sample_size, round=3
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
metrics.log_scalar(
|
| 637 |
+
"valid_neg_loss", -loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
targets = torch.cat(
|
| 642 |
+
[log.get("target", 0) for log in logging_outputs], dim=0
|
| 643 |
+
)
|
| 644 |
+
print(targets.shape, probs.shape)
|
| 645 |
+
|
| 646 |
+
targets = targets[:len(probs)]
|
| 647 |
+
bedroc_list = []
|
| 648 |
+
auc_list = []
|
| 649 |
+
for i in range(len(probs)):
|
| 650 |
+
prob = probs[i]
|
| 651 |
+
target = targets[i]
|
| 652 |
+
label = torch.zeros_like(prob)
|
| 653 |
+
label[target]=1.0
|
| 654 |
+
cur_auc = roc_auc_score(label.cpu(), prob.cpu())
|
| 655 |
+
auc_list.append(cur_auc)
|
| 656 |
+
bedroc = calculate_bedroc(label.cpu(), prob.cpu(), 80.5)
|
| 657 |
+
bedroc_list.append(bedroc)
|
| 658 |
+
bedroc = np.mean(bedroc_list)
|
| 659 |
+
auc = np.mean(auc_list)
|
| 660 |
+
|
| 661 |
+
top_k_acc = top_k_accuracy_score(targets.cpu(), probs.cpu(), k=3, normalize=True)
|
| 662 |
+
metrics.log_scalar(f"{split}_auc", auc, sample_size, round=3)
|
| 663 |
+
metrics.log_scalar(f"{split}_bedroc", bedroc, sample_size, round=3)
|
| 664 |
+
metrics.log_scalar(f"{split}_top3_acc", top_k_acc, sample_size, round=3)
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
@staticmethod
|
| 669 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 670 |
+
"""
|
| 671 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 672 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 673 |
+
to True will improves distributed training speed.
|
| 674 |
+
"""
|
| 675 |
+
return is_train
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
@register_loss("in_batch_softmax_hinge")
|
| 679 |
+
class IBSLoss_rank(CrossEntropyLoss):
|
| 680 |
+
def __init__(self, task):
|
| 681 |
+
super().__init__(task)
|
| 682 |
+
self.lambda_hinge = 1.5
|
| 683 |
+
self.num_updates = 0
|
| 684 |
+
self.margin = 0.0
|
| 685 |
+
|
| 686 |
+
def set_num_updates(self, num_updates):
|
| 687 |
+
self.num_updates = num_updates
|
| 688 |
+
|
| 689 |
+
def forward(self, model, sample, reduce=True, fix_encoder=False):
|
| 690 |
+
"""Compute the loss for the given sample.
|
| 691 |
+
"""
|
| 692 |
+
net_output = model(
|
| 693 |
+
**sample["net_input"],
|
| 694 |
+
smi_list = sample["smi_name"],
|
| 695 |
+
pocket_list = sample["pocket_name"],
|
| 696 |
+
features_only=True,
|
| 697 |
+
fix_encoder=fix_encoder,
|
| 698 |
+
is_train = self.training
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
logit_output = net_output[0]
|
| 702 |
+
loss_diff,_,_ = net_output[2]
|
| 703 |
+
|
| 704 |
+
extra = net_output[3]
|
| 705 |
+
loss = self.compute_loss(model, logit_output, extra, sample, reduce=reduce)
|
| 706 |
+
#print(loss.item(), loss_diff.item()) 15:1.9
|
| 707 |
+
loss = loss + 0.5 * loss_diff
|
| 708 |
+
sample_size = logit_output.size(0)
|
| 709 |
+
targets = torch.arange(sample_size, dtype=torch.long).cuda()
|
| 710 |
+
affinities = sample["target"]["finetune_target"].view(-1)
|
| 711 |
+
if not self.training:
|
| 712 |
+
logit_output = logit_output[:,:sample_size]
|
| 713 |
+
probs = F.softmax(logit_output.float(), dim=-1).view(
|
| 714 |
+
-1, logit_output.size(-1)
|
| 715 |
+
)
|
| 716 |
+
logging_output = {
|
| 717 |
+
"loss": loss.data,
|
| 718 |
+
"prob": probs.data,
|
| 719 |
+
"target": targets,
|
| 720 |
+
"smi_name": sample["smi_name"],
|
| 721 |
+
"sample_size": sample_size,
|
| 722 |
+
"bsz": targets.size(0),
|
| 723 |
+
"scale": net_output[1].data,
|
| 724 |
+
"affinity": affinities,
|
| 725 |
+
}
|
| 726 |
+
else:
|
| 727 |
+
logging_output = {
|
| 728 |
+
"loss": loss.data,
|
| 729 |
+
"sample_size": sample_size,
|
| 730 |
+
"bsz": targets.size(0),
|
| 731 |
+
"scale": net_output[1].data
|
| 732 |
+
}
|
| 733 |
+
return loss, sample_size, logging_output
|
| 734 |
+
|
| 735 |
+
def compute_loss(self, model, net_output, extra, sample, reduce=True):
|
| 736 |
+
logits = net_output.float()
|
| 737 |
+
B = logits.size(0)
|
| 738 |
+
lprobs_pocket = F.log_softmax(logits, dim=-1)
|
| 739 |
+
lprobs_pocket = lprobs_pocket.view(-1, lprobs_pocket.size(-1))
|
| 740 |
+
sample_size = lprobs_pocket.size(0)
|
| 741 |
+
targets= torch.arange(sample_size, dtype=torch.long).view(-1).cuda()
|
| 742 |
+
|
| 743 |
+
# pocket retrieve mol
|
| 744 |
+
loss_pocket = F.nll_loss(
|
| 745 |
+
lprobs_pocket,
|
| 746 |
+
targets,
|
| 747 |
+
reduction="sum" if reduce else "none",
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
logits_mol_side = logits[:, :B]
|
| 751 |
+
lprobs_mol = F.log_softmax(torch.transpose(logits_mol_side, 0, 1), dim=-1)
|
| 752 |
+
lprobs_mol = lprobs_mol.view(-1, lprobs_mol.size(-1))
|
| 753 |
+
lprobs_mol = lprobs_mol[:sample_size]
|
| 754 |
+
|
| 755 |
+
# mol retrieve pocket
|
| 756 |
+
loss_mol = F.nll_loss(
|
| 757 |
+
lprobs_mol,
|
| 758 |
+
targets,
|
| 759 |
+
reduction="sum" if reduce else "none",
|
| 760 |
+
)
|
| 761 |
+
|
| 762 |
+
loss = 0.5 * loss_pocket + 0.5 * loss_mol
|
| 763 |
+
|
| 764 |
+
##====
|
| 765 |
+
lig_emb_aux = torch.cat([extra['mol_emb'].detach(), extra['decoy_emb']], dim=0) # [2B, D]
|
| 766 |
+
logit_lig = torch.matmul(lig_emb_aux, lig_emb_aux.t())
|
| 767 |
+
hard_idx = torch.arange(B, device=logits.device)
|
| 768 |
+
hard_neg = logit_lig[hard_idx, hard_idx + B]
|
| 769 |
+
|
| 770 |
+
# row = logit_lig[hard_idx, :].clone() # [B, 2B]
|
| 771 |
+
# row[hard_idx, hard_idx] = 0.0
|
| 772 |
+
# row[hard_idx, hard_idx + B] = 0.0
|
| 773 |
+
# avg_neg = (row.sum(dim=-1) / (2*B - 2)).detach()
|
| 774 |
+
|
| 775 |
+
row = logit_lig[hard_idx, :B].clone() # [B, 2B]
|
| 776 |
+
row[hard_idx, hard_idx] = 0.0
|
| 777 |
+
avg_neg = (row.sum(dim=-1) / (B - 1)).detach()
|
| 778 |
+
#avg_neg = logit_lig[hard_idx, :].mean(dim=-1).detach()
|
| 779 |
+
|
| 780 |
+
# 0: is hard, 1: is random
|
| 781 |
+
hir = sample["hard_label"].view(-1).to(logits.device).float() # 0/1
|
| 782 |
+
mask = (1.0 - hir)
|
| 783 |
+
loss_mean = F.relu(avg_neg - hard_neg) * mask
|
| 784 |
+
loss_mean = loss_mean.sum() if reduce else loss_mean
|
| 785 |
+
# with torch.no_grad():
|
| 786 |
+
# mask = (1.0 - hir)
|
| 787 |
+
# gap = (avg_neg - hard_neg + self.margin)
|
| 788 |
+
# vr_all = (gap > 0).float().mean()
|
| 789 |
+
# vr_true = ((gap > 0) & (mask > 0)).float().sum() / mask.sum().clamp_min(1.0)
|
| 790 |
+
# print(
|
| 791 |
+
# "loss_aux", loss_mean.item(),
|
| 792 |
+
# "avg", avg_neg.mean().item(),
|
| 793 |
+
# "hard", hard_neg.mean().item(),
|
| 794 |
+
# "gap", gap.mean().item(),
|
| 795 |
+
# "vr_all", vr_all.item(),
|
| 796 |
+
# "vr_true", vr_true.item(),
|
| 797 |
+
# "hir", hir.mean().item(),
|
| 798 |
+
# "n_true", mask.sum().item()
|
| 799 |
+
# )
|
| 800 |
+
loss = loss + self.lambda_hinge * loss_mean
|
| 801 |
+
|
| 802 |
+
return loss
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
@staticmethod
|
| 806 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 807 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 808 |
+
metrics.log_scalar("scale", logging_outputs[0].get("scale"), round=3)
|
| 809 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
| 810 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 811 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 812 |
+
metrics.log_scalar(
|
| 813 |
+
"loss", loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 814 |
+
)
|
| 815 |
+
if "valid" in split or "test" in split:
|
| 816 |
+
acc_sum = sum(
|
| 817 |
+
sum(log.get("prob").argmax(dim=-1) == log.get("target"))
|
| 818 |
+
for log in logging_outputs
|
| 819 |
+
)
|
| 820 |
+
|
| 821 |
+
prob_list = []
|
| 822 |
+
if len(logging_outputs) == 1:
|
| 823 |
+
prob_list.append(logging_outputs[0].get("prob"))
|
| 824 |
+
else:
|
| 825 |
+
for i in range(len(logging_outputs)-1):
|
| 826 |
+
prob_list.append(logging_outputs[i].get("prob"))
|
| 827 |
+
probs = torch.cat(prob_list, dim=0)
|
| 828 |
+
|
| 829 |
+
metrics.log_scalar(
|
| 830 |
+
f"{split}_acc", acc_sum / sample_size, sample_size, round=3
|
| 831 |
+
)
|
| 832 |
+
|
| 833 |
+
metrics.log_scalar(
|
| 834 |
+
"valid_neg_loss", -loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
targets = torch.cat(
|
| 839 |
+
[log.get("target", 0) for log in logging_outputs], dim=0
|
| 840 |
+
)
|
| 841 |
+
print(targets.shape, probs.shape)
|
| 842 |
+
|
| 843 |
+
targets = targets[:len(probs)]
|
| 844 |
+
bedroc_list = []
|
| 845 |
+
auc_list = []
|
| 846 |
+
for i in range(len(probs)):
|
| 847 |
+
prob = probs[i]
|
| 848 |
+
target = targets[i]
|
| 849 |
+
label = torch.zeros_like(prob)
|
| 850 |
+
label[target]=1.0
|
| 851 |
+
cur_auc = roc_auc_score(label.cpu(), prob.cpu())
|
| 852 |
+
auc_list.append(cur_auc)
|
| 853 |
+
bedroc = calculate_bedroc(label.cpu(), prob.cpu(), 80.5)
|
| 854 |
+
bedroc_list.append(bedroc)
|
| 855 |
+
bedroc = np.mean(bedroc_list)
|
| 856 |
+
auc = np.mean(auc_list)
|
| 857 |
+
|
| 858 |
+
top_k_acc = top_k_accuracy_score(targets.cpu(), probs.cpu(), k=3, normalize=True)
|
| 859 |
+
metrics.log_scalar(f"{split}_auc", auc, sample_size, round=3)
|
| 860 |
+
metrics.log_scalar(f"{split}_bedroc", bedroc, sample_size, round=3)
|
| 861 |
+
metrics.log_scalar(f"{split}_top3_acc", top_k_acc, sample_size, round=3)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
@staticmethod
|
| 866 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 867 |
+
"""
|
| 868 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 869 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 870 |
+
to True will improves distributed training speed.
|
| 871 |
+
"""
|
| 872 |
+
return is_train
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
@register_loss("in_batch_softmax_weighted")
|
| 877 |
+
class IBSLoss_weighted(CrossEntropyLoss):
|
| 878 |
+
def __init__(self, task):
|
| 879 |
+
super().__init__(task)
|
| 880 |
+
self.lambda_property = 0.05
|
| 881 |
+
|
| 882 |
+
def forward(self, model, sample, reduce=True, fix_encoder=False):
|
| 883 |
+
"""Compute the loss for the given sample.
|
| 884 |
+
|
| 885 |
+
Returns a tuple with three elements:
|
| 886 |
+
1) the loss
|
| 887 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 888 |
+
3) logging outputs to display while training
|
| 889 |
+
"""
|
| 890 |
+
net_output = model(
|
| 891 |
+
**sample["net_input"],
|
| 892 |
+
smi_list = sample["smi_name"],
|
| 893 |
+
pocket_list = sample["pocket_name"],
|
| 894 |
+
features_only=True,
|
| 895 |
+
fix_encoder=fix_encoder,
|
| 896 |
+
is_train = self.training
|
| 897 |
+
)
|
| 898 |
+
|
| 899 |
+
logit_output = net_output[0]
|
| 900 |
+
loss_diff,_,_ = net_output[2]
|
| 901 |
+
loss = self.compute_loss(model, logit_output, sample, reduce=reduce)
|
| 902 |
+
#print(loss.item(), loss_diff.item()) 15:1.9
|
| 903 |
+
loss = loss + 0.5 * loss_diff
|
| 904 |
+
sample_size = logit_output.size(0)
|
| 905 |
+
targets = torch.arange(sample_size, dtype=torch.long).cuda()
|
| 906 |
+
affinities = sample["target"]["finetune_target"].view(-1)
|
| 907 |
+
if not self.training:
|
| 908 |
+
logit_output = logit_output[:,:sample_size]
|
| 909 |
+
probs = F.softmax(logit_output.float(), dim=-1).view(
|
| 910 |
+
-1, logit_output.size(-1)
|
| 911 |
+
)
|
| 912 |
+
logging_output = {
|
| 913 |
+
"loss": loss.data,
|
| 914 |
+
"prob": probs.data,
|
| 915 |
+
"target": targets,
|
| 916 |
+
"smi_name": sample["smi_name"],
|
| 917 |
+
"sample_size": sample_size,
|
| 918 |
+
"bsz": targets.size(0),
|
| 919 |
+
"scale": net_output[1].data,
|
| 920 |
+
"affinity": affinities,
|
| 921 |
+
}
|
| 922 |
+
else:
|
| 923 |
+
logging_output = {
|
| 924 |
+
"loss": loss.data,
|
| 925 |
+
"sample_size": sample_size,
|
| 926 |
+
"bsz": targets.size(0),
|
| 927 |
+
"scale": net_output[1].data
|
| 928 |
+
}
|
| 929 |
+
return loss, sample_size, logging_output
|
| 930 |
+
|
| 931 |
+
def compute_loss(self, model, net_output, sample, reduce=True):
|
| 932 |
+
#=============
|
| 933 |
+
# weighted_loss
|
| 934 |
+
logits = net_output.float()
|
| 935 |
+
B = logits.size(0)
|
| 936 |
+
logits = self._apply_property_weight(logits, sample["scaffold_fp"], sample["decoy_scaffold_fp"])
|
| 937 |
+
#=============
|
| 938 |
+
lprobs_pocket = F.log_softmax(logits, dim=-1)
|
| 939 |
+
lprobs_pocket = lprobs_pocket.view(-1, lprobs_pocket.size(-1))
|
| 940 |
+
sample_size = lprobs_pocket.size(0)
|
| 941 |
+
targets= torch.arange(sample_size, dtype=torch.long).view(-1).cuda()
|
| 942 |
+
|
| 943 |
+
# pocket retrieve mol
|
| 944 |
+
loss_pocket = F.nll_loss(
|
| 945 |
+
lprobs_pocket,
|
| 946 |
+
targets,
|
| 947 |
+
reduction="sum" if reduce else "none",
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
logits_mol_side = logits[:, :B]
|
| 951 |
+
lprobs_mol = F.log_softmax(torch.transpose(logits_mol_side, 0, 1), dim=-1)
|
| 952 |
+
lprobs_mol = lprobs_mol.view(-1, lprobs_mol.size(-1))
|
| 953 |
+
lprobs_mol = lprobs_mol[:sample_size]
|
| 954 |
+
|
| 955 |
+
# mol retrieve pocket
|
| 956 |
+
loss_mol = F.nll_loss(
|
| 957 |
+
lprobs_mol,
|
| 958 |
+
targets,
|
| 959 |
+
reduction="sum" if reduce else "none",
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
loss = 0.5 * loss_pocket + 0.5 * loss_mol
|
| 963 |
+
return loss
|
| 964 |
+
|
| 965 |
+
def _apply_property_weight(self, logits, prop_vec_batch, decoy_prop_vec_batch):
|
| 966 |
+
if self.lambda_property == 0:
|
| 967 |
+
return logits
|
| 968 |
+
|
| 969 |
+
B, L = logits.shape
|
| 970 |
+
X_pos = prop_vec_batch.float().to(logits.device)
|
| 971 |
+
X_dec = decoy_prop_vec_batch.float().to(logits.device)
|
| 972 |
+
X_all = torch.cat([X_pos, X_dec], dim=0)
|
| 973 |
+
|
| 974 |
+
S = X_pos @ X_all.t() # [B, L]
|
| 975 |
+
idx = torch.arange(B, device=logits.device)
|
| 976 |
+
S[idx, idx] = 0.0
|
| 977 |
+
# mask_high = S > 0.9 # maybe false negative
|
| 978 |
+
# S[mask_high] = 0.0
|
| 979 |
+
alpha = 1.0 + self.lambda_property * S
|
| 980 |
+
logits = logits + torch.log(alpha + 1e-8)
|
| 981 |
+
|
| 982 |
+
return logits
|
| 983 |
+
|
| 984 |
+
@staticmethod
|
| 985 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 986 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 987 |
+
metrics.log_scalar("scale", logging_outputs[0].get("scale"), round=3)
|
| 988 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
| 989 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 990 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 991 |
+
metrics.log_scalar(
|
| 992 |
+
"loss", loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 993 |
+
)
|
| 994 |
+
if "valid" in split or "test" in split:
|
| 995 |
+
acc_sum = sum(
|
| 996 |
+
sum(log.get("prob").argmax(dim=-1) == log.get("target"))
|
| 997 |
+
for log in logging_outputs
|
| 998 |
+
)
|
| 999 |
+
|
| 1000 |
+
prob_list = []
|
| 1001 |
+
if len(logging_outputs) == 1:
|
| 1002 |
+
prob_list.append(logging_outputs[0].get("prob"))
|
| 1003 |
+
else:
|
| 1004 |
+
for i in range(len(logging_outputs)-1):
|
| 1005 |
+
prob_list.append(logging_outputs[i].get("prob"))
|
| 1006 |
+
probs = torch.cat(prob_list, dim=0)
|
| 1007 |
+
|
| 1008 |
+
metrics.log_scalar(
|
| 1009 |
+
f"{split}_acc", acc_sum / sample_size, sample_size, round=3
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
metrics.log_scalar(
|
| 1013 |
+
"valid_neg_loss", -loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
targets = torch.cat(
|
| 1018 |
+
[log.get("target", 0) for log in logging_outputs], dim=0
|
| 1019 |
+
)
|
| 1020 |
+
print(targets.shape, probs.shape)
|
| 1021 |
+
|
| 1022 |
+
targets = targets[:len(probs)]
|
| 1023 |
+
bedroc_list = []
|
| 1024 |
+
auc_list = []
|
| 1025 |
+
for i in range(len(probs)):
|
| 1026 |
+
prob = probs[i]
|
| 1027 |
+
target = targets[i]
|
| 1028 |
+
label = torch.zeros_like(prob)
|
| 1029 |
+
label[target]=1.0
|
| 1030 |
+
cur_auc = roc_auc_score(label.cpu(), prob.cpu())
|
| 1031 |
+
auc_list.append(cur_auc)
|
| 1032 |
+
bedroc = calculate_bedroc(label.cpu(), prob.cpu(), 80.5)
|
| 1033 |
+
bedroc_list.append(bedroc)
|
| 1034 |
+
bedroc = np.mean(bedroc_list)
|
| 1035 |
+
auc = np.mean(auc_list)
|
| 1036 |
+
|
| 1037 |
+
top_k_acc = top_k_accuracy_score(targets.cpu(), probs.cpu(), k=3, normalize=True)
|
| 1038 |
+
metrics.log_scalar(f"{split}_auc", auc, sample_size, round=3)
|
| 1039 |
+
metrics.log_scalar(f"{split}_bedroc", bedroc, sample_size, round=3)
|
| 1040 |
+
metrics.log_scalar(f"{split}_top3_acc", top_k_acc, sample_size, round=3)
|
| 1041 |
+
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
@staticmethod
|
| 1045 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 1046 |
+
"""
|
| 1047 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 1048 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 1049 |
+
to True will improves distributed training speed.
|
| 1050 |
+
"""
|
| 1051 |
+
return is_train
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
|
| 1058 |
+
@register_loss("multi_task_BCE")
|
| 1059 |
+
class MultiTaskBCELoss(CrossEntropyLoss):
|
| 1060 |
+
def __init__(self, task):
|
| 1061 |
+
super().__init__(task)
|
| 1062 |
+
|
| 1063 |
+
def forward(self, model, sample, reduce=True, fix_encoder=False):
|
| 1064 |
+
"""Compute the loss for the given sample.
|
| 1065 |
+
Returns a tuple with three elements:
|
| 1066 |
+
1) the loss
|
| 1067 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 1068 |
+
3) logging outputs to display while training
|
| 1069 |
+
"""
|
| 1070 |
+
net_output = model(
|
| 1071 |
+
**sample["net_input"],
|
| 1072 |
+
masked_tokens=None,
|
| 1073 |
+
features_only=True,
|
| 1074 |
+
classification_head_name=self.args.classification_head_name,
|
| 1075 |
+
fix_encoder=fix_encoder
|
| 1076 |
+
)
|
| 1077 |
+
logit_output = net_output[0]
|
| 1078 |
+
is_valid = sample["target"]["finetune_target"] > -0.5
|
| 1079 |
+
loss = self.compute_loss(
|
| 1080 |
+
model, logit_output, sample, reduce=reduce, is_valid=is_valid
|
| 1081 |
+
)
|
| 1082 |
+
sample_size = sample["target"]["finetune_target"].size(0)
|
| 1083 |
+
if not self.training:
|
| 1084 |
+
probs = torch.sigmoid(logit_output.float()).view(-1, logit_output.size(-1))
|
| 1085 |
+
logging_output = {
|
| 1086 |
+
"loss": loss.data,
|
| 1087 |
+
"prob": probs.data,
|
| 1088 |
+
"target": sample["target"]["finetune_target"].view(-1).data,
|
| 1089 |
+
"num_task": self.args.num_classes,
|
| 1090 |
+
"sample_size": sample_size,
|
| 1091 |
+
"conf_size": self.args.conf_size,
|
| 1092 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 1093 |
+
}
|
| 1094 |
+
else:
|
| 1095 |
+
logging_output = {
|
| 1096 |
+
"loss": loss.data,
|
| 1097 |
+
"sample_size": sample_size,
|
| 1098 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 1099 |
+
}
|
| 1100 |
+
return loss, sample_size, logging_output
|
| 1101 |
+
|
| 1102 |
+
def compute_loss(self, model, net_output, sample, reduce=True, is_valid=None):
|
| 1103 |
+
pred = net_output[is_valid].float()
|
| 1104 |
+
targets = sample["target"]["finetune_target"][is_valid].float()
|
| 1105 |
+
loss = F.binary_cross_entropy_with_logits(
|
| 1106 |
+
pred,
|
| 1107 |
+
targets,
|
| 1108 |
+
reduction="sum" if reduce else "none",
|
| 1109 |
+
)
|
| 1110 |
+
return loss
|
| 1111 |
+
|
| 1112 |
+
@staticmethod
|
| 1113 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 1114 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 1115 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
| 1116 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 1117 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 1118 |
+
metrics.log_scalar(
|
| 1119 |
+
"loss", loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 1120 |
+
)
|
| 1121 |
+
if "valid" in split or "test" in split:
|
| 1122 |
+
agg_auc_list = []
|
| 1123 |
+
num_task = logging_outputs[0].get("num_task", 0)
|
| 1124 |
+
conf_size = logging_outputs[0].get("conf_size", 0)
|
| 1125 |
+
y_true = (
|
| 1126 |
+
torch.cat([log.get("target", 0) for log in logging_outputs], dim=0)
|
| 1127 |
+
.view(-1, conf_size, num_task)
|
| 1128 |
+
.cpu()
|
| 1129 |
+
.numpy()
|
| 1130 |
+
.mean(axis=1)
|
| 1131 |
+
)
|
| 1132 |
+
y_pred = (
|
| 1133 |
+
torch.cat([log.get("prob") for log in logging_outputs], dim=0)
|
| 1134 |
+
.view(-1, conf_size, num_task)
|
| 1135 |
+
.cpu()
|
| 1136 |
+
.numpy()
|
| 1137 |
+
.mean(axis=1)
|
| 1138 |
+
)
|
| 1139 |
+
# [test_size, num_classes] = [test_size * conf_size, num_classes].mean(axis=1)
|
| 1140 |
+
for i in range(y_true.shape[1]):
|
| 1141 |
+
# AUC is only defined when there is at least one positive data.
|
| 1142 |
+
if np.sum(y_true[:, i] == 1) > 0 and np.sum(y_true[:, i] == 0) > 0:
|
| 1143 |
+
# ignore nan values
|
| 1144 |
+
is_labeled = y_true[:, i] > -0.5
|
| 1145 |
+
agg_auc_list.append(
|
| 1146 |
+
roc_auc_score(y_true[is_labeled, i], y_pred[is_labeled, i])
|
| 1147 |
+
)
|
| 1148 |
+
if len(agg_auc_list) < y_true.shape[1]:
|
| 1149 |
+
warnings.warn("Some target is missing!")
|
| 1150 |
+
if len(agg_auc_list) == 0:
|
| 1151 |
+
raise RuntimeError(
|
| 1152 |
+
"No positively labeled data available. Cannot compute Average Precision."
|
| 1153 |
+
)
|
| 1154 |
+
agg_auc = sum(agg_auc_list) / len(agg_auc_list)
|
| 1155 |
+
metrics.log_scalar(f"{split}_agg_auc", agg_auc, sample_size, round=4)
|
| 1156 |
+
|
| 1157 |
+
@staticmethod
|
| 1158 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 1159 |
+
"""
|
| 1160 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 1161 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 1162 |
+
to True will improves distributed training speed.
|
| 1163 |
+
"""
|
| 1164 |
+
return is_train
|
| 1165 |
+
|
| 1166 |
+
@register_loss("BCE")
|
| 1167 |
+
class BCELoss(CrossEntropyLoss):
|
| 1168 |
+
def __init__(self, task):
|
| 1169 |
+
super().__init__(task)
|
| 1170 |
+
|
| 1171 |
+
def forward(self, model, sample, reduce=True, fix_encoder=False):
|
| 1172 |
+
"""Compute the loss for the given sample.
|
| 1173 |
+
Returns a tuple with three elements:
|
| 1174 |
+
1) the loss
|
| 1175 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 1176 |
+
3) logging outputs to display while training
|
| 1177 |
+
"""
|
| 1178 |
+
net_output = model(
|
| 1179 |
+
**sample["net_input"],
|
| 1180 |
+
smi_list = sample["smi_name"],
|
| 1181 |
+
pocket_list = sample["pocket_name"],
|
| 1182 |
+
features_only=True,
|
| 1183 |
+
fix_encoder=fix_encoder
|
| 1184 |
+
)
|
| 1185 |
+
logit_output = net_output
|
| 1186 |
+
loss = self.compute_loss(
|
| 1187 |
+
model, logit_output, sample, reduce=reduce
|
| 1188 |
+
)
|
| 1189 |
+
sample_size = sample["target"]["finetune_target"].size(0)
|
| 1190 |
+
|
| 1191 |
+
if not self.training:
|
| 1192 |
+
probs = torch.sigmoid(logit_output.float())
|
| 1193 |
+
#print(probs.size())
|
| 1194 |
+
logging_output = {
|
| 1195 |
+
"loss": loss.data,
|
| 1196 |
+
"prob": probs.data,
|
| 1197 |
+
"target": sample["target"]["finetune_target"].view(-1).data,
|
| 1198 |
+
"sample_size": sample_size,
|
| 1199 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 1200 |
+
}
|
| 1201 |
+
else:
|
| 1202 |
+
logging_output = {
|
| 1203 |
+
"loss": loss.data,
|
| 1204 |
+
"sample_size": sample_size,
|
| 1205 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 1206 |
+
}
|
| 1207 |
+
return loss, sample_size, logging_output
|
| 1208 |
+
|
| 1209 |
+
def compute_loss(self, model, net_output, sample, reduce=True, is_valid=None):
|
| 1210 |
+
pred = net_output.float()
|
| 1211 |
+
targets = sample["target"]["finetune_target"].float()
|
| 1212 |
+
loss = F.binary_cross_entropy_with_logits(
|
| 1213 |
+
pred,
|
| 1214 |
+
targets,
|
| 1215 |
+
reduction="sum" if reduce else "none",
|
| 1216 |
+
)
|
| 1217 |
+
return loss
|
| 1218 |
+
|
| 1219 |
+
@staticmethod
|
| 1220 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 1221 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 1222 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
| 1223 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 1224 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 1225 |
+
metrics.log_scalar(
|
| 1226 |
+
"loss", loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 1227 |
+
)
|
| 1228 |
+
if "valid" in split or "test" in split:
|
| 1229 |
+
y_true_list = []
|
| 1230 |
+
y_pred_list = []
|
| 1231 |
+
y_true_list = [log.get("target", 0) for log in logging_outputs]
|
| 1232 |
+
y_pred_list = [log.get("prob") for log in logging_outputs]
|
| 1233 |
+
y_true = (
|
| 1234 |
+
torch.cat(y_true_list, dim=0)
|
| 1235 |
+
.cpu()
|
| 1236 |
+
.numpy()
|
| 1237 |
+
)
|
| 1238 |
+
y_pred = (
|
| 1239 |
+
torch.cat(y_pred_list, dim=0)
|
| 1240 |
+
.cpu()
|
| 1241 |
+
.numpy()
|
| 1242 |
+
)
|
| 1243 |
+
# [test_size, num_classes] = [test_size * conf_size, num_classes].mean(axis=1)
|
| 1244 |
+
|
| 1245 |
+
auc = roc_auc_score(y_true , y_pred)
|
| 1246 |
+
|
| 1247 |
+
|
| 1248 |
+
agg_auc = auc
|
| 1249 |
+
metrics.log_scalar(f"{split}_agg_auc", agg_auc, sample_size, round=4)
|
| 1250 |
+
|
| 1251 |
+
@staticmethod
|
| 1252 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 1253 |
+
"""
|
| 1254 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 1255 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 1256 |
+
to True will improves distributed training speed.
|
| 1257 |
+
"""
|
| 1258 |
+
return is_train
|
| 1259 |
+
|
| 1260 |
+
@register_loss("finetune_cross_entropy_pocket")
|
| 1261 |
+
class FinetuneCrossEntropyPocketLoss(FinetuneCrossEntropyLoss):
|
| 1262 |
+
def __init__(self, task):
|
| 1263 |
+
super().__init__(task)
|
| 1264 |
+
|
| 1265 |
+
def forward(self, model, sample, reduce=True):
|
| 1266 |
+
"""Compute the loss for the given sample.
|
| 1267 |
+
|
| 1268 |
+
Returns a tuple with three elements:
|
| 1269 |
+
1) the loss
|
| 1270 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 1271 |
+
3) logging outputs to display while training
|
| 1272 |
+
"""
|
| 1273 |
+
net_output = model(
|
| 1274 |
+
**sample["net_input"],
|
| 1275 |
+
features_only=True,
|
| 1276 |
+
classification_head_name=self.args.classification_head_name,
|
| 1277 |
+
)
|
| 1278 |
+
logit_output = net_output[0]
|
| 1279 |
+
loss = self.compute_loss(model, logit_output, sample, reduce=reduce)
|
| 1280 |
+
sample_size = sample["target"]["finetune_target"].size(0)
|
| 1281 |
+
if not self.training:
|
| 1282 |
+
probs = F.softmax(logit_output.float(), dim=-1).view(
|
| 1283 |
+
-1, logit_output.size(-1)
|
| 1284 |
+
)
|
| 1285 |
+
logging_output = {
|
| 1286 |
+
"loss": loss.data,
|
| 1287 |
+
"prob": probs.data,
|
| 1288 |
+
"target": sample["target"]["finetune_target"].view(-1).data,
|
| 1289 |
+
"sample_size": sample_size,
|
| 1290 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 1291 |
+
}
|
| 1292 |
+
else:
|
| 1293 |
+
logging_output = {
|
| 1294 |
+
"loss": loss.data,
|
| 1295 |
+
"sample_size": sample_size,
|
| 1296 |
+
"bsz": sample["target"]["finetune_target"].size(0),
|
| 1297 |
+
}
|
| 1298 |
+
return loss, sample_size, logging_output
|
| 1299 |
+
|
| 1300 |
+
@staticmethod
|
| 1301 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 1302 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 1303 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
| 1304 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 1305 |
+
# we divide by log(2) to convert the loss from base e to base 2
|
| 1306 |
+
metrics.log_scalar(
|
| 1307 |
+
"loss", loss_sum / sample_size / math.log(2), sample_size, round=3
|
| 1308 |
+
)
|
| 1309 |
+
if "valid" in split or "test" in split:
|
| 1310 |
+
acc_sum = sum(
|
| 1311 |
+
sum(log.get("prob").argmax(dim=-1) == log.get("target"))
|
| 1312 |
+
for log in logging_outputs
|
| 1313 |
+
)
|
| 1314 |
+
metrics.log_scalar(
|
| 1315 |
+
f"{split}_acc", acc_sum / sample_size, sample_size, round=3
|
| 1316 |
+
)
|
| 1317 |
+
preds = (
|
| 1318 |
+
torch.cat(
|
| 1319 |
+
[log.get("prob").argmax(dim=-1) for log in logging_outputs], dim=0
|
| 1320 |
+
)
|
| 1321 |
+
.cpu()
|
| 1322 |
+
.numpy()
|
| 1323 |
+
)
|
| 1324 |
+
targets = (
|
| 1325 |
+
torch.cat([log.get("target", 0) for log in logging_outputs], dim=0)
|
| 1326 |
+
.cpu()
|
| 1327 |
+
.numpy()
|
| 1328 |
+
)
|
| 1329 |
+
metrics.log_scalar(f"{split}_pre", precision_score(targets, preds), round=3)
|
| 1330 |
+
metrics.log_scalar(f"{split}_rec", recall_score(targets, preds), round=3)
|
| 1331 |
+
metrics.log_scalar(
|
| 1332 |
+
f"{split}_f1", f1_score(targets, preds), sample_size, round=3
|
| 1333 |
+
)
|
data/unimol/losses/unimol.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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licensed under the MIT license found in the
|
| 3 |
+
# LICENSE file in the root directory of this source tree.
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from unicore import metrics
|
| 8 |
+
from unicore.losses import UnicoreLoss, register_loss
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@register_loss("unimol")
|
| 12 |
+
class UniMolLoss(UnicoreLoss):
|
| 13 |
+
def __init__(self, task):
|
| 14 |
+
super().__init__(task)
|
| 15 |
+
self.padding_idx = task.dictionary.pad()
|
| 16 |
+
self.seed = task.seed
|
| 17 |
+
self.dist_mean = 6.312581655060595
|
| 18 |
+
self.dist_std = 3.3899264663911888
|
| 19 |
+
|
| 20 |
+
def forward(self, model, sample, reduce=True):
|
| 21 |
+
input_key = "net_input"
|
| 22 |
+
target_key = "target"
|
| 23 |
+
masked_tokens = sample[target_key]["tokens_target"].ne(self.padding_idx)
|
| 24 |
+
sample_size = masked_tokens.long().sum()
|
| 25 |
+
(
|
| 26 |
+
logits_encoder,
|
| 27 |
+
encoder_distance,
|
| 28 |
+
encoder_coord,
|
| 29 |
+
x_norm,
|
| 30 |
+
delta_encoder_pair_rep_norm,
|
| 31 |
+
) = model(**sample[input_key], encoder_masked_tokens=masked_tokens)
|
| 32 |
+
target = sample[target_key]["tokens_target"]
|
| 33 |
+
if masked_tokens is not None:
|
| 34 |
+
target = target[masked_tokens]
|
| 35 |
+
masked_token_loss = F.nll_loss(
|
| 36 |
+
F.log_softmax(logits_encoder, dim=-1, dtype=torch.float32),
|
| 37 |
+
target,
|
| 38 |
+
ignore_index=self.padding_idx,
|
| 39 |
+
reduction="mean",
|
| 40 |
+
)
|
| 41 |
+
masked_pred = logits_encoder.argmax(dim=-1)
|
| 42 |
+
masked_hit = (masked_pred == target).long().sum()
|
| 43 |
+
masked_cnt = sample_size
|
| 44 |
+
loss = masked_token_loss * self.args.masked_token_loss
|
| 45 |
+
logging_output = {
|
| 46 |
+
"sample_size": 1,
|
| 47 |
+
"bsz": sample[target_key]["tokens_target"].size(0),
|
| 48 |
+
"seq_len": sample[target_key]["tokens_target"].size(1)
|
| 49 |
+
* sample[target_key]["tokens_target"].size(0),
|
| 50 |
+
"masked_token_loss": masked_token_loss.data,
|
| 51 |
+
"masked_token_hit": masked_hit.data,
|
| 52 |
+
"masked_token_cnt": masked_cnt,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
if encoder_coord is not None:
|
| 56 |
+
# real = mask + delta
|
| 57 |
+
coord_target = sample[target_key]["coord_target"]
|
| 58 |
+
masked_coord_loss = F.smooth_l1_loss(
|
| 59 |
+
encoder_coord[masked_tokens].view(-1, 3).float(),
|
| 60 |
+
coord_target[masked_tokens].view(-1, 3),
|
| 61 |
+
reduction="mean",
|
| 62 |
+
beta=1.0,
|
| 63 |
+
)
|
| 64 |
+
loss = loss + masked_coord_loss * self.args.masked_coord_loss
|
| 65 |
+
# restore the scale of loss for displaying
|
| 66 |
+
logging_output["masked_coord_loss"] = masked_coord_loss.data
|
| 67 |
+
|
| 68 |
+
if encoder_distance is not None:
|
| 69 |
+
dist_masked_tokens = masked_tokens
|
| 70 |
+
masked_dist_loss = self.cal_dist_loss(
|
| 71 |
+
sample, encoder_distance, dist_masked_tokens, target_key, normalize=True
|
| 72 |
+
)
|
| 73 |
+
loss = loss + masked_dist_loss * self.args.masked_dist_loss
|
| 74 |
+
logging_output["masked_dist_loss"] = masked_dist_loss.data
|
| 75 |
+
|
| 76 |
+
if self.args.x_norm_loss > 0 and x_norm is not None:
|
| 77 |
+
loss = loss + self.args.x_norm_loss * x_norm
|
| 78 |
+
logging_output["x_norm_loss"] = x_norm.data
|
| 79 |
+
|
| 80 |
+
if (
|
| 81 |
+
self.args.delta_pair_repr_norm_loss > 0
|
| 82 |
+
and delta_encoder_pair_rep_norm is not None
|
| 83 |
+
):
|
| 84 |
+
loss = (
|
| 85 |
+
loss + self.args.delta_pair_repr_norm_loss * delta_encoder_pair_rep_norm
|
| 86 |
+
)
|
| 87 |
+
logging_output[
|
| 88 |
+
"delta_pair_repr_norm_loss"
|
| 89 |
+
] = delta_encoder_pair_rep_norm.data
|
| 90 |
+
|
| 91 |
+
logging_output["loss"] = loss.data
|
| 92 |
+
return loss, 1, logging_output
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
def reduce_metrics(logging_outputs, split="valid") -> None:
|
| 96 |
+
"""Aggregate logging outputs from data parallel training."""
|
| 97 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
| 98 |
+
bsz = sum(log.get("bsz", 0) for log in logging_outputs)
|
| 99 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
| 100 |
+
seq_len = sum(log.get("seq_len", 0) for log in logging_outputs)
|
| 101 |
+
metrics.log_scalar("loss", loss_sum / sample_size, sample_size, round=3)
|
| 102 |
+
metrics.log_scalar("seq_len", seq_len / bsz, 1, round=3)
|
| 103 |
+
|
| 104 |
+
masked_loss = sum(log.get("masked_token_loss", 0) for log in logging_outputs)
|
| 105 |
+
metrics.log_scalar(
|
| 106 |
+
"masked_token_loss", masked_loss / sample_size, sample_size, round=3
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
masked_acc = sum(
|
| 110 |
+
log.get("masked_token_hit", 0) for log in logging_outputs
|
| 111 |
+
) / sum(log.get("masked_token_cnt", 0) for log in logging_outputs)
|
| 112 |
+
metrics.log_scalar("masked_acc", masked_acc, sample_size, round=3)
|
| 113 |
+
|
| 114 |
+
masked_coord_loss = sum(
|
| 115 |
+
log.get("masked_coord_loss", 0) for log in logging_outputs
|
| 116 |
+
)
|
| 117 |
+
if masked_coord_loss > 0:
|
| 118 |
+
metrics.log_scalar(
|
| 119 |
+
"masked_coord_loss",
|
| 120 |
+
masked_coord_loss / sample_size,
|
| 121 |
+
sample_size,
|
| 122 |
+
round=3,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
masked_dist_loss = sum(
|
| 126 |
+
log.get("masked_dist_loss", 0) for log in logging_outputs
|
| 127 |
+
)
|
| 128 |
+
if masked_dist_loss > 0:
|
| 129 |
+
metrics.log_scalar(
|
| 130 |
+
"masked_dist_loss", masked_dist_loss / sample_size, sample_size, round=3
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
x_norm_loss = sum(log.get("x_norm_loss", 0) for log in logging_outputs)
|
| 134 |
+
if x_norm_loss > 0:
|
| 135 |
+
metrics.log_scalar(
|
| 136 |
+
"x_norm_loss", x_norm_loss / sample_size, sample_size, round=3
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
delta_pair_repr_norm_loss = sum(
|
| 140 |
+
log.get("delta_pair_repr_norm_loss", 0) for log in logging_outputs
|
| 141 |
+
)
|
| 142 |
+
if delta_pair_repr_norm_loss > 0:
|
| 143 |
+
metrics.log_scalar(
|
| 144 |
+
"delta_pair_repr_norm_loss",
|
| 145 |
+
delta_pair_repr_norm_loss / sample_size,
|
| 146 |
+
sample_size,
|
| 147 |
+
round=3,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
@staticmethod
|
| 151 |
+
def logging_outputs_can_be_summed(is_train) -> bool:
|
| 152 |
+
"""
|
| 153 |
+
Whether the logging outputs returned by `forward` can be summed
|
| 154 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
| 155 |
+
to True will improves distributed training speed.
|
| 156 |
+
"""
|
| 157 |
+
return True
|
| 158 |
+
|
| 159 |
+
def cal_dist_loss(self, sample, dist, masked_tokens, target_key, normalize=False):
|
| 160 |
+
dist_masked_tokens = masked_tokens
|
| 161 |
+
masked_distance = dist[dist_masked_tokens, :]
|
| 162 |
+
masked_distance_target = sample[target_key]["distance_target"][
|
| 163 |
+
dist_masked_tokens
|
| 164 |
+
]
|
| 165 |
+
non_pad_pos = masked_distance_target > 0
|
| 166 |
+
if normalize:
|
| 167 |
+
masked_distance_target = (
|
| 168 |
+
masked_distance_target.float() - self.dist_mean
|
| 169 |
+
) / self.dist_std
|
| 170 |
+
masked_dist_loss = F.smooth_l1_loss(
|
| 171 |
+
masked_distance[non_pad_pos].view(-1).float(),
|
| 172 |
+
masked_distance_target[non_pad_pos].view(-1),
|
| 173 |
+
reduction="mean",
|
| 174 |
+
beta=1.0,
|
| 175 |
+
)
|
| 176 |
+
return masked_dist_loss
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@register_loss("unimol_infer")
|
| 180 |
+
class UniMolInferLoss(UnicoreLoss):
|
| 181 |
+
def __init__(self, task):
|
| 182 |
+
super().__init__(task)
|
| 183 |
+
self.padding_idx = task.dictionary.pad()
|
| 184 |
+
|
| 185 |
+
def forward(self, model, sample, reduce=True):
|
| 186 |
+
"""Compute the loss for the given sample.
|
| 187 |
+
|
| 188 |
+
Returns a tuple with three elements:
|
| 189 |
+
1) the loss
|
| 190 |
+
2) the sample size, which is used as the denominator for the gradient
|
| 191 |
+
3) logging outputs to display while training
|
| 192 |
+
"""
|
| 193 |
+
input_key = "net_input"
|
| 194 |
+
target_key = "target"
|
| 195 |
+
src_tokens = sample[input_key]["src_tokens"].ne(self.padding_idx)
|
| 196 |
+
(
|
| 197 |
+
encoder_rep,
|
| 198 |
+
encoder_pair_rep,
|
| 199 |
+
) = model(**sample[input_key], features_only=True)
|
| 200 |
+
sample_size = sample[input_key]["src_tokens"].size(0)
|
| 201 |
+
encoder_pair_rep_list = []
|
| 202 |
+
for i in range(sample_size): # rm padding token
|
| 203 |
+
encoder_pair_rep_list.append(encoder_pair_rep[i][src_tokens[i], :][:, src_tokens[i]].data.cpu().numpy())
|
| 204 |
+
logging_output = {
|
| 205 |
+
"mol_repr_cls": encoder_rep[:, 0, :].data.cpu().numpy(), # get cls token
|
| 206 |
+
"pair_repr": encoder_pair_rep_list,
|
| 207 |
+
"smi_name": sample[target_key]["smi_name"],
|
| 208 |
+
"bsz": sample[input_key]["src_tokens"].size(0),
|
| 209 |
+
}
|
| 210 |
+
return 0, sample_size, logging_output
|
data/unimol/models/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .drugclip import BindingAffinityModel
|
| 2 |
+
from .transformer_encoder_with_pair import TransformerEncoderWithPair
|
| 3 |
+
from .unimol import UniMolModel
|