diff --git a/.github/imgs/multi_point_mut_performance.png b/.github/imgs/multi_point_mut_performance.png new file mode 100644 index 0000000..4e70686 Binary files /dev/null and b/.github/imgs/multi_point_mut_performance.png differ diff --git a/.github/imgs/multi_point_mut_performance_violin.png b/.github/imgs/multi_point_mut_performance_violin.png new file mode 100644 index 0000000..4c4937f Binary files /dev/null and b/.github/imgs/multi_point_mut_performance_violin.png differ diff --git a/.github/imgs/single_point_mut_performance.png b/.github/imgs/single_point_mut_performance.png new file mode 100644 index 0000000..2061a32 Binary files /dev/null and b/.github/imgs/single_point_mut_performance.png differ diff --git a/.github/imgs/single_point_mut_performance_violin.png b/.github/imgs/single_point_mut_performance_violin.png new file mode 100644 index 0000000..8a14be7 Binary files /dev/null and b/.github/imgs/single_point_mut_performance_violin.png differ diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f40aa9e..62406bc 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -14,7 +14,7 @@ jobs: runs-on: [ubuntu-latest] strategy: matrix: - python-version: ["3.9", "3.10", "3.11"] + python-version: ["3.9", "3.10", "3.11", "3.12"] steps: - uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index 21b797f..eb829a7 100644 --- a/.gitignore +++ b/.gitignore @@ -388,3 +388,6 @@ avGFP_shortened_dca_encoded.csv datasets/AVGFP/avGFP_shortened.csv avGFP_dca_encoded.csv scripts/Runtime_tests/runtimes.png +datasets/AVGFP/Recomb_Double_Split/Predictions_Hybrid_TopRecomb_Double_Split.txt +scripts/ProteinGym_runs/single_point_mut_performance_violin.png +scripts/ProteinGym_runs/multi_point_mut_performance_violin.png diff --git a/.vscode/launch.json b/.vscode/launch.json index 036fea6..8491667 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -6,7 +6,7 @@ "configurations": [ { "name": "Python: PyPEF Help", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -19,7 +19,7 @@ { "name": "Python: PyPEF MKLSTS ANEH", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -35,7 +35,7 @@ { "name": "Python: PyPEF MKLSTS avGFP", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -49,9 +49,26 @@ ] }, + { + "name": "Python: PyPEF MKPS avGFP drecomb", + "type": "debugpy", + "request": "launch", + "env": {"PYTHONPATH": "${workspaceFolder}"}, + "program": "${workspaceFolder}/pypef/main.py", + "console": "integratedTerminal", + "justMyCode": true, + "cwd": "${workspaceFolder}/datasets/AVGFP/", + "args": [ + "mkps", + "--wt", "P42212_F64L.fasta", + "--input", "avGFP.csv", + "--drecomb" + ] + }, + { "name": "Python: PyPEF ml -e onehot pls_loocv", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -73,7 +90,7 @@ // or // 2. $pypef hybrid -m GREMLIN -t TS.fasl --params GREMLIN "name": "Python: PyPEF save GREMLIN avGFP model", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -87,9 +104,27 @@ ] }, + { + "name": "Python: PyPEF hybrid LS-TS GREMLIN-DCA avGFP", + "type": "debugpy", + "request": "launch", + "env": {"PYTHONPATH": "${workspaceFolder}"}, + "program": "${workspaceFolder}/pypef/main.py", + "console": "integratedTerminal", + "justMyCode": true, + "cwd": "${workspaceFolder}/datasets/AVGFP/", + "args": [ + "hybrid", + //"-m", "GREMLIN", // optional, not required + "--ls", "LS.fasl", + "--ts", "TS.fasl", + "--params", "GREMLIN" + ] + }, + { "name": "Python: PyPEF hybrid/only-TS-zero-shot GREMLIN-DCA avGFP", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -106,7 +141,7 @@ { "name": "Python: PyPEF hybrid/only-PS-zero-shot GREMLIN-DCA avGFP", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -121,11 +156,45 @@ ] }, + { + "name": "Python: PyPEF hybrid/only-PS-zero-shot GREMLIN-DCA avGFP drecomb II", + "type": "debugpy", + "request": "launch", + "env": {"PYTHONPATH": "${workspaceFolder}"}, + "program": "${workspaceFolder}/pypef/main.py", + "console": "integratedTerminal", + "justMyCode": true, + "cwd": "${workspaceFolder}/datasets/AVGFP/", + "args": [ + "hybrid", + "-m", "HYBRIDgremlin", + "--pmult", "--drecomb", + "--params", "GREMLIN" + ] + }, + + { + "name": "Python: PyPEF hybrid/only-PS-zero-shot GREMLIN-DCA avGFP drecomb", + "type": "debugpy", + "request": "launch", + "env": {"PYTHONPATH": "${workspaceFolder}"}, + "program": "${workspaceFolder}/pypef/main.py", + "console": "integratedTerminal", + "justMyCode": true, + "cwd": "${workspaceFolder}/datasets/AVGFP/", + "args": [ + "hybrid", + "-m", "GREMLIN", + "--pmult", "--drecomb", + "--params", "GREMLIN" + ] + }, + { // PLMC zero-shot steps: // 1. $pypef param_inference --params uref100_avgfp_jhmmer_119_plmc_42.6.params // 2. $pypef hybrid -t TS.fasl --params PLMC "name": "Python: PyPEF save PLMC avGFP model", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -140,7 +209,7 @@ { "name": "Python: PyPEF hybrid/only-TS-zero-shot PLMC-DCA avGFP", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -157,7 +226,7 @@ { "name": "Python: PyPEF hybrid/only-PS-zero-shot PLMC-DCA avGFP", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -175,7 +244,7 @@ { "name": "Python: PyPEF hybrid/only-PS-zero-shot PLMC-DCA variant 2 avGFP", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", @@ -193,7 +262,7 @@ { "name": "Python: PyPEF !wrong! MSA input format (STO)", - "type": "python", + "type": "debugpy", "request": "launch", "env": {"PYTHONPATH": "${workspaceFolder}"}, "program": "${workspaceFolder}/pypef/main.py", diff --git a/LICENSE.md b/LICENSE.md index 79c8373..52df679 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -8,445 +8,188 @@ PyPEF – an Integrated Framework for Data-driven Protein Engineering, *Journal PyPEF: Pythonic Protein Engineering Framework ------ - Niklas E. Siedhoff + Niklas E. Siedhoff Alexander-Maurice Illig LICENSE ------ -Attribution-NonCommercial-ShareAlike 4.0 International -CC BY-NC-SA 4.0 + +CC BY-SA (Attribution-ShareAlike 4.0 International, https://creativecommons.org/licenses/by-sa/4.0/) + +This license enables reusers to distribute, remix, adapt, and build upon the material in any medium or format, so long as attribution is given to the creator. The license allows for commercial use. If you remix, adapt, or build upon the material, you must license the modified material under identical terms. CC BY-SA includes the following elements: + +- BY: credit must be given to the creator. +- SA: Adaptations must be shared under the same terms. + +Attribution-ShareAlike 4.0 International +CC BY-SA 4.0 ======================================================================= -Creative Commons Corporation ("Creative Commons") is not a law firm and -does not provide legal services or legal advice. Distribution of -Creative Commons public licenses does not create a lawyer-client or -other relationship. Creative Commons makes its licenses and related -information available on an "as-is" basis. Creative Commons gives no -warranties regarding its licenses, any material licensed under their -terms and conditions, or any related information. Creative Commons -disclaims all liability for damages resulting from their use to the -fullest extent possible. +**About the license and Creative Commons** + +Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. **Using Creative Commons Public Licenses** -Creative Commons public licenses provide a standard set of terms and -conditions that creators and other rights holders may use to share -original works of authorship and other material subject to copyright -and certain other rights specified in the public license below. The -following considerations are for informational purposes only, are not -exhaustive, and do not form part of our licenses. - -**Considerations for licensors:** Our public licenses are -intended for use by those authorized to give the public -permission to use material in ways otherwise restricted by -copyright and certain other rights. Our licenses are -irrevocable. Licensors should read and understand the terms -and conditions of the license they choose before applying it. -Licensors should also secure all rights necessary before -applying our licenses so that the public can reuse the -material as expected. Licensors should clearly mark any -material not subject to the license. This includes other CC- -licensed material, or material used under an exception or -limitation to copyright. More considerations for licensors: -https://wiki.creativecommons.org/Considerations_for_licensors - -**Considerations for the public:** By using one of our public -licenses, a licensor grants the public permission to use the -licensed material under specified terms and conditions. If -the licensor's permission is not necessary for any reason--for -example, because of any applicable exception or limitation to -copyright--then that use is not regulated by the license. Our -licenses grant only permissions under copyright and certain -other rights that a licensor has authority to grant. Use of -the licensed material may still be restricted for other -reasons, including because others have copyright or other -rights in the material. A licensor may make special requests, -such as asking that all changes be marked or described. -Although not required by our licenses, you are encouraged to -respect those requests where reasonable. More_considerations -for the public: -https://wiki.creativecommons.org/Considerations_for_licensees - - - -Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International -Public License ------- -By exercising the Licensed Rights (defined below), You accept and agree -to be bound by the terms and conditions of this Creative Commons -Attribution-NonCommercial-ShareAlike 4.0 International Public License -("Public License"). To the extent this Public License may be -interpreted as a contract, You are granted the Licensed Rights in -consideration of Your acceptance of these terms and conditions, and the -Licensor grants You such rights in consideration of benefits the -Licensor receives from making the Licensed Material available under -these terms and conditions. +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. +**Considerations for licensors:** +Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: https://wiki.creativecommons.org/wiki/Considerations_for_licensors_and_licensees#Considerations_for_licensors +**Considerations for the public:** +By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: https://wiki.creativecommons.org/wiki/Considerations_for_licensors_and_licensees#Considerations_for_licensees + +Attribution-ShareAlike 4.0 International +------ +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. **Section 1 -- Definitions.** -a. **Adapted Material** means material subject to Copyright and Similar -Rights that is derived from or based upon the Licensed Material -and in which the Licensed Material is translated, altered, -arranged, transformed, or otherwise modified in a manner requiring -permission under the Copyright and Similar Rights held by the -Licensor. For purposes of this Public License, where the Licensed -Material is a musical work, performance, or sound recording, -Adapted Material is always produced where the Licensed Material is -synched in timed relation with a moving image. +a. **Adapted Material** means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. -b. **Adapter's License** means the license You apply to Your Copyright -and Similar Rights in Your contributions to Adapted Material in -accordance with the terms and conditions of this Public License. +b. **Adapter's License** means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. **BY-NC-SA Compatible License** means a license listed at https://creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. -d. **Copyright and Similar Rights** means copyright and/or similar rights -closely related to copyright including, without limitation, -performance, broadcast, sound recording, and Sui Generis Database -Rights, without regard to how the rights are labeled or -categorized. For purposes of this Public License, the rights -specified in Section 2(b)(1)-(2) are not Copyright and Similar -Rights. - -e. **Effective Technological Measures** means those measures that, in the -absence of proper authority, may not be circumvented under laws -fulfilling obligations under Article 11 of the WIPO Copyright -Treaty adopted on December 20, 1996, and/or similar international -agreements. - -f. **Exceptions and Limitations** means fair use, fair dealing, and/or -any other exception or limitation to Copyright and Similar Rights -that applies to Your use of the Licensed Material. - -g. **License Elements** means the license attributes listed in the name -of a Creative Commons Public License. The License Elements of this -Public License are Attribution, NonCommercial, and ShareAlike. - -h. **Licensed Material** means the artistic or literary work, database, -or other material to which the Licensor applied this Public -License. - -i. **Licensed Rights** means the rights granted to You subject to the -terms and conditions of this Public License, which are limited to -all Copyright and Similar Rights that apply to Your use of the -Licensed Material and that the Licensor has authority to license. - -j. **Licensor** means the individual(s) or entity(ies) granting rights -under this Public License. - -k. **NonCommercial** means not primarily intended for or directed towards -commercial advantage or monetary compensation. For purposes of -this Public License, the exchange of the Licensed Material for -other material subject to Copyright and Similar Rights by digital -file-sharing or similar means is NonCommercial provided there is -no payment of monetary compensation in connection with the -exchange. - -l. **Share** means to provide material to the public by any means or -process that requires permission under the Licensed Rights, such -as reproduction, public display, public performance, distribution, -dissemination, communication, or importation, and to make material -available to the public including in ways that members of the -public may access the material from a place and at a time -individually chosen by them. - -m. **Sui Generis Database Rights** means rights other than copyright -resulting from Directive 96/9/EC of the European Parliament and of -the Council of 11 March 1996 on the legal protection of databases, -as amended and/or succeeded, as well as other essentially -equivalent rights anywhere in the world. - -n. **You** means the individual or entity exercising the Licensed Rights -under this Public License. **Your** has a corresponding meaning. +d. **Copyright and Similar Rights** means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. +e. **Effective Technological Measures** means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. -**Section 2 -- Scope.** - -a. **License grant.** +f. **Exceptions and Limitations** means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. -1. Subject to the terms and conditions of this Public License, -the Licensor hereby grants You a worldwide, royalty-free, -non-sublicensable, non-exclusive, irrevocable license to -exercise the Licensed Rights in the Licensed Material to: +g. **License Elements** means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. -a. reproduce and Share the Licensed Material, in whole or -in part, for NonCommercial purposes only; and +h. **Licensed Material** means the artistic or literary work, database, or other material to which the Licensor applied this Public License. -b. produce, reproduce, and Share Adapted Material for -NonCommercial purposes only. +i. **Licensed Rights** means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. -2. Exceptions and Limitations. For the avoidance of doubt, where -Exceptions and Limitations apply to Your use, this Public -License does not apply, and You do not need to comply with -its terms and conditions. +j. **Licensor** means the individual(s) or entity(ies) granting rights under this Public License. -3. Term. The term of this Public License is specified in Section -6(a). +k. **Share** means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. -4. Media and formats; technical modifications allowed. The -Licensor authorizes You to exercise the Licensed Rights in -all media and formats whether now known or hereafter created, -and to make technical modifications necessary to do so. The -Licensor waives and/or agrees not to assert any right or -authority to forbid You from making technical modifications -necessary to exercise the Licensed Rights, including -technical modifications necessary to circumvent Effective -Technological Measures. For purposes of this Public License, -simply making modifications authorized by this Section 2(a) -(4) never produces Adapted Material. - -5. Downstream recipients. - -a. Offer from the Licensor -- Licensed Material. Every -recipient of the Licensed Material automatically -receives an offer from the Licensor to exercise the -Licensed Rights under the terms and conditions of this -Public License. - -b. Additional offer from the Licensor -- Adapted Material. -Every recipient of Adapted Material from You -automatically receives an offer from the Licensor to -exercise the Licensed Rights in the Adapted Material -under the conditions of the Adapter's License You apply. - -c. No downstream restrictions. You may not offer or impose -any additional or different terms or conditions on, or -apply any Effective Technological Measures to, the -Licensed Material if doing so restricts exercise of the -Licensed Rights by any recipient of the Licensed -Material. - -6. No endorsement. Nothing in this Public License constitutes or -may be construed as permission to assert or imply that You -are, or that Your use of the Licensed Material is, connected -with, or sponsored, endorsed, or granted official status by, -the Licensor or others designated to receive attribution as -provided in Section 3(a)(1)(A)(i). +l. **Sui Generis Database Rights** means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. -b. **Other rights.** +m. **You** means the individual or entity exercising the Licensed Rights under this Public License. **Your** has a corresponding meaning. -1. Moral rights, such as the right of integrity, are not -licensed under this Public License, nor are publicity, -privacy, and/or other similar personality rights; however, to -the extent possible, the Licensor waives and/or agrees not to -assert any such rights held by the Licensor to the limited -extent necessary to allow You to exercise the Licensed -Rights, but not otherwise. +**Section 2 -- Scope.** -2. Patent and trademark rights are not licensed under this -Public License. +a. **License grant.** -3. To the extent possible, the Licensor waives any right to -collect royalties from You for the exercise of the Licensed -Rights, whether directly or through a collecting society -under any voluntary or waivable statutory or compulsory -licensing scheme. In all other cases the Licensor expressly -reserves any right to collect such royalties, including when -the Licensed Material is used other than for NonCommercial -purposes. +1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: +A. reproduce and Share the Licensed Material, in whole or in part; and +B. produce, reproduce, and Share Adapted Material. +2. **Exceptions and Limitations.** For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. -**Section 3 -- License Conditions.** +3. **Term.** The term of this Public License is specified in Section +6(a). -Your exercise of the Licensed Rights is expressly made subject to the -following conditions. +4. **Media and formats; technical modifications allowed.** The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. -a. **Attribution.** +5. Downstream recipients. + A. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. +B. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply. +C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. -1. If You Share the Licensed Material (including in modified -form), You must: +6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i) . -a. retain the following if it is supplied by the Licensor -with the Licensed Material: +b. **Other rights.** -i. identification of the creator(s) of the Licensed -Material and any others designated to receive -attribution, in any reasonable manner requested by -the Licensor (including by pseudonym if -designated); +1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. -ii. a copyright notice; +2. Patent and trademark rights are not licensed under this Public License. -iii. a notice that refers to this Public License; +3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. -iv. a notice that refers to the disclaimer of -warranties; +**Section 3 -- License Conditions.** -v. a URI or hyperlink to the Licensed Material to the -extent reasonably practicable; +Your exercise of the Licensed Rights is expressly made subject to the following conditions. -b. indicate if You modified the Licensed Material and -retain an indication of any previous modifications; and +a. **Attribution.** -c. indicate the Licensed Material is licensed under this -Public License, and include the text of, or the URI or -hyperlink to, this Public License. +1. If You Share the Licensed Material (including in modified form), You must: +A. retain the following if it is supplied by the Licensor +with the Licensed Material: +    i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); +    ii. a copyright notice; +    iii. a notice that refers to this Public License; +    iv. a notice that refers to the disclaimer of warranties; +    v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; +B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and +C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. -2. You may satisfy the conditions in Section 3(a)(1) in any -reasonable manner based on the medium, means, and context in -which You Share the Licensed Material. For example, it may be -reasonable to satisfy the conditions by providing a URI or -hyperlink to a resource that includes the required -information. +2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. -3. If requested by the Licensor, You must remove any of the -information required by Section 3(a)(1)(A) to the extent -reasonably practicable. +3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. b. **ShareAlike.** -In addition to the conditions in Section 3(a), if You Share -Adapted Material You produce, the following conditions also apply. - -1. The Adapter's License You apply must be a Creative Commons -license with the same License Elements, this version or -later, or a BY-NC-SA Compatible License. +In addition to the conditions in Section 3(a) , if You Share Adapted Material You produce, the following conditions also apply. -2. You must include the text of, or the URI or hyperlink to, the -Adapter's License You apply. You may satisfy this condition -in any reasonable manner based on the medium, means, and -context in which You Share Adapted Material. +1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. -3. You may not offer or impose any additional or different terms -or conditions on, or apply any Effective Technological -Measures to, Adapted Material that restrict exercise of the -rights granted under the Adapter's License You apply. +2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. +3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. **Section 4 -- Sui Generis Database Rights.** -Where the Licensed Rights include Sui Generis Database Rights that -apply to Your use of the Licensed Material: +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: -a. for the avoidance of doubt, Section 2(a)(1) grants You the right -to extract, reuse, reproduce, and Share all or a substantial -portion of the contents of the database for NonCommercial purposes -only; +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; -b. if You include all or a substantial portion of the database -contents in a database in which You have Sui Generis Database -Rights, then the database in which You have Sui Generis Database -Rights (but not its individual contents) is Adapted Material, -including for purposes of Section 3(b); and +b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b) ; and -c. You must comply with the conditions in Section 3(a) if You Share -all or a substantial portion of the contents of the database. - -For the avoidance of doubt, this Section 4 supplements and does not -replace Your obligations under this Public License where the Licensed -Rights include other Copyright and Similar Rights. +c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. **Section 5 -- Disclaimer of Warranties and Limitation of Liability.** -**a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE -EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS -AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF -ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, -IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, -WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR -PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, -ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT -KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT -ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.** - -**b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE -TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, -NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, -INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, -COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR -USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN -ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR -DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR -IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.** - -c. The disclaimer of warranties and limitation of liability provided -above shall be interpreted in a manner that, to the extent -possible, most closely approximates an absolute disclaimer and -waiver of all liability. +**a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.** + +**b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.** +c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. **Section 6 -- Term and Termination.** -a. This Public License applies for the term of the Copyright and -Similar Rights licensed here. However, if You fail to comply with -this Public License, then Your rights under this Public License -terminate automatically. +a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. -b. Where Your right to use the Licensed Material has terminated under -Section 6(a), it reinstates: +b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: -1. automatically as of the date the violation is cured, provided -it is cured within 30 days of Your discovery of the -violation; or +1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. -For the avoidance of doubt, this Section 6(b) does not affect any -right the Licensor may have to seek remedies for Your violations -of this Public License. +For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. -c. For the avoidance of doubt, the Licensor may also offer the -Licensed Material under separate terms or conditions or stop -distributing the Licensed Material at any time; however, doing so -will not terminate this Public License. +c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. -d. Sections 1, 5, 6, 7, and 8 survive termination of this Public -License. +d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. **Section 7 -- Other Terms and Conditions.** -a. The Licensor shall not be bound by any additional or different -terms or conditions communicated by You unless expressly agreed. - -b. Any arrangements, understandings, or agreements regarding the -Licensed Material not stated herein are separate from and -independent of the terms and conditions of this Public License. +a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. +b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. **Section 8 -- Interpretation.** -a. For the avoidance of doubt, this Public License does not, and -shall not be interpreted to, reduce, limit, restrict, or impose -conditions on any use of the Licensed Material that could lawfully -be made without permission under this Public License. +a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. -b. To the extent possible, if any provision of this Public License is -deemed unenforceable, it shall be automatically reformed to the -minimum extent necessary to make it enforceable. If the provision -cannot be reformed, it shall be severed from this Public License -without affecting the enforceability of the remaining terms and -conditions. +b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. -c. No term or condition of this Public License will be waived and no -failure to comply consented to unless expressly agreed to by the -Licensor. +c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. -d. Nothing in this Public License constitutes or may be interpreted -as a limitation upon, or waiver of, any privileges and immunities -that apply to the Licensor or You, including from the legal -processes of any jurisdiction or authority. +d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. -======================================================================= +============================================================================================ + +**About Creative Commons** + + + Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the "Licensor." The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication . Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies , Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. -Creative Commons is not a party to its public -licenses. Notwithstanding, Creative Commons may elect to apply one of -its public licenses to material it publishes and in those instances -will be considered the “Licensor.” The text of the Creative Commons -public licenses is dedicated to the public domain under the CC0 Public -Domain Dedication. Except for the limited purpose of indicating that -material is shared under a Creative Commons public license or as -otherwise permitted by the Creative Commons policies published at -https://creativecommons.org/policies, Creative Commons does not authorize the -use of the trademark "Creative Commons" or any other trademark or logo -of Creative Commons without its prior written consent including, -without limitation, in connection with any unauthorized modifications -to any of its public licenses or any other arrangements, -understandings, or agreements concerning use of licensed material. For -the avoidance of doubt, this paragraph does not form part of the -public licenses. - -Creative Commons may be contacted at https://creativecommons.org. +Creative Commons may be contacted at https://creativecommons.org. diff --git a/README.md b/README.md index bd5c81a..3f3a8e9 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,19 @@ This repository contains the source files and supplementary information for the PyPEF framework, which is described in
Niklas E. Siedhoff*1,§*, Alexander-Maurice Illig*1,§*, Ulrich Schwaneberg*1,2*, Mehdi D. Davari*3,\**,
-PyPEF – An Integrated Framework for Data-Driven Protein Engineering, *J. Chem. Inf. Model.* 2021, 61, 3463-3476
+PyPEF – An Integrated Framework for Data-Driven Protein Engineering,
+*J. Chem. Inf. Model.* 2021, 61, 3463-3476
https://doi.org/10.1021/acs.jcim.1c00099
as well as additional framework features described in the preprint
Alexander-Maurice Illig*1,§*, Niklas E. Siedhoff*1,§*, Ulrich Schwaneberg*1,2*, Mehdi D. Davari*3,\**,
-A hybrid model combining evolutionary probability and machine learning leverages data-driven protein engineering, *To be published*
-Preprint available at bioRxiv: https://doi.org/10.1101/2022.06.07.495081. +A hybrid model combining evolutionary probability and machine learning leverages data-driven protein engineering,
+preprint available at bioRxiv: https://doi.org/10.1101/2022.06.07.495081
+*now published as*
+Evolutionary Probability and Stacked Regressions Enable Data-Driven Protein Engineering with Minimized Experimental Effort,
+*J. Chem. Inf. Model.* 2024, 64, 16, 6350–6360
+https://doi.org/10.1021/acs.jcim.4c00704 *1*Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany
*2*DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany
@@ -463,14 +468,20 @@ This list is by no means complete, see ProteinGym [repository](https://github.co The performance of the GREMLIN model used is shown in the following for predicting -(I) single substitution effects (blue), including Hybrid model performances with N_Train = {25, 50, 75, 100, 200} (orange, green, red, purple, brown) +(I) single substitution effects (blue), including Hybrid model performances with N_Train = {100, 200, 1000} (orange, green, and red, respectively)

- drawing + drawing +

+

+ drawing

-(II) multi-substitution effects (blue), including Hybrid model performances with N_Train = {25, 50, 75, 100, 200} (orange, green, red, purple, brown) +(II) multi-substitution effects (blue), including Hybrid model performances with N_Train = {100, 200, 1000} (orange, green, and red, respectively) +

+ drawing +

- drawing + drawing

for ProteinGym datasets computed using the scripts located at [scripts/ProteinGym_runs](scripts/ProteinGym_runs). diff --git a/pypef/__init__.py b/pypef/__init__.py index 1a97f16..6b35e02 100644 --- a/pypef/__init__.py +++ b/pypef/__init__.py @@ -2,19 +2,14 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution - -__version__ = '0.3.4' +__version__ = '0.3.6' diff --git a/pypef/dca/dca_run.py b/pypef/dca/dca_run.py index 1447a98..1baa4bc 100644 --- a/pypef/dca/dca_run.py +++ b/pypef/dca/dca_run.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution import logging logger = logging.getLogger('pypef.dca.dca_run') diff --git a/pypef/dca/gremlin_inference.py b/pypef/dca/gremlin_inference.py index 6dd501d..dfff281 100644 --- a/pypef/dca/gremlin_inference.py +++ b/pypef/dca/gremlin_inference.py @@ -1,20 +1,16 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -# Created on 17 May 2023 +# Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution """ Code taken from GREMLIN repository available at https://github.com/sokrypton/GREMLIN_CPP/ diff --git a/pypef/dca/hybrid_model.py b/pypef/dca/hybrid_model.py index 9a72785..4acccd1 100644 --- a/pypef/dca/hybrid_model.py +++ b/pypef/dca/hybrid_model.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution # Contains Python code used for the approach presented in our 'hybrid modeling' paper # Preprint available at: https://doi.org/10.1101/2022.06.07.495081 @@ -28,11 +24,14 @@ from os.path import isfile, join from typing import Union import logging + +import pypef.dca.plmc_encoding logger = logging.getLogger('pypef.dca.hybrid_model') import numpy as np import sklearn.base from scipy.stats import spearmanr +from scipy.optimize import curve_fit from sklearnex import patch_sklearn patch_sklearn(verbose=False) from sklearn.linear_model import Ridge @@ -44,7 +43,7 @@ remove_nan_encoded_positions, get_wt_sequence, split_variants ) -from pypef.dca.plmc_encoding import PLMC, get_dca_data_parallel, get_encoded_sequence, EffectiveSiteError +from pypef.dca.plmc_encoding import PLMC, get_dca_data_parallel, get_encoded_sequence from pypef.utils.to_file import predictions_out from pypef.utils.plot import plot_y_true_vs_y_pred import pypef.dca.gremlin_inference @@ -55,20 +54,24 @@ class DCAHybridModel: # TODO: Implementation of other regression techniques (CVRegression models) def __init__( self, - x_train: np.ndarray = None, - y_train: np.ndarray = None, - x_test: np.ndarray = None, # not necessary for training - y_test: np.ndarray = None, # not necessary for training - x_wt=None, - alphas=None, # Ridge regression grid for the parameter 'alpha' - parameter_range=None, # Parameter range of 'beta_1' and 'beta_2' with lower bound <= x <= upper bound + x_train: np.ndarray | None = None, # DCA-encoded sequences + y_train: np.ndarray | None = None, # true labels + x_test: np.ndarray | None = None, # not necessary for training + y_test: np.ndarray | None = None, # not necessary for training + x_wt: np.ndarray | None = None, # Wild type encoding + alphas: np.ndarray | None = None, # Ridge regression grid for the parameter 'alpha' + parameter_range: list | None = None, # Parameter range of 'beta_1' and 'beta_2' with lower bound <= x <= upper bound + logistic: bool | None = None ): if parameter_range is None: parameter_range = [(0, 1), (0, 1)] if alphas is None: alphas = np.logspace(-6, 6, 100) - self.alphas = alphas + if logistic is None: + logistic = False self.parameter_range = parameter_range + self.alphas = alphas + self.logistic = logistic self.x_train = x_train self.y_train = y_train self.x_test = x_test @@ -140,6 +143,10 @@ def _delta_x( """ return np.subtract(x, self.x_wild_type) + @staticmethod + def logistic_func(delta_e, *args): + return args[0] / (1 + np.exp(-args[1] * (delta_e - args[2]))) + args[3] + def _delta_e( self, x: np.ndarray @@ -162,6 +169,25 @@ def _delta_e( and wild-type. """ return np.sum(self._delta_x(x), axis=1) + + def _logistic_delta_e( + self, + ys, + delta_es + ): + popt, _pcov = curve_fit( + self.logistic_func, + delta_es, + ys, + maxfev=10000, + p0=(1, 1, -7, 1), + bounds=[(-5, -5, -20, -20), (5, 5, 0, 20)] + ) + y_dca_logistic = self.logistic_func(ys, delta_es, *popt) + #import matplotlib.pyplot as plt + #plt.scatter(np.array(delta_es).argsort().argsort(), delta_es);plt.savefig('delta_es.png', dpi=300);plt.clf() + #plt.scatter(np.array(y_dca_logistic).argsort().argsort(), y_dca_logistic);plt.savefig('delta_es_logistic.png', dpi=300);plt.clf() + return y_dca_logistic def _spearmanr_dca(self) -> float: """ @@ -175,8 +201,8 @@ def _spearmanr_dca(self) -> float: or beta_1 * y_dca - beta_2 * y_ridge. """ - y_dca = self._delta_e(self.X) - return self.spearmanr(self.y, y_dca) + y_dca = self._delta_e(self.x_train) + return self.spearmanr(self.y_train, y_dca) def ridge_predictor( self, @@ -234,7 +260,7 @@ def _y_hybrid( """ # Uncomment lines below to see if correlation between # y_true and y_dca is positive or negative: - # logger.info(f'Positive or negative correlation of (all data) y_true ' + # logger.info(f'Positive or negative correlation of (train data) y_true ' # f'and y_dca (+/-?): {self._spearmanr_dca:.3f}') if self._spearmanr_dca >= 0: return beta_1 * y_dca + beta_2 * y_ridge @@ -245,7 +271,8 @@ def _adjust_betas( self, y: np.ndarray, y_dca: np.ndarray, - y_ridge: np.ndarray + y_ridge: np.ndarray, + rank_based: bool = False ) -> np.ndarray: """ Find parameters that maximize the absolut Spearman rank @@ -266,16 +293,20 @@ def _adjust_betas( 'beta_1' and 'beta_2' that maximize the absolut Spearman rank correlation coefficient. """ - loss = lambda b: -np.abs(self.spearmanr(y, b[0] * y_dca + b[1] * y_ridge)) - minimizer = differential_evolution(loss, bounds=self.parameter_range, tol=1e-4) + if rank_based: + loss = lambda params: np.sum(np.power(y - params[0] * y_dca - params[1] * y_ridge, 2)) + minimizer = differential_evolution(loss, bounds=[(0, 10), (0, 10)], tol=1e-4) + else: + loss = lambda params: -np.abs(self.spearmanr(y, params[0] * y_dca + params[1] * y_ridge)) + minimizer = differential_evolution(loss, bounds=self.parameter_range, tol=1e-4) return minimizer.x def settings( self, x_train: np.ndarray, y_train: np.ndarray, - train_size_fit=0.66, - random_state=42 + train_size_fit: float = 0.66, + random_state: int = 42 ) -> tuple: """ Get the adjusted parameters 'beta_1', 'beta_2', and the @@ -322,16 +353,23 @@ def settings( If this is not given -> return parameter setting for 'EVmutation' model. """ - y_ttrain_min_cv = int(0.2 * len(y_ttrain)) # 0.2 because of five-fold cross validation (1/5) + # int(0.2 * len(y_ttrain)) due to 5-fold-CV for adjusting the (Ridge) regressor + y_ttrain_min_cv = int(0.2 * len(y_ttrain)) if y_ttrain_min_cv < 2: return 1.0, 0.0, None - y_dca_ttest = self._delta_e(X_ttest) + if self.logistic: + y_dca_ttest = self._logistic_delta_e(ys=y_ttest, delta_es=self._delta_e(X_ttest)) + else: + y_dca_ttest = self._delta_e(X_ttest) + + ridge = self.ridge_predictor(X_ttrain, y_ttrain) y_ridge_ttest = ridge.predict(X_ttest) - beta1, beta2 = self._adjust_betas(y_ttest, y_dca_ttest, y_ridge_ttest) + beta1, beta2 = self._adjust_betas( + y_ttest, y_dca_ttest, y_ridge_ttest, rank_based=self.logistic) return beta1, beta2, ridge def hybrid_prediction( @@ -367,7 +405,7 @@ def hybrid_prediction( y_ridge = np.random.random(len(y_dca)) # in order to suppress error else: y_ridge = reg.predict(x) - # adjusting: + or - on all data --> +-beta_1 * y_dca + beta_2 * y_ridge + # adjusting: + or - on train data --> +-beta_1 * y_dca + beta_2 * y_ridge return self._y_hybrid(y_dca, y_ridge, beta_1, beta_2) def split_performance( @@ -441,6 +479,7 @@ def ls_ts_performance(self): self.y_test, self.hybrid_prediction(self.x_test, reg, beta_1, beta_2) ) + self.beta_1, self.beta_2, self.regressor = beta_1, beta_2, reg return spearman_r, reg, beta_1, beta_2 def train_and_test( @@ -581,10 +620,12 @@ def get_model_path(model: str): elif isfile(f'Pickles/{model}'): model_path = f'Pickles/{model}' else: - raise SystemError("Did not find specified model file in current working directory " - " or /Pickles subdirectory. Make sure to train/save a model first " - "(e.g., for saving a GREMLIN model, type \"pypef param_inference --msa TARGET_MSA.a2m\" " - "or, for saving a plmc model, type \"pypef param_inference --params TARGET_PLMC.params\").") + raise SystemError( + "Did not find specified model file in current working directory " + " or /Pickles subdirectory. Make sure to train/save a model first " + "(e.g., for saving a GREMLIN model, type \"pypef param_inference --msa TARGET_MSA.a2m\" " + "or, for saving a plmc model, type \"pypef param_inference --params TARGET_PLMC.params\")." + ) return model_path except TypeError: raise SystemError("No provided model. " @@ -600,6 +641,10 @@ def get_model_and_type( and to load the model from the identified plmc pickle file or from the loaded pickle dictionary. """ + if type(params_file) == pypef.dca.gremlin_inference.GREMLIN: + return params_file, 'GREMLIN' + if type(params_file) == pypef.dca.plmc_encoding.PLMC: + return params_file, 'PLMC' file_path = get_model_path(params_file) try: with open(file_path, 'rb') as read_pkl_file: @@ -1103,11 +1148,11 @@ def predict_ps( # also predicting "pmult" dict directories model_pickle_file = params_file logger.info(f'Trying to load model from saved parameters (Pickle file): {model_pickle_file}...') else: - logger.info(f'Loading model from saved model (Pickle file): {model_pickle_file}...') + logger.info(f'Loading model from saved model (Pickle file {os.path.abspath(model_pickle_file)})...') model, model_type = get_model_and_type(model_pickle_file) if model_type == 'PLMC' or model_type == 'GREMLIN': - logger.info(f'No hybrid model provided – falling back to a statistical DCA model.') + logger.info(f'No hybrid model provided - falling back to a statistical DCA model.') elif model_type == 'Hybrid': beta_1, beta_2, reg = model.beta_1, model.beta_2, model.regressor if reg is None: @@ -1136,13 +1181,13 @@ def predict_ps( # also predicting "pmult" dict directories file_path = os.path.join(path, file) sequences, variants, _ = get_sequences_from_file(file_path) if model_type != 'Hybrid': - x_test, test_variants, x_wt, *_ = plmc_or_gremlin_encoding( + x_test, _, _, _, x_wt, *_ = plmc_or_gremlin_encoding( variants, sequences, None, model, threads=threads, verbose=False, substitution_sep=separator) ys_pred = get_delta_e_statistical_model(x_test, x_wt) else: # Hybrid model input requires params from plmc or GREMLIN model ##encoding_model, encoding_model_type = get_model_and_type(params_file) - x_test, test_variants, *_ = plmc_or_gremlin_encoding( + x_test, _test_variants, *_ = plmc_or_gremlin_encoding( variants, sequences, None, params_file, threads=threads, verbose=False, substitution_sep=separator ) diff --git a/pypef/dca/plmc_encoding.py b/pypef/dca/plmc_encoding.py index 995213f..eb72ac7 100644 --- a/pypef/dca/plmc_encoding.py +++ b/pypef/dca/plmc_encoding.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution """ Contains Python code used for the approach presented in our 'hybrid modeling' paper @@ -31,11 +27,11 @@ References: [1] Hopf, T. A., Ingraham, J. B., Poelwijk, F.J., Schärfe, C.P.I., Springer, M., Sander, C., & Marks, D. S. Mutation effects predicted from sequence co-variation. - Nature Biotechnology, 35, 2017, 128–135 + Nature Biotechnology, 35, 2017, 128-135 https://doi.org/10.1038/nbt.3769 [2] Hopf T. A., Green A. G., Schubert B., et al. The EVcouplings Python framework for coevolutionary sequence analysis. - Bioinformatics 35, 2019, 1582–1584 + Bioinformatics 35, 2019, 1582-1584 https://doi.org/10.1093/bioinformatics/bty862 [3] Ekeberg, M., Lövkvist, C., Lan, Y., Weigt, M., & Aurell, E. Improved contact prediction in proteins: Using pseudolikelihoods to infer Potts models. diff --git a/pypef/main.py b/pypef/main.py index e7d0268..112e795 100644 --- a/pypef/main.py +++ b/pypef/main.py @@ -2,20 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution - # docstring for argument parsing using docopts """ diff --git a/pypef/ml/ml_run.py b/pypef/ml/ml_run.py index 1b1629c..d0e50d5 100644 --- a/pypef/ml/ml_run.py +++ b/pypef/ml/ml_run.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution import os from os import listdir diff --git a/pypef/ml/parallelization.py b/pypef/ml/parallelization.py index 1d6e467..41e001a 100644 --- a/pypef/ml/parallelization.py +++ b/pypef/ml/parallelization.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution """ Validation modules from regression.py for AAindex-based encoding diff --git a/pypef/ml/regression.py b/pypef/ml/regression.py index cd08703..81b9c4a 100644 --- a/pypef/ml/regression.py +++ b/pypef/ml/regression.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution """ Main modules for regression/ML including feature generation diff --git a/pypef/utils/directed_evolution.py b/pypef/utils/directed_evolution.py index 58a958b..4a8420b 100644 --- a/pypef/utils/directed_evolution.py +++ b/pypef/utils/directed_evolution.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution """ Modules for performing random evolution walks diff --git a/pypef/utils/learning_test_sets.py b/pypef/utils/learning_test_sets.py index 017bdb8..528375e 100644 --- a/pypef/utils/learning_test_sets.py +++ b/pypef/utils/learning_test_sets.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution """ Modules for creating training and test sets diff --git a/pypef/utils/low_n_mutation_extrapolation.py b/pypef/utils/low_n_mutation_extrapolation.py index 8fcb838..a286cbe 100644 --- a/pypef/utils/low_n_mutation_extrapolation.py +++ b/pypef/utils/low_n_mutation_extrapolation.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution import os import random diff --git a/pypef/utils/performance.py b/pypef/utils/performance.py index 22da68c..be889fb 100644 --- a/pypef/utils/performance.py +++ b/pypef/utils/performance.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution import warnings import numpy as np diff --git a/pypef/utils/plot.py b/pypef/utils/plot.py index 37b26e9..aaf50ad 100644 --- a/pypef/utils/plot.py +++ b/pypef/utils/plot.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution import os import numpy as np diff --git a/pypef/utils/prediction_sets.py b/pypef/utils/prediction_sets.py index c3f8aa7..439a36b 100644 --- a/pypef/utils/prediction_sets.py +++ b/pypef/utils/prediction_sets.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution """ Modules for making prediction files diff --git a/pypef/utils/sto2a2m.py b/pypef/utils/sto2a2m.py index f13b5b2..bb02616 100644 --- a/pypef/utils/sto2a2m.py +++ b/pypef/utils/sto2a2m.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution import logging logger = logging.getLogger('pypef.utils.sto2a2m') diff --git a/pypef/utils/to_file.py b/pypef/utils/to_file.py index 9cdb638..10f8043 100644 --- a/pypef/utils/to_file.py +++ b/pypef/utils/to_file.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution import os import numpy as np diff --git a/pypef/utils/utils_run.py b/pypef/utils/utils_run.py index 5e661e9..b5e3697 100644 --- a/pypef/utils/utils_run.py +++ b/pypef/utils/utils_run.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution import os diff --git a/pypef/utils/variant_data.py b/pypef/utils/variant_data.py index 12b7771..8415d1a 100644 --- a/pypef/utils/variant_data.py +++ b/pypef/utils/variant_data.py @@ -2,19 +2,15 @@ # -*- coding: utf-8 -*- # Created on 05 October 2020 # @authors: Niklas Siedhoff, Alexander-Maurice Illig -# @contact: +# @contact: # PyPEF - Pythonic Protein Engineering Framework -# Released under Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0) +# https://github.com/niklases/PyPEF +# Licensed under Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) # For more information about the license see https://creativecommons.org/licenses/by-nc/4.0/legalcode # PyPEF – An Integrated Framework for Data-Driven Protein Engineering # Journal of Chemical Information and Modeling, 2021, 61, 3463-3476 # https://doi.org/10.1021/acs.jcim.1c00099 -# Niklas E. Siedhoff1,§, Alexander-Maurice Illig1,§, Ulrich Schwaneberg1,2, Mehdi D. Davari1,* -# 1Institute of Biotechnology, RWTH Aachen University, Worringer Weg 3, 52074 Aachen, Germany -# 2DWI-Leibniz Institute for Interactive Materials, Forckenbeckstraße 50, 52074 Aachen, Germany -# *Corresponding author -# §Equal contribution from __future__ import annotations import os @@ -166,7 +162,7 @@ def get_sequences_from_file( def get_seqs_from_var_name( wt_seq: str, substitutions: list, - fitness_values: list, + fitness_values: None | list = None, shift_pos: int = 0 ) -> tuple[list, list, list]: """ @@ -177,14 +173,16 @@ def get_seqs_from_var_name( wt_seq: str Wild-type sequence as string substitutions: list - List of amino acid substittuions of a single variant of the format: + List of amino acid substitutions of a single variant of the format: - Single substitution variant, e.g. variant A123C: ['A123C'] - Higher variants, e.g. variant A123C/D234E/F345G: ['A123C', 'D234E, 'F345G'] --> Full substitutions list, e.g.: [['A123C'], ['A123C', 'D234E, 'F345G']] fitness_values: list List of ints/floats of the variant fitness values, e.g. for two variants: [1.4, 0.8] """ - variant, values, sequences = [], [], [] + if fitness_values is None: + fitness_values = np.zeros(len(substitutions)).tolist() + variants, values, sequences = [], [], [] for i, var in enumerate(substitutions): # var are lists of (single or multiple) substitutions temp = list(wt_seq) name = '' @@ -197,8 +195,8 @@ def get_seqs_from_var_name( new_amino_acid = str(single_var)[-1] if str(single_var)[0].isalpha(): # Assertion only possible for format AaPosAa, e.g. A123C assert str(single_var)[0] == temp[position_index], f"Input variant: "\ - f"{str(single_var)[0]}{position_index}{new_amino_acid}, WT amino "\ - f"acid variant {temp[position_index]}{position_index}{new_amino_acid}" + f"{str(single_var)[0]}{position_index + 1}{new_amino_acid}, WT amino "\ + f"acid variant {temp[position_index]}{position_index + 1}{new_amino_acid}" temp[position_index] = new_amino_acid # checking if multiple entries are inside list if separation == 0: @@ -206,11 +204,11 @@ def get_seqs_from_var_name( else: name += '/' + single_var separation += 1 - variant.append(name) + variants.append(name) values.append(fitness_values[i]) sequences.append(''.join(temp)) - return variant, values, sequences + return variants, values, sequences def remove_nan_encoded_positions( diff --git a/scripts/CLI/run_cli_tests_linux.sh b/scripts/CLI/run_cli_tests_linux.sh index 81bf3f3..ad0df5b 100644 --- a/scripts/CLI/run_cli_tests_linux.sh +++ b/scripts/CLI/run_cli_tests_linux.sh @@ -19,7 +19,7 @@ export PS4='+(Line ${LINENO}): ' # echo script line numbers ### if using downloaded/locally stored pypef .py files: ########################################################################################################################## conda env remove -n pypef # -conda create -n pypef python=3.11 -y # +conda create -n pypef python=3.12 -y # eval "$(conda shell.bash hook)" # conda activate pypef # cd '../' # @@ -307,6 +307,10 @@ echo $pypef hybrid extrapolation -i 37_ANEH_variants_dca_encoded.csv --conc echo +rm 37_ANEH_variants_plmc_dca_encoded.csv +echo +rm 37_ANEH_variants_gremlin_dca_encoded.csv +echo ### Hybrid model (and some pure ML and pure DCA) tests on avGFP dataset cd '../AVGFP' @@ -368,7 +372,7 @@ echo $pypef hybrid -m PLMC -t TS.fasl --params PLMC --threads $threads echo -# ## No training set given: Statistical prediction, Hybrid: pure statistical +# No training set given: Statistical prediction, Hybrid: pure statistical $pypef hybrid -t TS.fasl --params PLMC --threads $threads echo $pypef hybrid -p TS.fasl --params PLMC --threads $threads @@ -428,6 +432,7 @@ echo $pypef hybrid -m HYBRIDgremlin -t TS.fasl --params GREMLIN echo + $pypef encode -i avGFP.csv -e dca -w P42212_F64L.fasta --params uref100_avgfp_jhmmer_119_plmc_42.6.params --threads $threads echo $pypef encode -i avGFP.csv -e onehot -w P42212_F64L.fasta @@ -454,7 +459,11 @@ echo $pypef hybrid -m HYBRIDplmc -p avGFP_prediction_set.fasta --params uref100_avgfp_jhmmer_119_plmc_42.6.params --threads $threads echo $pypef mkps -i avGFP.csv -w P42212_F64L.fasta --drecomb -#$pypef hybrid -m HYBRID --params uref100_avgfp_jhmmer_119_plmc_42.6.params --pmult --drecomb --threads $threads # many single variants for recombination, takes too long +echo +# many single variants for recombination, takes too long +#$pypef hybrid -m HYBRIDplmc --params uref100_avgfp_jhmmer_119_plmc_42.6.params --pmult --drecomb --threads $threads +#echo +$pypef hybrid -m HYBRIDgremlin --params GREMLIN --pmult --drecomb echo $pypef hybrid directevo -m HYBRIDplmc -w P42212_F64L.fasta --params uref100_avgfp_jhmmer_119_plmc_42.6.params diff --git a/scripts/CLI/run_cli_tests_win.ps1 b/scripts/CLI/run_cli_tests_win.ps1 index 4d3756a..759bb4f 100644 --- a/scripts/CLI/run_cli_tests_win.ps1 +++ b/scripts/CLI/run_cli_tests_win.ps1 @@ -26,7 +26,7 @@ function ExitOnExitCode { if ($LastExitCode) { ### if using downloaded/locally stored pypef .py files: ########################################################################################################################## conda env remove -n pypef # -conda create -n pypef python=3.11 -y # +conda create -n pypef python=3.12 -y # conda activate pypef # $path=Get-Location # $path=Split-Path -Path $path -Parent # @@ -432,6 +432,13 @@ pypef hybrid extrapolation -i 37_ANEH_variants_dca_encoded.csv --conc ExitOnExitCode Write-Host +Remove-Item 37_ANEH_variants_plmc_dca_encoded.csv +ExitOnExitCode +Write-Host +Remove-Item 37_ANEH_variants_gremlin_dca_encoded.csv +ExitOnExitCode +Write-Host + ### Hybrid model (and some pure ML and pure DCA) tests on avGFP dataset Set-Location -Path '../AVGFP' @@ -635,7 +642,13 @@ pypef hybrid -m HYBRIDplmc -p avGFP_prediction_set.fasta --params uref100_avgfp_ ExitOnExitCode Write-Host pypef mkps -i avGFP.csv -w P42212_F64L.fasta --drecomb -#pypef hybrid -m HYBRID --params uref100_avgfp_jhmmer_119_plmc_42.6.params --pmult --drecomb --threads $threads # many single variants for recombination, takes too long +ExitOnExitCode +Write-Host +# many single variants for recombination, takes too long +#pypef hybrid -m HYBRIDplmc --params uref100_avgfp_jhmmer_119_plmc_42.6.params --pmult --drecomb --threads $threads +#ExitOnExitCode +#Write-Host +pypef hybrid -m HYBRIDgremlin --params GREMLIN --pmult --drecomb ExitOnExitCode Write-Host diff --git a/scripts/ProteinGym_runs/README.md b/scripts/ProteinGym_runs/README.md index 7e83566..933b7ed 100644 --- a/scripts/ProteinGym_runs/README.md +++ b/scripts/ProteinGym_runs/README.md @@ -1,4 +1,10 @@ ## Benchmark runs on publicly available ProteinGym protein variant sequence-fitness datasets Data is taken (script-based download) from "DMS Assays"-->"Substitutions" and "Multiple Sequence Alignments"-->"DMS Assays" data from https://proteingym.org/download. -First, run `download_proteingym_and_extract_data.py` to download and extract the ProteinGym data and subsequently run `run_performance_tests_proteingym_data.py` to get the predictions/the performance on those datasets. +Run the following to download and extract the ProteinGym data and subsequently to get the predictions/the performance on those datasets. +``` +#python -m pip install -r ../../requirements.txt +python -m pip install seaborn +python download_proteingym_and_extract_data.py +python run_performance_tests_proteingym_data.py +``` diff --git a/scripts/ProteinGym_runs/run_performance_tests_proteingym_data.py b/scripts/ProteinGym_runs/run_performance_tests_proteingym_data.py index 3a1d033..09fe4b9 100644 --- a/scripts/ProteinGym_runs/run_performance_tests_proteingym_data.py +++ b/scripts/ProteinGym_runs/run_performance_tests_proteingym_data.py @@ -7,13 +7,14 @@ import tensorflow as tf from scipy.stats import spearmanr import matplotlib.pyplot as plt +import seaborn as sns from sklearn.model_selection import train_test_split from adjustText import adjust_text # Add local PyPEF path if not using pip-installed PyPEF version sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) from pypef.dca.gremlin_inference import GREMLIN -from pypef.dca.hybrid_model import DCAHybridModel, get_delta_e_statistical_model, remove_gap_pos +from pypef.dca.hybrid_model import DCAHybridModel, get_delta_e_statistical_model # , remove_gap_pos from pypef.utils.variant_data import get_seqs_from_var_name if not tf.config.list_physical_devices('GPU'): @@ -34,147 +35,193 @@ def plot_performance(mut_data, plot_name, mut_sep=':'): tested_dsets = [] dset_dca_perfs = [] dset_hybrid_perfs = [] + dset_ns_y_test = [] n_tested_datasets = 0 plt.figure(figsize=(40, 12)) train_test_size_texts = [] for i, (dset_key, dset_paths) in enumerate(mut_data.items()): - print(f'\n{i+1}/{len(mut_data.items())}\n' - f'===============================================================') - csv_path = dset_paths['CSV_path'] - msa_path = dset_paths['MSA_path'] - wt_seq = dset_paths['WT_sequence'] - msa_start = dset_paths['MSA_start'] - msa_end = dset_paths['MSA_end'] - wt_seq = wt_seq[msa_start - 1:msa_end] - print('CSV path:', csv_path) - print('MSA path:', msa_path) - print('MSA start:', msa_start, '- MSA end:', msa_end) - print('WT sequence (trimmed from MSA start to MSA end):\n' + wt_seq) - # Getting % usage of virtual_memory (3rd field) - #import psutil;print(f'RAM used: {round(psutil.virtual_memory()[3]/1E9, 3)} ' - # f'GB ({psutil.virtual_memory()[2]} %)') - variant_fitness_data = pd.read_csv(csv_path, sep=',') - print('N_variant-fitness-tuples:', np.shape(variant_fitness_data)[0]) - #if np.shape(variant_fitness_data)[0] > 400000: - # print('More than 400000 variant-fitness pairs which represents a ' - # 'potential out-of-memory risk, skipping dataset...') - # continue - variants = variant_fitness_data['mutant'] - fitnesses = variant_fitness_data['DMS_score'] - variants_split = [] - for variant in variants: - # Split double and higher substituted variants to multiple single substitutions; - # e.g. separated by ':' or '/' - variants_split.append(variant.split(mut_sep)) - variants, fitnesses, sequences = get_seqs_from_var_name( - wt_seq, variants_split, fitnesses, shift_pos=msa_start - 1) - # Only model sequences with length of max. 800 amino acids to avoid out of memory errors - print('Sequence length:', len(wt_seq)) - if len(wt_seq) > MAX_WT_SEQUENCE_LENGTH: - print(f'Sequence length over {MAX_WT_SEQUENCE_LENGTH}, which represents a potential out-of-memory risk ' - f'(when running on GPU, set threshold to length ~400 dependent on available VRAM), ' - f'skipping dataset...') - continue - gremlin = GREMLIN(alignment=msa_path, wt_seq=wt_seq, opt_iter=100, max_msa_seqs=10000) - gaps_1_indexed = gremlin.gaps_1_indexed - count_gap_variants = 0 - n_muts = [] - for variant in variants_split: - n_muts.append(len(variant)) - for substitution in variant: - if int(substitution[1:-1]) in gaps_1_indexed: - count_gap_variants += 1 - break - max_muts = max(n_muts) - print(f'N max. (multiple) amino acid substitutions: {max_muts}') - ratio_input_vars_at_gaps = count_gap_variants / len(variants) - if count_gap_variants > 0: - print(f'{int(count_gap_variants)} of {len(variants)} ({ratio_input_vars_at_gaps * 100:.2f} %) input ' - f'variants to be predicted are variants with amino acid substitutions at gap ' - f'positions (these variants will be predicted/labeled with a fitness of 0.0).\n' - f'Gap positions (1-indexed): {gaps_1_indexed}') - if ratio_input_vars_at_gaps >= 1.0: - print(f'Gap positions (1-indexed): {gaps_1_indexed}\n' - f'100% substitutions at gap positions, skipping dataset...') - continue - # gaps = gremlin.gaps - #variants, sequences, fitnesses = remove_gap_pos(gaps, variants, sequences, fitnesses) - x_dca = gremlin.collect_encoded_sequences(sequences) - x_wt = gremlin.x_wt - # Statistical model performance - y_pred = get_delta_e_statistical_model(x_dca, x_wt) - print(f'Statistical DCA model performance on all {len(fitnesses)} datapoints; Spearman\'s rho: ' - f'{abs(spearmanr(fitnesses, y_pred)[0]):.3f}') - train_test_size_texts.append(plt.text( - n_tested_datasets, - abs(spearmanr(fitnesses, y_pred)[0]), - f'0' + r'$\rightarrow$' + f'{len(fitnesses)}', - color='tab:blue', size=4, ha='right' - )) - assert len(x_dca) == len(fitnesses) == len(variants) == len(sequences) == len(y_pred) - hybrid_perfs = [] - for i_t, train_size in enumerate([25, 50, 75, 100, 200]): - try: - x_train, x_test, y_train, y_test = train_test_split( - x_dca, fitnesses, train_size=train_size, random_state=42) - hybrid_model = DCAHybridModel(x_train=x_train, y_train=y_train, x_wt=x_wt) - beta_1, beta_2, regressor = hybrid_model.settings(x_train=x_train, y_train=y_train) - y_test_pred = hybrid_model.hybrid_prediction( - x=x_test, reg=regressor, beta_1=beta_1, beta_2=beta_2) - print(f'Hybrid DCA model performance on {len(y_test)} datapoints (Train size: {train_size}: ' - f'N Train: {len(y_train)}, N Test: {len(y_test)}). Spearman\'s rho: ' - f'{abs(spearmanr(y_test, y_test_pred)[0]):.3f}') - hybrid_perfs.append(abs(spearmanr(y_test, y_test_pred)[0])) - train_test_size_texts.append( - plt.text(n_tested_datasets, - abs(spearmanr(y_test, y_test_pred)[0]), - f'{len(y_train)}' + r'$\rightarrow$' + f'{len(y_test)}', - color=['tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown'][i_t], - size=4, ha='right' + print(f'\n{i+1}/{len(mut_data.items())}\n' + f'===============================================================') + csv_path = dset_paths['CSV_path'] + msa_path = dset_paths['MSA_path'] + wt_seq = dset_paths['WT_sequence'] + msa_start = dset_paths['MSA_start'] + msa_end = dset_paths['MSA_end'] + wt_seq = wt_seq[msa_start - 1:msa_end] + #if len(wt_seq) > 200: # For quicker/test runs + # continue + print('CSV path:', csv_path) + print('MSA path:', msa_path) + print('MSA start:', msa_start, '- MSA end:', msa_end) + print('WT sequence (trimmed from MSA start to MSA end):\n' + wt_seq) + # Getting % usage of virtual_memory (3rd field) + #import psutil;print(f'RAM used: {round(psutil.virtual_memory()[3]/1E9, 3)} ' + # f'GB ({psutil.virtual_memory()[2]} %)') + variant_fitness_data = pd.read_csv(csv_path, sep=',') + print('N_variant-fitness-tuples:', np.shape(variant_fitness_data)[0]) + #if np.shape(variant_fitness_data)[0] > 400000: + # print('More than 400000 variant-fitness pairs which represents a ' + # 'potential out-of-memory risk, skipping dataset...') + # continue + variants = variant_fitness_data['mutant'] + fitnesses = variant_fitness_data['DMS_score'] + if len(fitnesses) <= 50: + print('Number of available variants <= 50, skipping dataset...') + continue + variants_split = [] + for variant in variants: + # Split double and higher substituted variants to multiple single substitutions; + # e.g. separated by ':' or '/' + variants_split.append(variant.split(mut_sep)) + variants, fitnesses, sequences = get_seqs_from_var_name( + wt_seq, variants_split, fitnesses, shift_pos=msa_start - 1) + # Only model sequences with length of max. 800 amino acids to avoid out of memory errors + print('Sequence length:', len(wt_seq)) + if len(wt_seq) > MAX_WT_SEQUENCE_LENGTH: + print(f'Sequence length over {MAX_WT_SEQUENCE_LENGTH}, which represents a potential out-of-memory risk ' + f'(when running on GPU, set threshold to length ~400 dependent on available VRAM), ' + f'skipping dataset...') + continue + gremlin = GREMLIN(alignment=msa_path, wt_seq=wt_seq, opt_iter=100, max_msa_seqs=10000) + gaps_1_indexed = gremlin.gaps_1_indexed + count_gap_variants = 0 + n_muts = [] + for variant in variants_split: + n_muts.append(len(variant)) + for substitution in variant: + if int(substitution[1:-1]) in gaps_1_indexed: + count_gap_variants += 1 + break + max_muts = max(n_muts) + print(f'N max. (multiple) amino acid substitutions: {max_muts}') + ratio_input_vars_at_gaps = count_gap_variants / len(variants) + if count_gap_variants > 0: + print(f'{int(count_gap_variants)} of {len(variants)} ({ratio_input_vars_at_gaps * 100:.2f} %) input ' + f'variants to be predicted are variants with amino acid substitutions at gap ' + f'positions (these variants will be predicted/labeled with a fitness of 0.0).\n' + f'Gap positions (1-indexed): {gaps_1_indexed}') + if ratio_input_vars_at_gaps >= 1.0: + print(f'Gap positions (1-indexed): {gaps_1_indexed}\n' + f'100% substitutions at gap positions, skipping dataset...') + continue + # gaps = gremlin.gaps + #variants, sequences, fitnesses = remove_gap_pos(gaps, variants, sequences, fitnesses) + x_dca = gremlin.collect_encoded_sequences(sequences) + x_wt = gremlin.x_wt + # Statistical model performance + y_pred = get_delta_e_statistical_model(x_dca, x_wt) + print(f'Statistical DCA model performance on all {len(fitnesses)} datapoints; Spearman\'s rho: ' + f'{abs(spearmanr(fitnesses, y_pred)[0]):.3f}') + train_test_size_texts.append(plt.text( + n_tested_datasets, + abs(spearmanr(fitnesses, y_pred)[0]), + f'0' + r'$\rightarrow$' + f'{len(fitnesses)}', + color='tab:blue', size=4, ha='right' + )) + assert len(x_dca) == len(fitnesses) == len(variants) == len(sequences) == len(y_pred) + hybrid_perfs = [] + ns_y_test = [len(fitnesses)] + for i_t, train_size in enumerate([100, 200, 1000]): + try: + x_train, x_test, y_train, y_test = train_test_split( + x_dca, fitnesses, train_size=train_size, random_state=42) + if len(y_test) <= 50: + print(f'Only {len(fitnesses)} in total, splitting the data in N_Train = {len(y_train)} ' + f'and N_Test = {len(y_test)} results in N_Test <= 50 variants - ' + f'not getting performance for N_Train = {len(y_train)}...') + hybrid_perfs.append(np.nan) + ns_y_test.append(np.nan) + continue + ns_y_test.append(len(y_test)) + hybrid_model = DCAHybridModel(x_train=x_train, y_train=y_train, x_wt=x_wt) + beta_1, beta_2, regressor = hybrid_model.settings(x_train=x_train, y_train=y_train) + y_test_pred = hybrid_model.hybrid_prediction( + x=x_test, reg=regressor, beta_1=beta_1, beta_2=beta_2 ) - ) - except ValueError: - hybrid_perfs.append(np.nan) - n_tested_datasets += 1 - tested_dsets.append(f'({n_tested_datasets}) {dset_key} ' - f'({len(variants)}, {100.0 - (ratio_input_vars_at_gaps * 100):.2f}%, {max_muts})') - dset_dca_perfs.append(abs(spearmanr(fitnesses, y_pred)[0])) - dset_hybrid_perfs.append(hybrid_perfs) - #import gc;gc.collect() # Potentially GC is needed to free some RAM (deallocated VRAM -> partly stored in RAM?) after each run - plt.plot(range(len(tested_dsets)), dset_dca_perfs, 'o--', markersize=8, color='tab:blue', label='DCA') + print(f'Hybrid DCA model performance (N Train: {len(y_train)}, N Test: {len(y_test)}). ' + f'Spearman\'s rho: {abs(spearmanr(y_test, y_test_pred)[0]):.3f}') + hybrid_perfs.append(abs(spearmanr(y_test, y_test_pred)[0])) + train_test_size_texts.append( + plt.text(n_tested_datasets, + abs(spearmanr(y_test, y_test_pred)[0]), + f'{len(y_train)}' + r'$\rightarrow$' + f'{len(y_test)}', + color=['tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown'][i_t], + size=4, ha='right' + ) + ) + except ValueError: + print(f'Only {len(fitnesses)} variant-fitness pairs in total, cannot split the data in N_Train = {train_size} and N_Test (N_Total - N_Train).') + hybrid_perfs.append(np.nan) + ns_y_test.append(np.nan) + n_tested_datasets += 1 + tested_dsets.append(f'({n_tested_datasets}) {dset_key} ' + f'({len(variants)}, {100.0 - (ratio_input_vars_at_gaps * 100):.2f}%, {max_muts})') + dset_dca_perfs.append(abs(spearmanr(fitnesses, y_pred)[0])) + dset_hybrid_perfs.append(hybrid_perfs) + dset_ns_y_test.append(ns_y_test) + #import gc;gc.collect() # Potentially GC is needed to free some RAM (deallocated VRAM -> partly stored in RAM?) after each run + plt.plot(range(len(tested_dsets)), dset_dca_perfs, 'o--', markersize=8, color='tab:blue', label='DCA (0)') plt.plot(range(len(tested_dsets) + 1), np.full(len(tested_dsets) + 1, np.nanmean(dset_dca_perfs)), color='tab:blue', linestyle='--') train_test_size_texts.append(plt.text(len(tested_dsets), np.nanmean(dset_dca_perfs), f'{np.nanmean(dset_dca_perfs):.2f}', color='tab:blue')) - plt.plot(range(len(tested_dsets)), np.array(dset_hybrid_perfs)[:, 0], 'o--', markersize=8, color='tab:orange', label='Hybrid (25)') + plt.plot(range(len(tested_dsets)), np.array(dset_hybrid_perfs)[:, 0], 'o--', markersize=8, color='tab:orange', label='Hybrid (100)') plt.plot(range(len(tested_dsets) + 1), np.full(len(tested_dsets) + 1, np.nanmean(np.array(dset_hybrid_perfs)[:, 0])), color='tab:orange', linestyle='--') train_test_size_texts.append(plt.text(len(tested_dsets), np.nanmean(np.array(dset_hybrid_perfs)[:, 0]), f'{np.nanmean(np.array(dset_hybrid_perfs)[:, 0]):.2f}', color='tab:orange')) - plt.plot(range(len(tested_dsets)), np.array(dset_hybrid_perfs)[:, 1], 'o--', markersize=8, color='tab:green', label='Hybrid (50)') + plt.plot(range(len(tested_dsets)), np.array(dset_hybrid_perfs)[:, 1], 'o--', markersize=8, color='tab:green', label='Hybrid (200)') plt.plot(range(len(tested_dsets) + 1), np.full(len(tested_dsets) + 1, np.nanmean(np.array(dset_hybrid_perfs)[:, 1])), color='tab:green', linestyle='--') train_test_size_texts.append(plt.text(len(tested_dsets), np.nanmean(np.array(dset_hybrid_perfs)[:, 1]), f'{np.nanmean(np.array(dset_hybrid_perfs)[:, 1]):.2f}', color='tab:green')) - plt.plot(range(len(tested_dsets)), np.array(dset_hybrid_perfs)[:, 2], 'o--', markersize=8, color='tab:red', label='Hybrid (75)') + plt.plot(range(len(tested_dsets)), np.array(dset_hybrid_perfs)[:, 2], 'o--', markersize=8, color='tab:red', label='Hybrid (1000)') plt.plot(range(len(tested_dsets) + 1), np.full(len(tested_dsets) + 1, np.nanmean(np.array(dset_hybrid_perfs)[:, 2])), color='tab:red', linestyle='--') train_test_size_texts.append(plt.text(len(tested_dsets), np.nanmean(np.array(dset_hybrid_perfs)[:, 2]), f'{np.nanmean(np.array(dset_hybrid_perfs)[:, 2]):.2f}', color='tab:red')) - plt.plot(range(len(tested_dsets)), np.array(dset_hybrid_perfs)[:, 3], 'o--', markersize=8, color='tab:purple', label='Hybrid (100)') - plt.plot(range(len(tested_dsets) + 1), np.full(len(tested_dsets) + 1, np.nanmean(np.array(dset_hybrid_perfs)[:, 3])), color='tab:purple', linestyle='--') - train_test_size_texts.append(plt.text(len(tested_dsets), np.nanmean(np.array(dset_hybrid_perfs)[:, 3]), f'{np.nanmean(np.array(dset_hybrid_perfs)[:, 3]):.2f}', color='tab:purple')) - - plt.plot(range(len(tested_dsets)), np.array(dset_hybrid_perfs)[:, 4], 'o--', markersize=8, color='tab:brown', label='Hybrid (200)') - plt.plot(range(len(tested_dsets) + 1), np.full(len(tested_dsets) + 1, np.nanmean(np.array(dset_hybrid_perfs)[:, 4])), color='tab:brown', linestyle='--') - train_test_size_texts.append(plt.text(len(tested_dsets), np.nanmean(np.array(dset_hybrid_perfs)[:, 4]), f'{np.nanmean(np.array(dset_hybrid_perfs)[:, 4]):.2f}', color='tab:brown')) - plt.xticks(range(len(tested_dsets)), tested_dsets, rotation=45, ha='right') plt.margins(0.01) plt.legend() plt.tight_layout() plt.ylim(0.0, 1.0) - plt.ylabel(r'|Spearmanr $\rho$|') + plt.ylabel(r'|Spearman $\rho$|') adjust_text(train_test_size_texts, expand=(1.2, 2)) plt.savefig(os.path.join(os.path.dirname(__file__), f'{plot_name}.png'), dpi=300) print('Saved file as ' + os.path.join(os.path.dirname(__file__), f'{plot_name}.png') + '.') + df = pd.DataFrame({ + 'DCA': dset_dca_perfs, + 'Hybrid 100': np.array(dset_hybrid_perfs)[:, 0], + 'Hybrid 200': np.array(dset_hybrid_perfs)[:, 1], + 'Hybrid 1000': np.array(dset_hybrid_perfs)[:, 2], + }) + plt.clf() + plt.figure(figsize=(16, 12)) + sns.set_style("whitegrid") + sns.violinplot(df, saturation=0.4) + plt.ylim(-0.09, 1.0) + plt.ylabel(r'|Spearmanr $\rho$|') + sns.swarmplot(df, color='black') + for n in range(0, 4): + plt.text( + n, -0.075, + [ + r'$\overline{|\rho|}=$' + f'{np.nanmean(dset_dca_perfs):.2f}', + r'$\overline{|\rho|}=$' + f'{np.nanmean(np.array(dset_hybrid_perfs)[:, 0]):.2f}', + r'$\overline{|\rho|}=$' + f'{np.nanmean(np.array(dset_hybrid_perfs)[:, 1]):.2f}', + r'$\overline{|\rho|}=$' + f'{np.nanmean(np.array(dset_hybrid_perfs)[:, 2]):.2f}' + ][n] + ) + plt.text( + n, -0.05, + r'$\overline{N_{Y_\mathrm{test}}}=$' + f'{int(np.nanmean(np.array(dset_ns_y_test)[:, n]))}' + ) + plt.text( + n, -0.025, + r'$N_\mathrm{Datasets}=$' + f'{np.count_nonzero(~np.isnan(np.array(dset_ns_y_test)[:, n]))}' + ) + print(f'\n{np.shape(dset_ns_y_test)[0]} datasets tested with N_Test\'s at N_Train\'s =\n' + f' 0 100 200 1000\n{np.nan_to_num(dset_ns_y_test).astype("int")}') + print() + plt.savefig(os.path.join(os.path.dirname(__file__), f'{plot_name}_violin.png'), dpi=300) + print('Saved file as ' + os.path.join(os.path.dirname(__file__), f'{plot_name}_violin.png') + '.') with open(single_point_mut_data, 'r') as fh: s_mut_data = json.loads(fh.read()) diff --git a/setup.py b/setup.py index b8fb390..04168ad 100644 --- a/setup.py +++ b/setup.py @@ -37,7 +37,7 @@ package_data={'pypef': ['ml/AAindex/*', 'ml/AAindex/Refined_cluster_indices_r0.93_r0.97/*']}, include_package_data=True, install_requires=[requirements], - python_requires='>= 3.9, < 3.12', + python_requires='>= 3.9, < 3.13', keywords='Pythonic Protein Engineering Framework', classifiers=[ 'Development Status :: 3 - Alpha', @@ -45,6 +45,7 @@ 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3.12', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Topic :: Scientific/Engineering :: Artificial Intelligence' ],