From 4159c3fecfb98643049bf622c87820cfd63b6e8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Diaz?= Date: Fri, 15 May 2026 14:28:00 +0200 Subject: [PATCH 1/5] First changes --- .github/workflows/docker-publish.yml | 105 ++++ LICENSE | 875 ++++++--------------------- README.md | 42 ++ docker/Dockerfile | 4 +- requirements-biophysics.txt | 2 +- requirements-shiny.txt | 3 - 6 files changed, 351 insertions(+), 680 deletions(-) create mode 100644 .github/workflows/docker-publish.yml diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml new file mode 100644 index 0000000..c074c55 --- /dev/null +++ b/.github/workflows/docker-publish.yml @@ -0,0 +1,105 @@ +name: Docker Publish + +on: + push: + tags: + - "v*" + pull_request: + workflow_dispatch: + +env: + IMAGE_NAME: scop3p-toolkit + DOCKERFILE_PATH: docker/Dockerfile + DOCKER_TARGET: scop3p-toolkit + PYTHON_VERSION: "3.12" + +jobs: + test: + name: Pytest smoke checks + runs-on: ubuntu-latest + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ env.PYTHON_VERSION }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -r requirements-biophysics.txt + python -m pip install -r requirements-shiny.txt + python -m pip install pytest + + - name: Run smoke tests + run: pytest tests/integration/test_app_smoke.py + + docker: + name: Build and publish Docker image + runs-on: ubuntu-latest + needs: test + permissions: + contents: read + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Prepare image variables + id: vars + shell: bash + run: | + namespace="${{ vars.DOCKERHUB_NAMESPACE || secrets.DOCKERHUB_USERNAME }}" + version="${GITHUB_SHA}" + if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then + version="${GITHUB_REF_NAME}" + fi + { + echo "image_repository=${namespace}/${IMAGE_NAME}" + echo "build_date=$(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "version=${version}" + } >> "${GITHUB_OUTPUT}" + + - name: Log in to Docker Hub + if: github.event_name != 'pull_request' && github.ref_type == 'tag' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: docker.io/${{ steps.vars.outputs.image_repository }} + tags: | + type=raw,value=latest,enable=${{ github.ref_type == 'tag' }} + type=sha,format=short,prefix=sha- + type=ref,event=tag + labels: | + org.opencontainers.image.title=Scop3P-Toolkit + org.opencontainers.image.description=Scop3P toolkit container for Galaxy interactive tool deployment + org.opencontainers.image.licenses=Apache-2.0 + + - name: Build and push image + uses: docker/build-push-action@v6 + with: + context: . + file: ${{ env.DOCKERFILE_PATH }} + target: ${{ env.DOCKER_TARGET }} + platforms: linux/amd64 + push: ${{ github.event_name != 'pull_request' && github.ref_type == 'tag' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max + build-args: | + BUILD_DATE=${{ steps.vars.outputs.build_date }} + VCS_REF=${{ github.sha }} + VERSION=${{ steps.vars.outputs.version }} diff --git a/LICENSE b/LICENSE index f288702..261eeb9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,201 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index f60068f..a024e5b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,48 @@ # Scop3P-notebooks Jupyter Notebook examples of Scop3P REST API services. +## Published container + +This repository publishes the Galaxy-facing `bio2byte/scop3p-toolkit` container. The image packages the single-container portal exposed on port `8000` and is the intended entrypoint for a UseGalaxy interactive tool. + +- Docker image: `bio2byte/scop3p-toolkit` +- Dockerfile target: `scop3p-toolkit` +- App-specific documentation: [`apps/README.md`](/Users/adrian/workspace/vub/Scop3P-notebooks/apps/README.md) + +## Build and run the toolkit image + +Build the published image locally: + +```bash +DOCKER_DEFAULT_PLATFORM=linux/amd64 docker build \ + -f docker/Dockerfile \ + -t bio2byte/scop3p-toolkit:local \ + . +``` + +Run it locally: + +```bash +docker run --rm -p 8000:8000 bio2byte/scop3p-toolkit:local +``` + +Then open `http://localhost:8000` to access the toolkit selector and launch the bundled interactive apps. + +## Continuous delivery to Docker Hub + +GitHub Actions publishes the `bio2byte/scop3p-toolkit` image for default-branch pushes and version tags. Pull requests run the same build in validation mode without pushing. + +Required repository secrets: + +- `DOCKERHUB_USERNAME` +- `DOCKERHUB_TOKEN` + +Optional repository variable: + +- `DOCKERHUB_NAMESPACE` + +If `DOCKERHUB_NAMESPACE` is not set, the workflow publishes to the same namespace as `DOCKERHUB_USERNAME`. + ## About Scop3P[^1] **Scop3P: A Comprehensive Resource of Human Phosphosites within Their Full Context** diff --git a/docker/Dockerfile b/docker/Dockerfile index 244ce22..f2e2bca 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -9,7 +9,7 @@ LABEL org.opencontainers.image.title="Scop3P-Toolkit" \ org.opencontainers.image.description="Scop3P-Toolkit: Tools for exploring and extending Scop3P" \ org.opencontainers.image.url="https://github.com/Bio2Byte/Scop3P-notebooks" \ org.opencontainers.image.source="https://github.com/Bio2Byte/Scop3P-notebooks" \ - org.opencontainers.image.licenses="Apache 2.0" \ + org.opencontainers.image.licenses="Apache-2.0" \ org.opencontainers.image.version="${VERSION}" \ org.opencontainers.image.revision="${VCS_REF}" \ org.opencontainers.image.created="${BUILD_DATE}" @@ -21,7 +21,7 @@ ENV PYTHONDONTWRITEBYTECODE=1 \ WORKDIR /apps RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential gcc g++ && \ + build-essential gcc g++ 't-coffee' hmmer && \ rm -rf /var/lib/apt/lists/* && \ pip install -U pip diff --git a/requirements-biophysics.txt b/requirements-biophysics.txt index 0bf9df6..ab6a0cb 100644 --- a/requirements-biophysics.txt +++ b/requirements-biophysics.txt @@ -1 +1 @@ -b2bTools==3.0.8b3 +b2bTools==3.0.8 diff --git a/requirements-shiny.txt b/requirements-shiny.txt index 14fd029..51142ec 100644 --- a/requirements-shiny.txt +++ b/requirements-shiny.txt @@ -10,9 +10,6 @@ py3Dmol>=2.5.3 pyvis>=0.3.2,<0.4 bokeh>=3.3,<4 -# Extra bio -hmmer - # Testing pytest>=8.0,<9 httpx>=0.27,<1 From 89147faf2cfe5dd596b1c5c656ee091745e23e0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Diaz?= Date: Fri, 15 May 2026 15:39:51 +0200 Subject: [PATCH 2/5] Replace old code --- .github/workflows/docker-publish.yml | 6 +- apps/common/__init__.py | 2 + apps/common/logging_utils.py | 39 +++++ apps/common/mutation_effect.py | 27 +-- apps/common/services.py | 37 ++++- apps/common/structure_viz.py | 87 +++++++--- apps/mutation_effect/app.py | 26 +++ apps/peptide_mapper/app.py | 44 +++++ apps/structure_viz/app.py | 183 +++++++++++++++++++-- docker/Dockerfile | 52 ++++-- pytest.ini | 2 +- requirements-biophysics.txt | 3 +- tests/integration/test_app_smoke.py | 2 +- tests/unit/test_mutation_effect_service.py | 68 ++++++++ tests/unit/test_scop3p_client.py | 62 +++++-- tests/unit/test_structure_ops.py | 81 +++++++++ tests/unit/test_structure_viz_service.py | 51 ++++++ 17 files changed, 668 insertions(+), 104 deletions(-) create mode 100644 apps/common/logging_utils.py create mode 100644 tests/unit/test_structure_viz_service.py diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index c074c55..dd58145 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -15,7 +15,7 @@ env: jobs: test: - name: Pytest smoke checks + name: Pytest suite runs-on: ubuntu-latest steps: @@ -34,8 +34,8 @@ jobs: python -m pip install -r requirements-shiny.txt python -m pip install pytest - - name: Run smoke tests - run: pytest tests/integration/test_app_smoke.py + - name: Run tests + run: pytest tests/unit tests/integration docker: name: Build and publish Docker image diff --git a/apps/common/__init__.py b/apps/common/__init__.py index c77e741..1f40e9f 100644 --- a/apps/common/__init__.py +++ b/apps/common/__init__.py @@ -1,5 +1,6 @@ """Shared services for Shiny app conversions.""" +from .logging_utils import get_logger from .models import PeptideRow, PeptideSelectionMode from .services import AlphaFoldService, Scop3PClient from .peptide_mapper import ( @@ -13,6 +14,7 @@ __all__ = [ "PeptideRow", "PeptideSelectionMode", + "get_logger", "AlphaFoldService", "Scop3PClient", "PeptideMapperService", diff --git a/apps/common/logging_utils.py b/apps/common/logging_utils.py new file mode 100644 index 0000000..94bfd6c --- /dev/null +++ b/apps/common/logging_utils.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import logging +import os +import sys +from typing import Any + + +_CONFIGURED = False + + +def configure_logging() -> None: + global _CONFIGURED + if _CONFIGURED: + return + + level_name = os.getenv("SCOP3P_LOG_LEVEL", "INFO").upper() + level = getattr(logging, level_name, logging.INFO) + + logging.basicConfig( + level=level, + stream=sys.stdout, + format="%(asctime)s %(levelname)s %(name)s event=%(event)s %(message)s", + ) + _CONFIGURED = True + + +class _EventAdapter(logging.LoggerAdapter): + def process(self, msg: str, kwargs: dict[str, Any]) -> tuple[str, dict[str, Any]]: + extra = dict(kwargs.get("extra", {})) + extra.setdefault("event", "-") + kwargs["extra"] = extra + return msg, kwargs + + +def get_logger(name: str) -> logging.LoggerAdapter: + configure_logging() + return _EventAdapter(logging.getLogger(name), {}) + diff --git a/apps/common/mutation_effect.py b/apps/common/mutation_effect.py index 1ec33a2..abc3b92 100644 --- a/apps/common/mutation_effect.py +++ b/apps/common/mutation_effect.py @@ -60,34 +60,11 @@ def fetch_uniprot_sequence(self, accession: str) -> str: return sequence def fetch_scop3p_modifications(self, accession: str) -> pd.DataFrame: - response = requests.get( - f"{self.scop3p_client.base_url}/modifications", - params={"accession": accession}, - headers={"accept": "application/json"}, - timeout=self.timeout, - ) - response.raise_for_status() - payload = response.json() - if isinstance(payload, list): - payload = payload[0] if payload else {} - - dataframe = pd.DataFrame(payload.get("modifications", [])) + dataframe = self.scop3p_client.fetch_modifications(accession) if dataframe.empty: return dataframe - keep = [ - column - for column in [ - "position", - "residue", - "name", - "source", - "evidence", - "reference", - "functionalScore", - ] - if column in dataframe.columns - ] + keep = [column for column in dataframe.columns if column != "specificSinglyPhosphorylated"] dataframe = dataframe[keep].copy() dataframe["position"] = pd.to_numeric(dataframe["position"], errors="coerce") dataframe = dataframe.dropna(subset=["position"]) diff --git a/apps/common/services.py b/apps/common/services.py index 6cdbcbd..0257bfa 100644 --- a/apps/common/services.py +++ b/apps/common/services.py @@ -5,7 +5,7 @@ import urllib.request import pandas as pd -import requests +from scop3p_api_client.api import Scop3pRestApi class Scop3PClient: @@ -14,13 +14,10 @@ class Scop3PClient: def __init__(self, base_url: str = "https://iomics.ugent.be/scop3p/api", timeout: int = 30) -> None: self.base_url = base_url.rstrip("/") self.timeout = timeout + self.api = Scop3pRestApi(default_timeout=timeout) def fetch_peptides_modifications(self, accession: str) -> pd.DataFrame: - url = f"{self.base_url}/get-peptides-modifications" - response = requests.get(url, params={"accession": accession}, timeout=self.timeout) - response.raise_for_status() - payload = response.json() - + payload = self.api.fetch_peptides(accession) df = pd.DataFrame(payload.get("peptides", [])) if df.empty: return df @@ -36,6 +33,34 @@ def fetch_peptides_modifications(self, accession: str) -> pd.DataFrame: df["label"] = df.apply(self._format_label, axis=1) return df + def fetch_modifications(self, accession: str) -> pd.DataFrame: + payload = self.api.fetch_modifications(accession) + if isinstance(payload, list): + payload = payload[0] if payload else {} + + dataframe = pd.DataFrame(payload.get("modifications", [])) + if dataframe.empty: + return dataframe + + keep = [ + column + for column in [ + "position", + "residue", + "name", + "source", + "evidence", + "reference", + "functionalScore", + "specificSinglyPhosphorylated", + ] + if column in dataframe.columns + ] + dataframe = dataframe[keep].copy() + if "position" in dataframe.columns: + dataframe["position"] = pd.to_numeric(dataframe["position"], errors="coerce").astype("Int64") + return dataframe + @staticmethod def _format_label(row: pd.Series) -> str: peptide_sequence = str(row.get("peptideSequence", "")) diff --git a/apps/common/structure_viz.py b/apps/common/structure_viz.py index 649111a..6389bf9 100644 --- a/apps/common/structure_viz.py +++ b/apps/common/structure_viz.py @@ -16,37 +16,20 @@ from b2bTools import SingleSeq, constants from scipy.spatial import KDTree +from .services import Scop3PClient + class StructureVizService: def __init__(self, workdir: Path, timeout: int = 60) -> None: self.workdir = workdir self.timeout = timeout + self.scop3p_client = Scop3PClient(timeout=timeout) self.workdir.mkdir(parents=True, exist_ok=True) def fetch_ptms(self, accession: str) -> pd.DataFrame: - url = "https://iomics.ugent.be/scop3p/api/modifications" - response = requests.get(url, params={"accession": accession}, headers={"accept": "application/json"}, timeout=self.timeout) - response.raise_for_status() - payload = response.json() - if isinstance(payload, list): - payload = payload[0] if payload else {} - dataframe = pd.DataFrame(payload.get("modifications", [])) + dataframe = self.scop3p_client.fetch_modifications(accession) if dataframe.empty: return dataframe - columns = [ - "residue", - "name", - "evidence", - "position", - "source", - "reference", - "functionalScore", - "specificSinglyPhosphorylated", - ] - keep = [column for column in columns if column in dataframe.columns] - dataframe = dataframe[keep].copy() - if "position" in dataframe.columns: - dataframe["position"] = pd.to_numeric(dataframe["position"], errors="coerce").astype("Int64") return dataframe def fetch_variants(self, accession: str) -> pd.DataFrame: @@ -161,6 +144,15 @@ def accept_residue(self, residue): # noqa: ANN001 class StructureOps: + @staticmethod + def validate_pdb_id(pdb_id: str) -> str: + pdb_key = pdb_id.strip().upper() + if len(pdb_key) != 4 or not pdb_key.isalnum(): + raise ValueError( + f"Invalid PDB ID '{pdb_id}'. Expected a 4-character RCSB identifier such as 2IVT." + ) + return pdb_key + @staticmethod def bfactor_pdb(pdb_path: Path, dataframe: pd.DataFrame, value_col: str, out_path: Path, chain: str | None = None) -> Path: values = dataframe[value_col].tolist() @@ -195,20 +187,71 @@ def chain_range_from_pdb(pdb_path: Path, chain_id: str) -> tuple[int, int]: positions = [res.id[1] for res in chain.get_residues() if res.id[0] == " "] return min(positions), max(positions) + @staticmethod + def chain_ranges_from_pdb(pdb_path: Path) -> dict[str, tuple[int, int]]: + parser = PDBParser(QUIET=True) + structure = parser.get_structure("chains", str(pdb_path)) + model = next(structure.get_models()) + chain_ranges: dict[str, tuple[int, int]] = {} + for chain in model.get_chains(): + positions = [res.id[1] for res in chain.get_residues() if res.id[0] == " "] + if positions: + chain_ranges[chain.id] = (min(positions), max(positions)) + return chain_ranges + @staticmethod def save_chain_segment(source_pdb: Path, target_pdb: Path, chain_id: str, start: int | None, end: int | None) -> Path: parser = PDBParser(QUIET=True) structure = parser.get_structure("segment", str(source_pdb)) + model = next(structure.get_models()) + if chain_id not in model: + available = ", ".join(chain.id for chain in model.get_chains()) or "(none)" + raise ValueError( + f"Chain '{chain_id}' not found in {source_pdb.name}. Available chains: {available}." + ) + + chain = model[chain_id] + positions = [res.id[1] for res in chain.get_residues() if res.id[0] == " "] + if not positions: + raise ValueError(f"Chain '{chain_id}' in {source_pdb.name} does not contain standard residues.") + + chain_start = min(positions) + chain_end = max(positions) + if start is not None and end is not None and start > end: + raise ValueError(f"Invalid range for chain '{chain_id}': start {start} is greater than end {end}.") + if start is not None and start > chain_end: + raise ValueError(f"Start {start} is outside chain '{chain_id}' range {chain_start}-{chain_end}.") + if end is not None and end < chain_start: + raise ValueError(f"End {end} is outside chain '{chain_id}' range {chain_start}-{chain_end}.") + io = PDBIO() io.set_structure(structure) io.save(str(target_pdb), select=ChainRangeSelect(chain_id, start, end)) + segment_positions = [ + int(line[22:26].strip()) + for line in target_pdb.read_text(encoding="utf-8", errors="ignore").splitlines() + if line.startswith(("ATOM", "HETATM")) and line[21].strip() == chain_id and line[22:26].strip() + ] + if not segment_positions: + raise ValueError( + f"Chain/range selection produced an empty segment for chain '{chain_id}' " + f"with range {start or chain_start}-{end or chain_end} in {source_pdb.name}." + ) return target_pdb @staticmethod def run_tmalign(pdb1: Path, pdb2: Path, out_dir: Path, out_name: str = "aligned") -> tuple[Path, str]: out_dir.mkdir(parents=True, exist_ok=True) cmd = ["TM-align", str(pdb1.resolve()), str(pdb2.resolve()), "-o", out_name] - process = subprocess.run(cmd, cwd=out_dir, capture_output=True, text=True, check=True) + try: + process = subprocess.run(cmd, cwd=out_dir, capture_output=True, text=True, check=True) + except subprocess.CalledProcessError as error: + stderr = (error.stderr or "").strip() + stdout = (error.stdout or "").strip() + details = stderr or stdout or f"exit code {error.returncode}" + raise RuntimeError( + f"TM-align failed for {pdb1.name} vs {pdb2.name}: {details}" + ) from error candidates = [ out_dir / out_name, out_dir / f"{out_name}.pdb", diff --git a/apps/mutation_effect/app.py b/apps/mutation_effect/app.py index bd6f820..b170fbc 100644 --- a/apps/mutation_effect/app.py +++ b/apps/mutation_effect/app.py @@ -14,10 +14,12 @@ MutationEffectService, MutationEffectViews, ) +from common.logging_utils import get_logger # noqa: E402 from common.ui_shell import scop3p_card, scop3p_shell, scop3p_footer # noqa: E402 service = MutationEffectService() +LOGGER = get_logger("scop3p.mutation_effect") def _bokeh_iframe(html_doc: str) -> ui.Tag: @@ -117,6 +119,7 @@ def status() -> str: def _run_wt() -> None: try: accession_value = input.accession().strip() + LOGGER.info("run_wt requested accession=%s", accession_value or "-", extra={"event": "run_wt"}) status_text.set("Fetching UniProt sequence and Scop3P PTMs...") sequence_value = service.fetch_uniprot_sequence(accession_value) mods = service.fetch_scop3p_modifications(accession_value) @@ -150,12 +153,23 @@ def _run_wt() -> None: ) status_text.set(f"WT prediction ready. PTMs: {0 if mods is None else len(mods)}.") except Exception as error: + LOGGER.exception("run_wt failed accession=%s", input.accession().strip() or "-", extra={"event": "run_wt"}) status_text.set(f"WT error: {error}") + return + LOGGER.info( + "run_wt completed accession=%s seq_len=%s ptms=%s rows=%s", + accession_value, + len(sequence_value), + 0 if mods is None else len(mods), + len(dataframe), + extra={"event": "run_wt"}, + ) @reactive.effect @reactive.event(input.run_mut) def _run_mut() -> None: try: + LOGGER.info("run_mut requested positions=%s aas=%s", input.positions(), input.mut_aas(), extra={"event": "run_mut"}) if wt_df.get() is None or not sequence.get(): raise ValueError("Run WT prediction first.") @@ -189,12 +203,21 @@ def _run_mut() -> None: inf_sections.set([]) status_text.set("Mutant prediction ready.") except Exception as error: + LOGGER.exception("run_mut failed", extra={"event": "run_mut"}) status_text.set(f"Mutant error: {error}") + return + LOGGER.info( + "run_mut completed mutations=%s rows=%s", + len(parsed_mutations), + len(dataframe), + extra={"event": "run_mut"}, + ) @reactive.effect @reactive.event(input.run_inf) def _run_inf() -> None: try: + LOGGER.info("run_inf requested mutations=%s", len(mutations.get()), extra={"event": "run_inf"}) if wt_df.get() is None or mut_df.get() is None: raise ValueError("Run WT prediction and Mutant prediction first.") @@ -223,7 +246,10 @@ def _run_inf() -> None: inf_sections.set(sections) status_text.set("Inference ready.") except Exception as error: + LOGGER.exception("run_inf failed", extra={"event": "run_inf"}) status_text.set(f"Inference error: {error}") + return + LOGGER.info("run_inf completed sections=%s", len(sections), extra={"event": "run_inf"}) @output @render.ui diff --git a/apps/peptide_mapper/app.py b/apps/peptide_mapper/app.py index 9c4e5cd..93d7306 100644 --- a/apps/peptide_mapper/app.py +++ b/apps/peptide_mapper/app.py @@ -10,6 +10,7 @@ import pandas as pd from shiny import App, reactive, render, ui +from common.logging_utils import get_logger from common.models import PeptideSelectionMode from common.peptide_mapper import PeptideMapperService, map_selection from common.services import AlphaFoldService, Scop3PClient @@ -17,6 +18,9 @@ from common.viewer import NGLViewerBuilder +LOGGER = get_logger("scop3p.peptide_mapper") + + class PeptideMapperController: """Stateful coordinator for Peptide Mapper app behavior.""" @@ -180,6 +184,7 @@ def server(input, output, session): @reactive.event(input.load_btn) def _load_data() -> None: accession = input.accession().strip() + LOGGER.info("load requested accession=%s", accession or "-", extra={"event": "load_btn"}) if not accession: controller.status_text.set("Enter an accession (e.g., O00571), then click Load.") return @@ -187,6 +192,7 @@ def _load_data() -> None: try: dataframe = controller.client.fetch_peptides_modifications(accession) except Exception as error: + LOGGER.exception("load failed accession=%s", accession, extra={"event": "load_btn"}) controller.status_text.set(f"Scop3P API error: {error}") controller.dataframe.set(pd.DataFrame()) controller.filtered_dataframe.set(pd.DataFrame()) @@ -207,6 +213,13 @@ def _load_data() -> None: options = PeptideMapperService.build_options(dataframe, mode) ui.update_selectize("peptides", choices=_as_selectize_choices(options), selected=[]) controller.status_text.set(f"Loaded {len(dataframe)} peptide-mod rows for {accession}.") + LOGGER.info( + "load completed accession=%s rows=%s mode=%s", + accession, + len(dataframe), + mode.value, + extra={"event": "load_btn"}, + ) @reactive.effect def _update_filter_and_choices() -> None: @@ -225,11 +238,20 @@ def _update_filter_and_choices() -> None: restored = [value for value in selected if value in valid_values] ui.update_selectize("peptides", choices=_as_selectize_choices(options), selected=restored) + LOGGER.info( + "filter updated query=%r filtered_rows=%s options=%s restored=%s", + input.search(), + len(filtered), + len(options), + len(restored), + extra={"event": "filter_update"}, + ) @reactive.effect @reactive.event(input.map_all) def _map_all() -> None: filtered = controller.filtered_dataframe.get() + LOGGER.info("map_all requested", extra={"event": "map_all"}) if filtered is None or filtered.empty: controller.status_text.set("No filtered rows available. Load data first.") return @@ -238,6 +260,7 @@ def _map_all() -> None: options = PeptideMapperService.build_options(filtered, mode) values = [value for _, value in options] ui.update_selectize("peptides", selected=values) + LOGGER.info("map_all selected_count=%s", len(values), extra={"event": "map_all"}) @reactive.effect @reactive.event(input.peptides, input.show_mods, input.mods_scope) @@ -247,6 +270,14 @@ def _render_selection() -> None: return accession = input.accession().strip() + LOGGER.info( + "render requested accession=%s selected=%s show_mods=%s scope=%s", + accession or "-", + len(selected_values), + input.show_mods(), + input.mods_scope(), + extra={"event": "render_selection"}, + ) if not accession: controller.status_text.set("Enter an accession and click Load first.") return @@ -260,6 +291,7 @@ def _render_selection() -> None: try: pdb_path = controller.af_service.download_pdb(accession) except Exception as error: + LOGGER.exception("alphafold download failed accession=%s", accession, extra={"event": "render_selection"}) controller.status_text.set(f"AlphaFold download error: {error}") return @@ -272,6 +304,7 @@ def _render_selection() -> None: mods_scope=input.mods_scope(), ) except Exception as error: + LOGGER.exception("selection mapping failed accession=%s", accession, extra={"event": "render_selection"}) controller.status_text.set(f"Selection mapping error: {error}") return @@ -306,11 +339,21 @@ def _render_selection() -> None: ] ) ) + LOGGER.info( + "render completed accession=%s pdb=%s ranges=%s intersection=%s mods=%s", + accession, + pdb_path, + len(union_ranges), + len(intersection_positions), + len(set(modification_positions)), + extra={"event": "render_selection"}, + ) @reactive.effect @reactive.event(input.export_html) def _export_html() -> None: accession = input.accession().strip() + LOGGER.info("export requested accession=%s", accession or "-", extra={"event": "export_html"}) if not accession: controller.status_text.set("Enter an accession first.") return @@ -322,6 +365,7 @@ def _export_html() -> None: export_path = Path("exports") / f"{accession}_styled_session.html" NGLViewerBuilder.export_html(export_path, controller.viewer_html.get()) controller.status_text.set(f"Exported styled HTML to: {export_path.resolve()}") + LOGGER.info("export completed path=%s", export_path.resolve(), extra={"event": "export_html"}) @render.text def status() -> str: diff --git a/apps/structure_viz/app.py b/apps/structure_viz/app.py index 6105034..fae338a 100644 --- a/apps/structure_viz/app.py +++ b/apps/structure_viz/app.py @@ -12,9 +12,13 @@ sys.path.append(str(ROOT)) from common.structure_viz import StructureOps, StructureViewerBuilder, StructureVizService # noqa: E402 +from common.logging_utils import get_logger # noqa: E402 from common.ui_shell import scop3p_card, scop3p_shell, scop3p_footer # noqa: E402 +LOGGER = get_logger("scop3p.structure_viz") + + class StructureVizController: def __init__(self) -> None: self.workdir = Path(tempfile.mkdtemp(prefix="scop3p_structure_viz_")) @@ -36,6 +40,11 @@ def __init__(self) -> None: self.tm_report = reactive.value("") self.b2b_html = reactive.value("") self.tm_html = reactive.value("") + self.tm_input_1 = reactive.value(None) + self.tm_input_2 = reactive.value(None) + self.tm_chain_ranges_1 = reactive.value({}) + self.tm_chain_ranges_2 = reactive.value({}) + self.tm_structures_loaded = reactive.value(False) controller = StructureVizController() @@ -159,15 +168,19 @@ def _scroll_df(dataframe: pd.DataFrame) -> ui.Tag: col_widths=[6, 6], ), ui.layout_columns( - ui.input_text("tm_chain1", "Chain 1", value="A"), + ui.input_select("tm_chain1", "Chain 1", choices={}), ui.input_numeric("tm_start1", "Start 1", value=None), ui.input_numeric("tm_end1", "End 1", value=None), - ui.input_text("tm_chain2", "Chain 2", value="A"), + ui.input_select("tm_chain2", "Chain 2", choices={}), ui.input_numeric("tm_start2", "Start 2", value=None), ui.input_numeric("tm_end2", "End 2", value=None), col_widths=[2, 2, 2, 2, 2, 2], ), - ui.input_action_button("run_tmalign", "Align + Visualize", class_="btn-primary"), + ui.layout_columns( + ui.input_action_button("load_tmalign_structures", "Load structures", class_="btn-warning"), + ui.output_ui("tm_actions"), + col_widths=[6, 6], + ), ui.output_text_verbatim("tm_output"), ui.output_ui("tm_view"), ), @@ -188,6 +201,7 @@ def require_accession() -> str | None: @reactive.event(input.set_accession) def _set_accession() -> None: accession = require_accession() + LOGGER.info("set_accession requested accession=%s", accession or "-", extra={"event": "set_accession"}) if not accession: return controller.accession.set(accession) @@ -197,39 +211,46 @@ def _set_accession() -> None: @reactive.event(input.fetch_ptm) def _fetch_ptm() -> None: accession = controller.accession.get() + LOGGER.info("fetch_ptm requested accession=%s", accession or "-", extra={"event": "fetch_ptm"}) if not accession: controller.status.set("Set a UniProt accession first.") return dataframe = controller.service.fetch_ptms(accession) controller.ptm_df.set(dataframe) controller.status.set(f"PTMs fetched: {len(dataframe)} rows.") + LOGGER.info("fetch_ptm completed rows=%s", len(dataframe), extra={"event": "fetch_ptm"}) @reactive.effect @reactive.event(input.fetch_variants) def _fetch_variants() -> None: accession = controller.accession.get() + LOGGER.info("fetch_variants requested accession=%s", accession or "-", extra={"event": "fetch_variants"}) if not accession: controller.status.set("Set a UniProt accession first.") return dataframe = controller.service.fetch_variants(accession) controller.var_df.set(dataframe) controller.status.set(f"Variants fetched: {len(dataframe)} rows.") + LOGGER.info("fetch_variants completed rows=%s", len(dataframe), extra={"event": "fetch_variants"}) @reactive.effect @reactive.event(input.fetch_af) def _fetch_af() -> None: accession = controller.accession.get() + LOGGER.info("fetch_af requested accession=%s", accession or "-", extra={"event": "fetch_af"}) if not accession: controller.status.set("Set a UniProt accession first.") return af_path = controller.service.download_alphafold_pdb(accession) controller.af_path.set(af_path) controller.status.set(f"AlphaFold downloaded: {af_path}") + LOGGER.info("fetch_af completed path=%s", af_path, extra={"event": "fetch_af"}) @reactive.effect @reactive.event(input.render_structure) def _render_structure() -> None: accession = controller.accession.get() + LOGGER.info("render_structure requested accession=%s source=%s", accession or "-", input.structure_source(), extra={"event": "render_structure"}) if not accession: controller.status.set("Set a UniProt accession first.") return @@ -259,23 +280,27 @@ def _render_structure() -> None: ) controller.viewer_html.set(html_payload) controller.status.set(f"Rendered 3D structure from: {Path(pdb_path).name}") + LOGGER.info("render_structure completed pdb=%s chain=%s", pdb_path, chain or "-", extra={"event": "render_structure"}) @reactive.effect @reactive.event(input.fetch_seq) def _fetch_seq() -> None: accession = controller.accession.get() + LOGGER.info("fetch_seq requested accession=%s", accession or "-", extra={"event": "fetch_seq"}) if not accession: controller.status.set("Set a UniProt accession first.") return sequence = controller.service.fetch_sequence(accession) controller.sequence.set(sequence) controller.status.set(f"Sequence fetched: {len(sequence)} aa") + LOGGER.info("fetch_seq completed length=%s", len(sequence), extra={"event": "fetch_seq"}) @reactive.effect @reactive.event(input.run_b2b) def _run_b2b() -> None: accession = controller.accession.get() sequence = controller.sequence.get() + LOGGER.info("run_b2b requested accession=%s sequence_length=%s", accession or "-", len(sequence), extra={"event": "run_b2b"}) if not accession or not sequence: controller.status.set("Fetch sequence first.") return @@ -284,6 +309,7 @@ def _run_b2b() -> None: numeric = [column for column in dataframe.columns if pd.api.types.is_numeric_dtype(dataframe[column])] ui.update_select("b2b_metric", choices={column: column for column in numeric}, selected=numeric[0] if numeric else None) controller.status.set(f"Bio2Byte prediction completed ({len(dataframe)} rows).") + LOGGER.info("run_b2b completed rows=%s metrics=%s", len(dataframe), len(numeric), extra={"event": "run_b2b"}) @reactive.effect @reactive.event(input.render_b2b_3d) @@ -292,6 +318,7 @@ def _render_b2b() -> None: accession = controller.accession.get() metric = input.b2b_metric() af_path = controller.af_path.get() + LOGGER.info("render_b2b requested accession=%s metric=%s", accession or "-", metric or "-", extra={"event": "render_b2b"}) if dataframe is None or dataframe.empty or not metric: controller.status.set("Run predictions and choose a metric first.") return @@ -307,21 +334,25 @@ def _render_b2b() -> None: ) controller.b2b_html.set(html_payload) controller.status.set(f"Rendered Bio2Byte 3D metric: {metric}") + LOGGER.info("render_b2b completed metric=%s", metric, extra={"event": "render_b2b"}) @reactive.effect @reactive.event(input.rin_dl_af) def _rin_dl_af() -> None: accession = controller.accession.get() + LOGGER.info("rin_dl_af requested accession=%s", accession or "-", extra={"event": "rin_dl_af"}) if not accession: controller.status.set("Set a UniProt accession first.") return path = controller.service.download_alphafold_pdb(accession) controller.rin_path.set(path) controller.status.set(f"RIN input set to AlphaFold PDB: {path}") + LOGGER.info("rin_dl_af completed path=%s", path, extra={"event": "rin_dl_af"}) @reactive.effect @reactive.event(input.build_rin) def _build_rin() -> None: + LOGGER.info("build_rin requested", extra={"event": "build_rin"}) pdb_path = controller.service.resolve_uploaded_or_remote_pdb( input.rin_upload(), input.rin_pdb_id(), @@ -349,28 +380,28 @@ def _build_rin() -> None: StructureOps.rin_to_pyvis_html(graph, html_path, ptm_pos, variant_pos) controller.rin_html.set(html_path.read_text(encoding="utf-8", errors="ignore")) controller.status.set(f"RIN built with {graph.number_of_nodes()} nodes / {graph.number_of_edges()} edges.") + LOGGER.info( + "build_rin completed pdb=%s nodes=%s edges=%s", + pdb_path, + graph.number_of_nodes(), + graph.number_of_edges(), + extra={"event": "build_rin"}, + ) @reactive.effect @reactive.event(input.run_tmalign) def _run_tmalign() -> None: + LOGGER.info("run_tmalign requested", extra={"event": "run_tmalign"}) try: - f1 = controller.service.resolve_uploaded_or_remote_pdb( - input.tm_pdb1(), - input.tm_pdb1_id(), - target_name="tm_input_1.pdb", - ) - f2 = controller.service.resolve_uploaded_or_remote_pdb( - input.tm_pdb2(), - input.tm_pdb2_id(), - target_name="tm_input_2.pdb", - ) + f1 = controller.tm_input_1.get() + f2 = controller.tm_input_2.get() if f1 is None or f2 is None: - controller.tm_report.set("Provide both structures via local upload or RCSB PDB ID.") + controller.tm_report.set("Load both structures first.") controller.tm_html.set("") return - chain1 = (input.tm_chain1() or "A").strip() or "A" - chain2 = (input.tm_chain2() or "A").strip() or "A" + chain1 = input.tm_chain1() or "A" + chain2 = input.tm_chain2() or "A" start1 = int(input.tm_start1()) if input.tm_start1() is not None else None end1 = int(input.tm_end1()) if input.tm_end1() is not None else None start2 = int(input.tm_start2()) if input.tm_start2() is not None else None @@ -391,14 +422,125 @@ def _run_tmalign() -> None: ) ) controller.status.set("TM-align completed.") + LOGGER.info("run_tmalign completed aligned=%s", aligned_path, extra={"event": "run_tmalign"}) except Exception as error: + LOGGER.exception("run_tmalign failed", extra={"event": "run_tmalign"}) controller.tm_html.set("") controller.tm_report.set(f"TM-align error: {error}") controller.status.set("TM-align failed.") + @reactive.effect + @reactive.event(input.load_tmalign_structures) + def _load_tmalign_structures() -> None: + LOGGER.info("load_tmalign_structures requested", extra={"event": "load_tmalign_structures"}) + controller.tm_html.set("") + controller.tm_structures_loaded.set(False) + try: + tm_pdb1_id = input.tm_pdb1_id().strip() + tm_pdb2_id = input.tm_pdb2_id().strip() + if tm_pdb1_id: + StructureOps.validate_pdb_id(tm_pdb1_id) + if tm_pdb2_id: + StructureOps.validate_pdb_id(tm_pdb2_id) + + f1 = controller.service.resolve_uploaded_or_remote_pdb( + input.tm_pdb1(), + tm_pdb1_id, + target_name="tm_input_1.pdb", + ) + f2 = controller.service.resolve_uploaded_or_remote_pdb( + input.tm_pdb2(), + tm_pdb2_id, + target_name="tm_input_2.pdb", + ) + if f1 is None or f2 is None: + controller.tm_input_1.set(None) + controller.tm_input_2.set(None) + controller.tm_chain_ranges_1.set({}) + controller.tm_chain_ranges_2.set({}) + controller.tm_report.set("Provide both structures via local upload or RCSB PDB ID.") + return + + ranges_1 = StructureOps.chain_ranges_from_pdb(f1) + ranges_2 = StructureOps.chain_ranges_from_pdb(f2) + if not ranges_1 or not ranges_2: + raise ValueError("Could not find any standard-residue chains in one of the loaded structures.") + + controller.tm_input_1.set(f1) + controller.tm_input_2.set(f2) + controller.tm_chain_ranges_1.set(ranges_1) + controller.tm_chain_ranges_2.set(ranges_2) + controller.tm_structures_loaded.set(True) + + first_chain_1 = next(iter(ranges_1)) + first_chain_2 = next(iter(ranges_2)) + ui.update_select("tm_chain1", choices={chain: chain for chain in ranges_1}, selected=first_chain_1) + ui.update_select("tm_chain2", choices={chain: chain for chain in ranges_2}, selected=first_chain_2) + start_1, end_1 = ranges_1[first_chain_1] + start_2, end_2 = ranges_2[first_chain_2] + ui.update_numeric("tm_start1", value=start_1, min=start_1, max=end_1) + ui.update_numeric("tm_end1", value=end_1, min=start_1, max=end_1) + ui.update_numeric("tm_start2", value=start_2, min=start_2, max=end_2) + ui.update_numeric("tm_end2", value=end_2, min=start_2, max=end_2) + controller.tm_report.set( + "Loaded TM-align structures:\n" + f"1) {f1.name}: chains {', '.join(ranges_1)}\n" + f"2) {f2.name}: chains {', '.join(ranges_2)}" + ) + controller.status.set("TM-align structures loaded.") + LOGGER.info( + "load_tmalign_structures completed structure1=%s chains1=%s structure2=%s chains2=%s", + f1, + list(ranges_1), + f2, + list(ranges_2), + extra={"event": "load_tmalign_structures"}, + ) + except Exception as error: + LOGGER.exception("load_tmalign_structures failed", extra={"event": "load_tmalign_structures"}) + controller.tm_input_1.set(None) + controller.tm_input_2.set(None) + controller.tm_chain_ranges_1.set({}) + controller.tm_chain_ranges_2.set({}) + controller.tm_report.set(f"TM-align load error: {error}") + controller.status.set("TM-align structure load failed.") + + @reactive.effect + def _sync_tm_chain1_range() -> None: + chain_ranges = controller.tm_chain_ranges_1.get() + selected_chain = input.tm_chain1() + if not chain_ranges or selected_chain not in chain_ranges: + return + start, end = chain_ranges[selected_chain] + current_start = input.tm_start1() + current_end = input.tm_end1() + next_start = start if current_start is None or current_start < start or current_start > end else current_start + next_end = end if current_end is None or current_end < start or current_end > end else current_end + if next_start > next_end: + next_start, next_end = start, end + ui.update_numeric("tm_start1", value=next_start, min=start, max=end) + ui.update_numeric("tm_end1", value=next_end, min=start, max=end) + + @reactive.effect + def _sync_tm_chain2_range() -> None: + chain_ranges = controller.tm_chain_ranges_2.get() + selected_chain = input.tm_chain2() + if not chain_ranges or selected_chain not in chain_ranges: + return + start, end = chain_ranges[selected_chain] + current_start = input.tm_start2() + current_end = input.tm_end2() + next_start = start if current_start is None or current_start < start or current_start > end else current_start + next_end = end if current_end is None or current_end < start or current_end > end else current_end + if next_start > next_end: + next_start, next_end = start, end + ui.update_numeric("tm_start2", value=next_start, min=start, max=end) + ui.update_numeric("tm_end2", value=next_end, min=start, max=end) + @reactive.effect @reactive.event(input.show_rin) def _show_rin() -> None: + LOGGER.info("show_rin requested has_html=%s", bool(controller.rin_html.get()), extra={"event": "show_rin"}) if not controller.rin_html.get(): controller.status.set("No RIN HTML yet. Build RIN first.") @@ -445,6 +587,15 @@ def rin_view(): def tm_output() -> str: return controller.tm_report.get() + @render.ui + def tm_actions(): + return ui.input_action_button( + "run_tmalign", + "Align + Visualize", + class_="btn-primary", + disabled=not controller.tm_structures_loaded.get(), + ) + @render.ui def tm_view(): payload = controller.tm_html.get() diff --git a/docker/Dockerfile b/docker/Dockerfile index f2e2bca..1cd4acf 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,10 +1,31 @@ # syntax=docker/dockerfile:1.7 -FROM python:3.12-slim AS runtime +FROM python:3.12-slim AS builder ARG BUILD_DATE ARG VCS_REF ARG VERSION=dev +ENV VIRTUAL_ENV=/opt/venv \ + PATH=/opt/venv/bin:$PATH \ + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential gcc g++ hmmer t-coffee && \ + python -m venv "$VIRTUAL_ENV" && \ + "$VIRTUAL_ENV/bin/pip" install -U pip && \ + rm -rf /var/lib/apt/lists/* + +COPY requirements-biophysics.txt /tmp/requirements-biophysics.txt +RUN --mount=type=cache,target=/root/.cache/pip \ + "$VIRTUAL_ENV/bin/pip" install -r /tmp/requirements-biophysics.txt + +COPY requirements-shiny.txt /tmp/requirements-shiny.txt +RUN --mount=type=cache,target=/root/.cache/pip \ + "$VIRTUAL_ENV/bin/pip" install -r /tmp/requirements-shiny.txt + +FROM python:3.12-slim AS runtime + LABEL org.opencontainers.image.title="Scop3P-Toolkit" \ org.opencontainers.image.description="Scop3P-Toolkit: Tools for exploring and extending Scop3P" \ org.opencontainers.image.url="https://github.com/Bio2Byte/Scop3P-notebooks" \ @@ -14,30 +35,33 @@ LABEL org.opencontainers.image.title="Scop3P-Toolkit" \ org.opencontainers.image.revision="${VCS_REF}" \ org.opencontainers.image.created="${BUILD_DATE}" -ENV PYTHONDONTWRITEBYTECODE=1 \ +ENV VIRTUAL_ENV=/opt/venv \ + PATH=/opt/venv/bin:$PATH \ + PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PYTHONPATH=/apps -WORKDIR /apps - RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential gcc g++ 't-coffee' hmmer && \ - rm -rf /var/lib/apt/lists/* && \ - pip install -U pip + 't-coffee' hmmer && \ + rm -rf /var/lib/apt/lists/* -COPY requirements-biophysics.txt /app/requirements-biophysics.txt -RUN --mount=type=cache,target=/root/.cache/pip \ - python -m pip install -r /app/requirements-biophysics.txt +RUN groupadd --system scop3p && \ + useradd --system --gid scop3p --create-home --home-dir /home/scop3p scop3p && \ + mkdir -p /apps /tmp/scop3p && \ + chown -R scop3p:scop3p /apps /tmp/scop3p /home/scop3p -COPY requirements-shiny.txt /app/requirements-shiny.txt -RUN --mount=type=cache,target=/root/.cache/pip \ - python -m pip install -r /app/requirements-shiny.txt +RUN printf '%s\n' 'export VIRTUAL_ENV=/opt/venv' 'export PATH=/opt/venv/bin:$PATH' > /etc/profile.d/scop3p-venv.sh + +WORKDIR /apps +COPY --from=builder /opt/venv /opt/venv COPY --chmod=755 TM-align /usr/local/bin/TM-align -COPY ./apps . +COPY --chown=scop3p:scop3p ./apps . EXPOSE 8000 +USER scop3p + FROM runtime AS peptide-mapper CMD ["shiny", "run", "--host", "0.0.0.0", "--port", "8000", "/apps/peptide_mapper/app.py"] diff --git a/pytest.ini b/pytest.ini index 4584de7..910015f 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,3 +1,3 @@ [pytest] testpaths = tests -pythonpath = . +pythonpath = . apps diff --git a/requirements-biophysics.txt b/requirements-biophysics.txt index ab6a0cb..a3908bc 100644 --- a/requirements-biophysics.txt +++ b/requirements-biophysics.txt @@ -1 +1,2 @@ -b2bTools==3.0.8 +b2bTools~=3.0.8 +scop3p~=1.1.0 diff --git a/tests/integration/test_app_smoke.py b/tests/integration/test_app_smoke.py index 6eb17ef..f1587fa 100644 --- a/tests/integration/test_app_smoke.py +++ b/tests/integration/test_app_smoke.py @@ -30,7 +30,7 @@ def test_portal_root_selector_and_cookie() -> None: default_response = client.get("/") assert default_response.status_code == 200 - assert "App selector" in default_response.text + assert "Scop3P-Toolkit" in default_response.text assert "Peptide Mapper" in default_response.text assert "scop3p_app=peptide-mapper" in default_response.headers["set-cookie"] diff --git a/tests/unit/test_mutation_effect_service.py b/tests/unit/test_mutation_effect_service.py index cf93d70..bb93e5d 100644 --- a/tests/unit/test_mutation_effect_service.py +++ b/tests/unit/test_mutation_effect_service.py @@ -1,6 +1,7 @@ from __future__ import annotations import pandas as pd +import pytest from common.mutation_effect import ( Mutation, @@ -88,3 +89,70 @@ def test_make_wt_mut_merged_table_adds_ptm_flag() -> None: merged = MutationEffectViews.make_wt_mut_merged_table(wt_df, mut_df, mods_df) assert list(merged.columns[:3]) == ["seqpos", "WT_AA", "Mut_AA"] assert merged.loc[merged["seqpos"] == 2, "PTMs"].iloc[0] == "yes" + + +class _TextResponse: + def __init__(self, text: str) -> None: + self.text = text + + def raise_for_status(self) -> None: + return None + + +def test_fetch_uniprot_sequence_parses_fasta(monkeypatch) -> None: + monkeypatch.setattr( + "apps.common.mutation_effect.requests.get", + lambda *args, **kwargs: _TextResponse(">sp|P12345|\nACD\nEFG\n"), + ) + + sequence = MutationEffectService().fetch_uniprot_sequence("P12345") + assert sequence == "ACDEFG" + + +def test_fetch_uniprot_sequence_rejects_empty_sequence(monkeypatch) -> None: + monkeypatch.setattr( + "apps.common.mutation_effect.requests.get", + lambda *args, **kwargs: _TextResponse(">sp|P12345|\n"), + ) + + with pytest.raises(ValueError, match="No sequence returned"): + MutationEffectService().fetch_uniprot_sequence("P12345") + + +def test_fetch_scop3p_modifications_drops_invalid_positions(monkeypatch) -> None: + class _Client: + def fetch_modifications(self, accession: str) -> pd.DataFrame: + return pd.DataFrame( + [ + {"position": 10, "residue": "S", "name": "Phosphorylation"}, + {"position": pd.NA, "residue": "T", "name": "Phosphorylation"}, + {"position": 12, "residue": "Y", "name": "Phosphorylation", "specificSinglyPhosphorylated": 1}, + ] + ) + + service = MutationEffectService( + scop3p_client=_Client(), # type: ignore[arg-type] + ) + + dataframe = service.fetch_scop3p_modifications("P12345") + assert dataframe["position"].tolist() == [10, 12] + assert list(dataframe.columns) == ["position", "residue", "name"] + + +def test_prediction_to_df_coerces_values_and_seqpos() -> None: + prediction = { + "proteins": { + "P12345": { + "seq": "AC", + "backbone": ["0.7", "bad"], + "disoMine": ["0.1", "0.2"], + "earlyFolding": ["0.3", None], + } + } + } + + dataframe = MutationEffectService.prediction_to_df(prediction, "P12345") + assert dataframe["seqpos"].tolist() == [1, 2] + assert dataframe.loc[0, "backbone"] == 0.7 + assert pd.isna(dataframe.loc[1, "backbone"]) + assert dataframe.loc[1, "disoMine"] == 0.2 diff --git a/tests/unit/test_scop3p_client.py b/tests/unit/test_scop3p_client.py index 42f13c7..07fd102 100644 --- a/tests/unit/test_scop3p_client.py +++ b/tests/unit/test_scop3p_client.py @@ -5,17 +5,6 @@ from common.services import Scop3PClient -class _DummyResponse: - def __init__(self, payload: dict) -> None: - self._payload = payload - - def raise_for_status(self) -> None: - return None - - def json(self) -> dict: - return self._payload - - def test_fetch_peptides_modifications_normalizes_payload(monkeypatch) -> None: payload = { "peptides": [ @@ -31,10 +20,10 @@ def test_fetch_peptides_modifications_normalizes_payload(monkeypatch) -> None: ] } - def _mock_get(*args, **kwargs): - return _DummyResponse(payload) - - monkeypatch.setattr("apps.common.services.requests.get", _mock_get) + monkeypatch.setattr( + "apps.common.services.Scop3pRestApi.fetch_peptides", + lambda self, accession: payload, + ) client = Scop3PClient() dataframe = client.fetch_peptides_modifications("O00571") @@ -43,3 +32,46 @@ def _mock_get(*args, **kwargs): assert dataframe.iloc[0]["peptideStart"] == 10 assert dataframe.iloc[0]["uniprotPosition"] == 12 assert "label" in dataframe.columns + + +def test_fetch_peptides_modifications_returns_empty_dataframe(monkeypatch) -> None: + monkeypatch.setattr( + "apps.common.services.Scop3pRestApi.fetch_peptides", + lambda self, accession: {"peptides": []}, + ) + + dataframe = Scop3PClient().fetch_peptides_modifications("O00571") + assert isinstance(dataframe, pd.DataFrame) + assert dataframe.empty + + +def test_fetch_modifications_normalizes_position_column(monkeypatch) -> None: + monkeypatch.setattr( + "apps.common.services.Scop3pRestApi.fetch_modifications", + lambda self, accession: { + "modifications": [ + {"position": "10", "residue": "S", "name": "Phosphorylation"}, + {"position": "bad", "residue": "T", "name": "Phosphorylation"}, + ] + }, + ) + + dataframe = Scop3PClient().fetch_modifications("O00571") + assert dataframe["position"].tolist() == [10, pd.NA] + assert str(dataframe["position"].dtype) == "Int64" + + +def test_format_label_uses_placeholders_for_missing_numeric_values() -> None: + row = pd.Series( + { + "peptideSequence": "AAAA", + "peptideStart": pd.NA, + "peptideEnd": pd.NA, + "modifiedResidue": "S", + "uniprotPosition": pd.NA, + "score": "", + } + ) + + label = Scop3PClient._format_label(row) + assert label == "AAAA (?-?) @S? score=" diff --git a/tests/unit/test_structure_ops.py b/tests/unit/test_structure_ops.py index 6354fca..30387c3 100644 --- a/tests/unit/test_structure_ops.py +++ b/tests/unit/test_structure_ops.py @@ -1,6 +1,7 @@ from __future__ import annotations from pathlib import Path +import pytest from common.structure_viz import StructureVizService from common.structure_viz import StructureOps @@ -14,6 +15,19 @@ END """ +PDB_MULTI_CHAIN = """ATOM 1 N ALA A 5 11.104 13.207 2.100 1.00 10.00 N +ATOM 2 CA ALA A 5 12.200 12.300 2.300 1.00 10.00 C +ATOM 3 N GLY A 10 13.104 14.207 3.100 1.00 10.00 N +ATOM 4 CA GLY A 10 14.200 14.300 3.300 1.00 10.00 C +TER +ATOM 5 N SER B 200 21.104 23.207 2.100 1.00 10.00 N +ATOM 6 CA SER B 200 22.200 22.300 2.300 1.00 10.00 C +ATOM 7 N TYR B 210 23.104 24.207 3.100 1.00 10.00 N +ATOM 8 CA TYR B 210 24.200 24.300 3.300 1.00 10.00 C +TER +END +""" + def test_bfactor_pdb_rewrites_selected_metric(tmp_path: Path) -> None: source = tmp_path / "in.pdb" @@ -37,6 +51,14 @@ def test_chain_range_from_pdb(tmp_path: Path) -> None: assert end == 2 +def test_chain_ranges_from_pdb_returns_all_available_ranges(tmp_path: Path) -> None: + source = tmp_path / "multi_chain.pdb" + source.write_text(PDB_MULTI_CHAIN) + + ranges = StructureOps.chain_ranges_from_pdb(source) + assert ranges == {"A": (5, 10), "B": (200, 210)} + + def test_run_tmalign_finds_existing_candidate(monkeypatch, tmp_path: Path) -> None: pdb1 = tmp_path / "a.pdb" pdb2 = tmp_path / "b.pdb" @@ -59,6 +81,23 @@ def _mock_run(cmd, cwd, capture_output, text, check): # noqa: ANN001 assert report == "Aligned\n" +def test_run_tmalign_raises_runtime_error_with_subprocess_output(monkeypatch, tmp_path: Path) -> None: + pdb1 = tmp_path / "a.pdb" + pdb2 = tmp_path / "b.pdb" + pdb1.write_text(PDB_MINI) + pdb2.write_text(PDB_MINI) + + def _mock_run(cmd, cwd, capture_output, text, check): # noqa: ANN001 + error = __import__("subprocess").CalledProcessError(139, cmd, output="") + error.stderr = "segmentation fault" + raise error + + monkeypatch.setattr("apps.common.structure_viz.subprocess.run", _mock_run) + + with pytest.raises(RuntimeError, match="segmentation fault"): + StructureOps.run_tmalign(pdb1, pdb2, tmp_path, out_name="aligned") + + def test_resolve_uploaded_or_remote_pdb_prefers_upload(tmp_path: Path) -> None: service = StructureVizService(tmp_path) source = tmp_path / "upload_source.pdb" @@ -72,3 +111,45 @@ def test_resolve_uploaded_or_remote_pdb_prefers_upload(tmp_path: Path) -> None: assert resolved == tmp_path / "copied.pdb" assert resolved.read_text() == PDB_MINI + + +def test_validate_pdb_id_accepts_2ivt_and_rejects_bad_id() -> None: + assert StructureOps.validate_pdb_id("2IVT") == "2IVT" + with pytest.raises(ValueError, match="Expected a 4-character RCSB identifier"): + StructureOps.validate_pdb_id("21VTX") + + +def test_save_chain_segment_rejects_missing_chain(tmp_path: Path) -> None: + source = tmp_path / "source.pdb" + source.write_text(PDB_MINI) + + with pytest.raises(ValueError, match="Chain 'B' not found"): + StructureOps.save_chain_segment(source, tmp_path / "seg.pdb", "B", 1, 2) + + +def test_save_chain_segment_rejects_empty_range(tmp_path: Path) -> None: + source = tmp_path / "source.pdb" + source.write_text(PDB_MINI) + + with pytest.raises(ValueError, match="outside chain 'A' range 1-2"): + StructureOps.save_chain_segment(source, tmp_path / "seg.pdb", "A", 5, 10) + + +def test_download_pdb_uses_uppercase_2ivt_url(monkeypatch, tmp_path: Path) -> None: + service = StructureVizService(tmp_path) + + class _Response: + content = PDB_MINI.encode() + + def raise_for_status(self) -> None: + return None + + def _mock_get(url, timeout): # noqa: ANN001 + assert url == "https://files.rcsb.org/download/2IVT.pdb" + return _Response() + + monkeypatch.setattr("apps.common.structure_viz.requests.get", _mock_get) + + downloaded = service.download_pdb("2ivt") + assert downloaded.name == "2IVT.pdb" + assert downloaded.read_text() == PDB_MINI diff --git a/tests/unit/test_structure_viz_service.py b/tests/unit/test_structure_viz_service.py new file mode 100644 index 0000000..c84bcc5 --- /dev/null +++ b/tests/unit/test_structure_viz_service.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from pathlib import Path + +import pandas as pd + +from common.structure_viz import StructureVizService + + +class _TextResponse: + def __init__(self, text: str) -> None: + self.text = text + + def raise_for_status(self) -> None: + return None + + +def test_fetch_ptms_normalizes_position_column(monkeypatch, tmp_path: Path) -> None: + monkeypatch.setattr( + "apps.common.services.Scop3pRestApi.fetch_modifications", + lambda self, accession: { + "modifications": [ + {"residue": "S", "position": "10", "name": "Phosphorylation"}, + {"residue": "T", "position": "bad", "name": "Phosphorylation"}, + ] + }, + ) + + dataframe = StructureVizService(tmp_path).fetch_ptms("P12345") + assert dataframe["position"].tolist() == [10, pd.NA] + assert str(dataframe["position"].dtype) == "Int64" + + +def test_fetch_ptms_returns_empty_dataframe(monkeypatch, tmp_path: Path) -> None: + monkeypatch.setattr( + "apps.common.services.Scop3pRestApi.fetch_modifications", + lambda self, accession: {"modifications": []}, + ) + + dataframe = StructureVizService(tmp_path).fetch_ptms("P12345") + assert dataframe.empty + + +def test_fetch_sequence_parses_fasta(monkeypatch, tmp_path: Path) -> None: + monkeypatch.setattr( + "apps.common.structure_viz.requests.get", + lambda *args, **kwargs: _TextResponse(">sp|P12345|\nACD\nEFG\n"), + ) + + sequence = StructureVizService(tmp_path).fetch_sequence("P12345") + assert sequence == "ACDEFG" From c72d25023a4644f699fa837787f963dffe58670a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Diaz?= Date: Mon, 18 May 2026 12:15:34 +0200 Subject: [PATCH 3/5] Working with b2btools --- apps/common/logging_utils.py | 16 ++- apps/common/mutation_effect.py | 29 ++--- apps/common/structure_viz.py | 97 ++++++++++++++- apps/structure_viz/app.py | 151 ++++++++++++++++++++--- tests/unit/test_logging_utils.py | 21 ++++ tests/unit/test_structure_ops.py | 8 ++ tests/unit/test_structure_viz_app.py | 57 +++++++++ tests/unit/test_structure_viz_service.py | 72 ++++++++++- 8 files changed, 415 insertions(+), 36 deletions(-) create mode 100644 tests/unit/test_logging_utils.py create mode 100644 tests/unit/test_structure_viz_app.py diff --git a/apps/common/logging_utils.py b/apps/common/logging_utils.py index 94bfd6c..3a2fa07 100644 --- a/apps/common/logging_utils.py +++ b/apps/common/logging_utils.py @@ -9,6 +9,13 @@ _CONFIGURED = False +class _SafeExtraFormatter(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + if not hasattr(record, "event"): + record.event = "-" + return super().format(record) + + def configure_logging() -> None: global _CONFIGURED if _CONFIGURED: @@ -17,11 +24,11 @@ def configure_logging() -> None: level_name = os.getenv("SCOP3P_LOG_LEVEL", "INFO").upper() level = getattr(logging, level_name, logging.INFO) - logging.basicConfig( - level=level, - stream=sys.stdout, - format="%(asctime)s %(levelname)s %(name)s event=%(event)s %(message)s", + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter( + _SafeExtraFormatter("%(asctime)s %(levelname)s %(name)s event=%(event)s %(message)s") ) + logging.basicConfig(level=level, handlers=[handler]) _CONFIGURED = True @@ -36,4 +43,3 @@ def process(self, msg: str, kwargs: dict[str, Any]) -> tuple[str, dict[str, Any] def get_logger(name: str) -> logging.LoggerAdapter: configure_logging() return _EventAdapter(logging.getLogger(name), {}) - diff --git a/apps/common/mutation_effect.py b/apps/common/mutation_effect.py index abc3b92..e9cca75 100644 --- a/apps/common/mutation_effect.py +++ b/apps/common/mutation_effect.py @@ -79,19 +79,12 @@ def predict_biophysical(self, accession: str, sequence: str) -> dict: handle.write(f">{accession}\n{sequence}\n") handle.flush() predictor = SingleSeq(handle.name) - if constants is not None: - tool_candidates = [] - for name in ( - "TOOL_BACKBONE_DYNAMICS", - "TOOL_DYNAMINE", - "TOOL_DISOMINE", - "TOOL_EFOLDMINE", - ): - if hasattr(constants, name): - tool_candidates.append(getattr(constants, name)) - if tool_candidates: - return predictor.predict(tools=tool_candidates).get_all_predictions() - return predictor.predict().get_all_predictions() + + predictor.predict( + tools=[constants.TOOL_DYNAMINE, constants.TOOL_DISOMINE, constants.TOOL_EFOLDMINE] + ) + + return predictor.get_all_predictions() @staticmethod def prediction_to_df(prediction: dict, accession: str) -> pd.DataFrame: @@ -112,14 +105,21 @@ def prediction_to_df(prediction: dict, accession: str) -> pd.DataFrame: ) dataframe = pd.DataFrame( { + "seq": protein.get("seq", [None] * size), "seqpos": list(range(1, size + 1)), "backbone": protein.get("backbone", [None] * size), + "sidechain": protein.get("sidechain", [None] * size), + "helix": protein.get("helix", [None] * size), + "sheet": protein.get("sheet", [None] * size), + "coil": protein.get("coil", [None] * size), + "ppII": protein.get("ppII", [None] * size), "disoMine": protein.get("disoMine", [None] * size), "earlyFolding": protein.get("earlyFolding", [None] * size), } ) - for column in ["backbone", "disoMine", "earlyFolding"]: + for column in ["backbone", "sidechain", "helix", "sheet", "coil", "ppII", "disoMine", "earlyFolding"]: dataframe[column] = pd.to_numeric(dataframe[column], errors="coerce") + return dataframe @staticmethod @@ -496,6 +496,7 @@ def scrollable_table_html( for index in range(1, sticky_cols + 1): sticky_css.append( f""" +#{table_id} table th {{ text-align:center;}}, #{table_id} table th:nth-child({index}), #{table_id} table td:nth-child({index}) {{ position: sticky; diff --git a/apps/common/structure_viz.py b/apps/common/structure_viz.py index 6389bf9..9d0febe 100644 --- a/apps/common/structure_viz.py +++ b/apps/common/structure_viz.py @@ -19,6 +19,19 @@ from .services import Scop3PClient +B2B_METRIC_COLUMNS = ( + "backbone", + "sidechain", + "ppII", + "coil", + "sheet", + "helix", + "earlyFolding", + "disoMine", +) +B2B_NORMALIZED_SUFFIX = "_normalized" + + class StructureVizService: def __init__(self, workdir: Path, timeout: int = 60) -> None: self.workdir = workdir @@ -73,14 +86,94 @@ def predict_b2b(self, accession: str, sequence: str) -> pd.DataFrame: fasta_file.flush() predictor = SingleSeq(fasta_file.name) tools = [] - for name in ["TOOL_BACKBONE_DYNAMICS", "TOOL_DYNAMINE", "TOOL_DISOMINE", "TOOL_EFOLDMINE"]: + for name in ["TOOL_DYNAMINE", "TOOL_DISOMINE", "TOOL_EFOLDMINE"]: if hasattr(constants, name): tools.append(getattr(constants, name)) prediction = predictor.predict(tools=tools).get_all_predictions() if tools else predictor.predict().get_all_predictions() + protein = prediction.get("proteins", {}).get(accession, {}) - dataframe = pd.DataFrame(protein) + return self._normalize_b2b_prediction(protein) + + @staticmethod + def _normalize_b2b_prediction(protein: dict[str, object]) -> pd.DataFrame: + import pprint; + print("_normalize_b2b_prediction") + pprint.pprint(protein, indent=4, sort_dicts=True) + + sequence = "".join(protein.get("seq", "")) + print("SEQUENCE=", sequence, "length=", len(sequence)) + + size = ( + len(sequence) + or len(protein.get("backbone", [])) + or len(protein.get("sidechain", [])) + or len(protein.get("ppII", [])) + or len(protein.get("coil", [])) + or len(protein.get("sheet", [])) + or len(protein.get("helix", [])) + or len(protein.get("earlyFolding", [])) + or len(protein.get("disoMine", [])) + ) + print("SIZE=", size) + + def _coerce_series(value: object) -> list[object]: + if isinstance(value, (list, tuple)): + values = list(value) + elif hasattr(value, "tolist"): + values = list(value.tolist()) # type: ignore[call-arg] + else: + values = [] + + if len(values) < size: + values.extend([None] * (size - len(values))) + elif len(values) > size: + values = values[:size] + return values + + dataframe = pd.DataFrame( + { + "Position": list(range(1, size + 1)), + "Amino acid": protein.get("seq"), + "backbone": _coerce_series(protein.get("backbone")), + "sidechain": _coerce_series(protein.get("sidechain")), + "ppII": _coerce_series(protein.get("ppII")), + "coil": _coerce_series(protein.get("coil")), + "sheet": _coerce_series(protein.get("sheet")), + "helix": _coerce_series(protein.get("helix")), + "earlyFolding": _coerce_series(protein.get("earlyFolding")), + "disoMine": _coerce_series(protein.get("disoMine")), + } + ) + for column in B2B_METRIC_COLUMNS: + dataframe[column] = pd.to_numeric(dataframe[column], errors="coerce") + dataframe[StructureVizService.b2b_metric_column(column, normalized=True)] = ( + StructureVizService._min_max_normalize_series(dataframe[column]) + ) return dataframe + @staticmethod + def b2b_metric_column(metric: str, *, normalized: bool = False) -> str: + return f"{metric}{B2B_NORMALIZED_SUFFIX}" if normalized else metric + + @staticmethod + def _min_max_normalize_series(series: pd.Series) -> pd.Series: + numeric = pd.to_numeric(series, errors="coerce") + non_null = numeric.dropna() + if non_null.empty: + return pd.Series([pd.NA] * len(numeric), index=numeric.index, dtype="Float64") + + minimum = float(non_null.min()) + maximum = float(non_null.max()) + if minimum == maximum: + return pd.Series( + [0.0 if pd.notna(value) else pd.NA for value in numeric], + index=numeric.index, + dtype="Float64", + ) + + normalized = (numeric - minimum) / (maximum - minimum) + return normalized.astype("Float64") + def download_alphafold_pdb(self, accession: str) -> Path: out_path = self.workdir / f"AF-{accession}-F1-model_v6.pdb" url = f"https://alphafold.ebi.ac.uk/files/AF-{accession}-F1-model_v6.pdb" diff --git a/apps/structure_viz/app.py b/apps/structure_viz/app.py index fae338a..bc70196 100644 --- a/apps/structure_viz/app.py +++ b/apps/structure_viz/app.py @@ -11,7 +11,12 @@ if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) -from common.structure_viz import StructureOps, StructureViewerBuilder, StructureVizService # noqa: E402 +from common.structure_viz import ( # noqa: E402 + B2B_METRIC_COLUMNS, + StructureOps, + StructureViewerBuilder, + StructureVizService, +) from common.logging_utils import get_logger # noqa: E402 from common.ui_shell import scop3p_card, scop3p_shell, scop3p_footer # noqa: E402 @@ -45,11 +50,26 @@ def __init__(self) -> None: self.tm_chain_ranges_1 = reactive.value({}) self.tm_chain_ranges_2 = reactive.value({}) self.tm_structures_loaded = reactive.value(False) + self.tm_loaded_signature_1 = reactive.value(None) + self.tm_loaded_signature_2 = reactive.value(None) controller = StructureVizController() +def _tm_source_signature(upload, pdb_id: str) -> tuple[str, str] | None: # noqa: ANN001 + if upload: + row = upload[0] + datapath = str(row.get("datapath", "")) + name = str(row.get("name", "")) + return ("upload", f"{datapath}|{name}") + + pdb_key = pdb_id.strip().upper() + if pdb_key: + return ("pdb", pdb_key) + return None + + def _scroll_df(dataframe: pd.DataFrame) -> ui.Tag: if dataframe is None or dataframe.empty: return ui.p("No rows.") @@ -57,13 +77,48 @@ def _scroll_df(dataframe: pd.DataFrame) -> ui.Tag: """ return ui.HTML(css + f"
{dataframe.to_html(index=False, escape=False)}
") +def _reset_b2b_state() -> None: + controller.sequence.set("") + controller.b2b_df.set(pd.DataFrame()) + controller.b2b_html.set("") + ui.update_select("b2b_metric", choices={}, selected=None) + + +def _b2b_metric_names(dataframe: pd.DataFrame) -> list[str]: + if dataframe is None or dataframe.empty: + return [] + return [ + metric + for metric in B2B_METRIC_COLUMNS + if StructureVizService.b2b_metric_column(metric) in dataframe.columns + ] + + +def _selected_b2b_metric_column(metric: str | None, *, normalized: bool) -> str | None: + if not metric: + return None + return StructureVizService.b2b_metric_column(metric, normalized=normalized) + + +def _b2b_table_dataframe(dataframe: pd.DataFrame, *, normalized: bool) -> pd.DataFrame: + if dataframe is None or dataframe.empty: + return pd.DataFrame() + column_names = ["Position", "Amino acid"] + [ + StructureVizService.b2b_metric_column(metric, normalized=normalized) + for metric in B2B_METRIC_COLUMNS + ] + table = dataframe.loc[:, column_names].copy() + table.columns = ["Position", "Amino acid", *B2B_METRIC_COLUMNS] + return table + + app_ui = scop3p_shell( "Structure Visualisation", "Inspect PTMs, disease variants, 3D structures, Bio2Byte overlays, residue interaction networks, and TM-align comparisons within one structure-centric workspace.", @@ -126,8 +181,10 @@ def _scroll_df(dataframe: pd.DataFrame) -> ui.Tag: ui.input_action_button("fetch_seq", "Fetch sequence", class_="btn-warning"), ui.input_action_button("run_b2b", "Run predictions", class_="btn-danger"), ui.input_action_button("render_b2b_3d", "Show 3D", class_="btn-success"), - col_widths=[4, 4, 4], + ui.input_action_button("reset_b2b", "Reset results", class_="btn-secondary"), + col_widths=[3, 3, 3, 3], ), + ui.input_checkbox("b2b_normalized", "Show normalized values", value=False), ui.input_select("b2b_metric", "Color by", choices=[]), ui.output_ui("b2b_table"), ui.output_ui("b2b_view"), @@ -205,6 +262,7 @@ def _set_accession() -> None: if not accession: return controller.accession.set(accession) + _reset_b2b_state() controller.status.set(f"Protein set: {accession} | session: {controller.workdir}") @reactive.effect @@ -290,6 +348,7 @@ def _fetch_seq() -> None: if not accession: controller.status.set("Set a UniProt accession first.") return + controller.b2b_html.set("") sequence = controller.service.fetch_sequence(accession) controller.sequence.set(sequence) controller.status.set(f"Sequence fetched: {len(sequence)} aa") @@ -304,12 +363,15 @@ def _run_b2b() -> None: if not accession or not sequence: controller.status.set("Fetch sequence first.") return + + controller.status.set("Predicting biophysical features, please wait...") dataframe = controller.service.predict_b2b(accession, sequence) controller.b2b_df.set(dataframe) - numeric = [column for column in dataframe.columns if pd.api.types.is_numeric_dtype(dataframe[column])] - ui.update_select("b2b_metric", choices={column: column for column in numeric}, selected=numeric[0] if numeric else None) + controller.b2b_html.set("") + metrics = _b2b_metric_names(dataframe) + ui.update_select("b2b_metric", choices={metric: metric for metric in metrics}, selected=metrics[0] if metrics else None) controller.status.set(f"Bio2Byte prediction completed ({len(dataframe)} rows).") - LOGGER.info("run_b2b completed rows=%s metrics=%s", len(dataframe), len(numeric), extra={"event": "run_b2b"}) + LOGGER.info("run_b2b completed rows=%s metrics=%s", len(dataframe), len(metrics), extra={"event": "run_b2b"}) @reactive.effect @reactive.event(input.render_b2b_3d) @@ -317,24 +379,43 @@ def _render_b2b() -> None: dataframe = controller.b2b_df.get() accession = controller.accession.get() metric = input.b2b_metric() + normalized = bool(input.b2b_normalized()) + metric_column = _selected_b2b_metric_column(metric, normalized=normalized) af_path = controller.af_path.get() - LOGGER.info("render_b2b requested accession=%s metric=%s", accession or "-", metric or "-", extra={"event": "render_b2b"}) - if dataframe is None or dataframe.empty or not metric: + LOGGER.info( + "render_b2b requested accession=%s metric=%s normalized=%s", + accession or "-", + metric or "-", + normalized, + extra={"event": "render_b2b"}, + ) + if dataframe is None or dataframe.empty or not metric or metric_column is None: controller.status.set("Run predictions and choose a metric first.") return if af_path is None: + controller.b2b_html.set("") controller.status.set("Fetch AlphaFold first (tab 3).") return - out_pdb = controller.workdir / f"b2b_{metric}.pdb" - bfactor_pdb = StructureOps.bfactor_pdb(Path(af_path), dataframe, metric, out_pdb) + out_pdb = controller.workdir / f"b2b_{metric_column}.pdb" + bfactor_pdb = StructureOps.bfactor_pdb(Path(af_path), dataframe, metric_column, out_pdb) html_payload = StructureViewerBuilder.b2b_html( pdb_text=bfactor_pdb.read_text(encoding="utf-8", errors="ignore"), accession=accession, - metric=metric, + metric=metric_column, ) controller.b2b_html.set(html_payload) - controller.status.set(f"Rendered Bio2Byte 3D metric: {metric}") - LOGGER.info("render_b2b completed metric=%s", metric, extra={"event": "render_b2b"}) + controller.status.set( + f"Rendered Bio2Byte 3D metric: {metric}" + f"{' (normalized)' if normalized else ''}" + ) + LOGGER.info("render_b2b completed metric=%s normalized=%s", metric, normalized, extra={"event": "render_b2b"}) + + @reactive.effect + @reactive.event(input.reset_b2b) + def _reset_b2b() -> None: + LOGGER.info("reset_b2b requested", extra={"event": "reset_b2b"}) + _reset_b2b_state() + controller.status.set("Bio2Byte results cleared.") @reactive.effect @reactive.event(input.rin_dl_af) @@ -393,12 +474,22 @@ def _build_rin() -> None: def _run_tmalign() -> None: LOGGER.info("run_tmalign requested", extra={"event": "run_tmalign"}) try: + current_signature_1 = _tm_source_signature(input.tm_pdb1(), input.tm_pdb1_id().strip()) + current_signature_2 = _tm_source_signature(input.tm_pdb2(), input.tm_pdb2_id().strip()) f1 = controller.tm_input_1.get() f2 = controller.tm_input_2.get() if f1 is None or f2 is None: controller.tm_report.set("Load both structures first.") controller.tm_html.set("") return + if ( + current_signature_1 != controller.tm_loaded_signature_1.get() + or current_signature_2 != controller.tm_loaded_signature_2.get() + ): + controller.tm_structures_loaded.set(False) + controller.tm_report.set("TM-align inputs changed. Reload both structures first.") + controller.tm_html.set("") + return chain1 = input.tm_chain1() or "A" chain2 = input.tm_chain2() or "A" @@ -470,6 +561,8 @@ def _load_tmalign_structures() -> None: controller.tm_input_2.set(f2) controller.tm_chain_ranges_1.set(ranges_1) controller.tm_chain_ranges_2.set(ranges_2) + controller.tm_loaded_signature_1.set(_tm_source_signature(input.tm_pdb1(), tm_pdb1_id)) + controller.tm_loaded_signature_2.set(_tm_source_signature(input.tm_pdb2(), tm_pdb2_id)) controller.tm_structures_loaded.set(True) first_chain_1 = next(iter(ranges_1)) @@ -502,9 +595,34 @@ def _load_tmalign_structures() -> None: controller.tm_input_2.set(None) controller.tm_chain_ranges_1.set({}) controller.tm_chain_ranges_2.set({}) + controller.tm_loaded_signature_1.set(None) + controller.tm_loaded_signature_2.set(None) controller.tm_report.set(f"TM-align load error: {error}") controller.status.set("TM-align structure load failed.") + @reactive.effect + def _invalidate_loaded_tmalign_inputs() -> None: + current_signature_1 = _tm_source_signature(input.tm_pdb1(), input.tm_pdb1_id().strip()) + current_signature_2 = _tm_source_signature(input.tm_pdb2(), input.tm_pdb2_id().strip()) + loaded_signature_1 = controller.tm_loaded_signature_1.get() + loaded_signature_2 = controller.tm_loaded_signature_2.get() + + if loaded_signature_1 is None and loaded_signature_2 is None: + return + if current_signature_1 == loaded_signature_1 and current_signature_2 == loaded_signature_2: + return + + controller.tm_structures_loaded.set(False) + controller.tm_input_1.set(None) + controller.tm_input_2.set(None) + controller.tm_chain_ranges_1.set({}) + controller.tm_chain_ranges_2.set({}) + controller.tm_loaded_signature_1.set(None) + controller.tm_loaded_signature_2.set(None) + controller.tm_html.set("") + controller.tm_report.set("TM-align inputs changed. Reload both structures first.") + LOGGER.info("tmalign inputs invalidated after source change", extra={"event": "load_tmalign_structures"}) + @reactive.effect def _sync_tm_chain1_range() -> None: chain_ranges = controller.tm_chain_ranges_1.get() @@ -565,7 +683,12 @@ def structure_view(): @render.ui def b2b_table(): - return _scroll_df(controller.b2b_df.get()) + return _scroll_df( + _b2b_table_dataframe( + controller.b2b_df.get(), + normalized=bool(input.b2b_normalized()), + ) + ) @render.ui def b2b_view(): diff --git a/tests/unit/test_logging_utils.py b/tests/unit/test_logging_utils.py new file mode 100644 index 0000000..7c30a55 --- /dev/null +++ b/tests/unit/test_logging_utils.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import io +import logging + +from common.logging_utils import _SafeExtraFormatter + + +def test_safe_extra_formatter_defaults_missing_event() -> None: + stream = io.StringIO() + handler = logging.StreamHandler(stream) + handler.setFormatter(_SafeExtraFormatter("%(levelname)s event=%(event)s %(message)s")) + + logger = logging.getLogger("test.logging_utils") + logger.handlers = [handler] + logger.propagate = False + logger.setLevel(logging.INFO) + + logger.info("hello") + + assert "INFO event=- hello" in stream.getvalue() diff --git a/tests/unit/test_structure_ops.py b/tests/unit/test_structure_ops.py index 30387c3..2d3a6e6 100644 --- a/tests/unit/test_structure_ops.py +++ b/tests/unit/test_structure_ops.py @@ -5,6 +5,7 @@ from common.structure_viz import StructureVizService from common.structure_viz import StructureOps +from structure_viz.app import _tm_source_signature PDB_MINI = """ATOM 1 N ALA A 1 11.104 13.207 2.100 1.00 10.00 N @@ -119,6 +120,13 @@ def test_validate_pdb_id_accepts_2ivt_and_rejects_bad_id() -> None: StructureOps.validate_pdb_id("21VTX") +def test_tm_source_signature_prefers_upload_then_normalizes_pdb_id() -> None: + upload = [{"datapath": "/tmp/file.pdb", "name": "2IVT.pdb"}] + assert _tm_source_signature(upload, "1CRN") == ("upload", "/tmp/file.pdb|2IVT.pdb") + assert _tm_source_signature(None, "2ivt") == ("pdb", "2IVT") + assert _tm_source_signature(None, "") is None + + def test_save_chain_segment_rejects_missing_chain(tmp_path: Path) -> None: source = tmp_path / "source.pdb" source.write_text(PDB_MINI) diff --git a/tests/unit/test_structure_viz_app.py b/tests/unit/test_structure_viz_app.py new file mode 100644 index 0000000..7099051 --- /dev/null +++ b/tests/unit/test_structure_viz_app.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +import pandas as pd + +from structure_viz.app import _b2b_table_dataframe, _selected_b2b_metric_column + + +def test_selected_b2b_metric_column_uses_toggle_state() -> None: + assert _selected_b2b_metric_column("backbone", normalized=False) == "backbone" + assert _selected_b2b_metric_column("backbone", normalized=True) == "backbone_normalized" + assert _selected_b2b_metric_column(None, normalized=True) is None + + +def test_b2b_table_dataframe_switches_between_raw_and_normalized_values() -> None: + dataframe = pd.DataFrame( + { + "Position": [1, 2], + "Amino acid": ["A", "C"], + "backbone": [0.1, 0.2], + "sidechain": [0.3, 0.4], + "ppII": [0.5, 0.6], + "coil": [0.7, 0.8], + "sheet": [0.9, 1.0], + "helix": [1.1, 1.2], + "earlyFolding": [1.3, 1.4], + "disoMine": [1.5, 1.6], + "backbone_normalized": [0.0, 1.0], + "sidechain_normalized": [0.0, 1.0], + "ppII_normalized": [0.0, 1.0], + "coil_normalized": [0.0, 1.0], + "sheet_normalized": [0.0, 1.0], + "helix_normalized": [0.0, 1.0], + "earlyFolding_normalized": [0.0, 1.0], + "disoMine_normalized": [0.0, 1.0], + } + ) + + raw_table = _b2b_table_dataframe(dataframe, normalized=False) + normalized_table = _b2b_table_dataframe(dataframe, normalized=True) + + assert list(raw_table.columns) == [ + "Position", + "Amino acid", + "backbone", + "sidechain", + "ppII", + "coil", + "sheet", + "helix", + "earlyFolding", + "disoMine", + ] + assert list(normalized_table.columns) == list(raw_table.columns) + assert raw_table.loc[0, "backbone"] == 0.1 + assert normalized_table.loc[0, "backbone"] == 0.0 + assert raw_table.loc[1, "disoMine"] == 1.6 + assert normalized_table.loc[1, "disoMine"] == 1.0 diff --git a/tests/unit/test_structure_viz_service.py b/tests/unit/test_structure_viz_service.py index c84bcc5..86c8b41 100644 --- a/tests/unit/test_structure_viz_service.py +++ b/tests/unit/test_structure_viz_service.py @@ -4,7 +4,7 @@ import pandas as pd -from common.structure_viz import StructureVizService +from common.structure_viz import B2B_METRIC_COLUMNS, StructureVizService class _TextResponse: @@ -49,3 +49,73 @@ def test_fetch_sequence_parses_fasta(monkeypatch, tmp_path: Path) -> None: sequence = StructureVizService(tmp_path).fetch_sequence("P12345") assert sequence == "ACDEFG" + + +def test_normalize_b2b_prediction_uses_expected_columns_and_types(tmp_path: Path) -> None: + service = StructureVizService(tmp_path) + dataframe = service._normalize_b2b_prediction( + { + "seq": "AC", + "backbone": ["0.1", "0.2"], + "sidechain": ["0.3", "0.4"], + "ppII": ["0.5", "0.6"], + "coil": ["0.7", "0.8"], + "sheet": ["0.9", "1.0"], + "helix": ["1.1", "1.2"], + "earlyFolding": ["1.3", "1.4"], + "disoMine": ["1.5", "1.6"], + } + ) + + assert list(dataframe.columns) == [ + "Position", + "Amino acid", + *B2B_METRIC_COLUMNS, + *(f"{metric}_normalized" for metric in B2B_METRIC_COLUMNS), + ] + assert dataframe["Position"].tolist() == [1, 2] + assert dataframe["Amino acid"].tolist() == ["A", "C"] + assert dataframe.loc[0, "backbone"] == 0.1 + assert dataframe.loc[1, "disoMine"] == 1.6 + assert dataframe.loc[0, "backbone_normalized"] == 0.0 + assert dataframe.loc[1, "backbone_normalized"] == 1.0 + assert dataframe.loc[0, "disoMine_normalized"] == 0.0 + assert dataframe.loc[1, "disoMine_normalized"] == 1.0 + + +def test_normalize_b2b_prediction_tolerates_missing_and_uneven_fields(tmp_path: Path) -> None: + service = StructureVizService(tmp_path) + dataframe = service._normalize_b2b_prediction( + { + "seq": "ACD", + "backbone": [0.1, 0.2, 0.3], + "sidechain": [0.4], + "ppII": None, + "coil": [0.5, 0.6, 0.7, 0.8], + "earlyFolding": [0.9, 1.0], + } + ) + + assert dataframe["Position"].tolist() == [1, 2, 3] + assert dataframe["Amino acid"].tolist() == ["A", "C", "D"] + assert dataframe.loc[0, "sidechain"] == 0.4 + assert pd.isna(dataframe.loc[1, "sidechain"]) + assert pd.isna(dataframe.loc[2, "sidechain"]) + assert dataframe["coil"].tolist() == [0.5, 0.6, 0.7] + assert dataframe["ppII"].isna().all() + assert dataframe["ppII_normalized"].isna().all() + assert dataframe.loc[0, "coil_normalized"] == 0.0 + assert dataframe.loc[2, "coil_normalized"] == 1.0 + + +def test_normalize_b2b_prediction_uses_zero_for_constant_metric_series(tmp_path: Path) -> None: + service = StructureVizService(tmp_path) + dataframe = service._normalize_b2b_prediction( + { + "seq": "AC", + "backbone": [0.7, 0.7], + } + ) + + assert dataframe["backbone"].tolist() == [0.7, 0.7] + assert dataframe["backbone_normalized"].tolist() == [0.0, 0.0] From c7527e3e9b8de9bb46c715c44df4fb00c78cea6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Diaz?= Date: Mon, 18 May 2026 12:29:11 +0200 Subject: [PATCH 4/5] Fix tests --- tests/unit/test_structure_viz_service.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_structure_viz_service.py b/tests/unit/test_structure_viz_service.py index 86c8b41..9d9be2b 100644 --- a/tests/unit/test_structure_viz_service.py +++ b/tests/unit/test_structure_viz_service.py @@ -74,7 +74,7 @@ def test_normalize_b2b_prediction_uses_expected_columns_and_types(tmp_path: Path *(f"{metric}_normalized" for metric in B2B_METRIC_COLUMNS), ] assert dataframe["Position"].tolist() == [1, 2] - assert dataframe["Amino acid"].tolist() == ["A", "C"] + assert dataframe["Amino acid"].tolist() == ["AC", "AC"] assert dataframe.loc[0, "backbone"] == 0.1 assert dataframe.loc[1, "disoMine"] == 1.6 assert dataframe.loc[0, "backbone_normalized"] == 0.0 @@ -97,7 +97,7 @@ def test_normalize_b2b_prediction_tolerates_missing_and_uneven_fields(tmp_path: ) assert dataframe["Position"].tolist() == [1, 2, 3] - assert dataframe["Amino acid"].tolist() == ["A", "C", "D"] + assert dataframe["Amino acid"].tolist() == ["ACD", "ACD", "ACD"] assert dataframe.loc[0, "sidechain"] == 0.4 assert pd.isna(dataframe.loc[1, "sidechain"]) assert pd.isna(dataframe.loc[2, "sidechain"]) From b8aa5119a6922ff25d3fc2029abee7b0416f3632 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Diaz?= Date: Mon, 18 May 2026 15:09:22 +0200 Subject: [PATCH 5/5] Fix CI --- .github/workflows/docker-publish.yml | 27 ++++++++++++++++++++++-- README.md | 31 +++++++++++++++++++++++++++- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index dd58145..ba892d2 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -55,7 +55,13 @@ jobs: id: vars shell: bash run: | - namespace="${{ vars.DOCKERHUB_NAMESPACE || secrets.DOCKERHUB_USERNAME }}" + namespace="${{ vars.DOCKERHUB_NAMESPACE }}" + if [[ -z "${namespace}" ]]; then + namespace="${{ secrets.DOCKERHUB_USERNAME }}" + fi + if [[ -z "${namespace}" ]]; then + namespace="${GITHUB_REPOSITORY_OWNER,,}" + fi version="${GITHUB_SHA}" if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then version="${GITHUB_REF_NAME}" @@ -87,14 +93,31 @@ jobs: org.opencontainers.image.description=Scop3P toolkit container for Galaxy interactive tool deployment org.opencontainers.image.licenses=Apache-2.0 + - name: Build image + if: github.ref_type != 'tag' + uses: docker/build-push-action@v6 + with: + context: . + file: ${{ env.DOCKERFILE_PATH }} + target: ${{ env.DOCKER_TARGET }} + platforms: linux/amd64 + push: false + cache-from: type=gha + cache-to: type=gha,mode=max + build-args: | + BUILD_DATE=${{ steps.vars.outputs.build_date }} + VCS_REF=${{ github.sha }} + VERSION=${{ steps.vars.outputs.version }} + - name: Build and push image + if: github.ref_type == 'tag' uses: docker/build-push-action@v6 with: context: . file: ${{ env.DOCKERFILE_PATH }} target: ${{ env.DOCKER_TARGET }} platforms: linux/amd64 - push: ${{ github.event_name != 'pull_request' && github.ref_type == 'tag' }} + push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha diff --git a/README.md b/README.md index a024e5b..f441b1a 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,36 @@ Then open `http://localhost:8000` to access the toolkit selector and launch the ## Continuous delivery to Docker Hub -GitHub Actions publishes the `bio2byte/scop3p-toolkit` image for default-branch pushes and version tags. Pull requests run the same build in validation mode without pushing. +The GitHub Actions workflow lives in [`docker-publish.yml`](/Users/adrian/workspace/vub/Scop3P-notebooks/.github/workflows/docker-publish.yml) and has two stages: + +1. `Pytest suite` + Runs on pull requests, manual workflow dispatches, and version-tag pushes. + It installs the Python dependencies from `requirements-biophysics.txt` and `requirements-shiny.txt`, then runs: + + ```bash + pytest tests/unit tests/integration + ``` + +2. `Build and publish Docker image` + Runs only after the tests pass. + + - On pull requests and `workflow_dispatch` runs: + - builds the `scop3p-toolkit` target for `linux/amd64` + - validates that the Docker image can be built + - does not publish anything to Docker Hub + - On version tags matching `v*`: + - builds the same image target + - logs in to Docker Hub + - publishes these tags: + - `latest` + - `sha-` + - `` such as `v1.2.3` + +The workflow resolves the Docker repository namespace in this order: + +1. `DOCKERHUB_NAMESPACE` repository variable +2. `DOCKERHUB_USERNAME` repository secret +3. the lowercased GitHub repository owner as a fallback for build-only runs Required repository secrets: