Metadata-Version: 2.4
Name: frustration-gpu
Version: 0.1.3
Summary: Pure-PyTorch reimplementation of LAMMPS-AWSEM frustration analysis (Wolynes-lab AWSEM Hamiltonian + Ferreiro frustration index), GPU-accelerated.
Author: Hassan Alhabeeb
License:                                  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 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 accept and charge a
              fee for the 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 2026 Hassan Alhabeeb
        
           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.
        
Project-URL: Homepage, https://github.com/Hassan-Alhabeeb/frustration_gpu
Project-URL: Repository, https://github.com/Hassan-Alhabeeb/frustration_gpu
Project-URL: Issues, https://github.com/Hassan-Alhabeeb/frustration_gpu/issues
Keywords: frustration,AWSEM,protein,allosteric,GPU,PyTorch,structural-biology,biophysics
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Chemistry
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Environment :: GPU :: NVIDIA CUDA
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: torch>=2.0
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=1.5
Requires-Dist: biopython>=1.81
Provides-Extra: cuda
Requires-Dist: torch>=2.0; extra == "cuda"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-xdist>=3.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.5; extra == "viz"
Dynamic: license-file

# frustration-gpu

Pure-PyTorch reimplementation of LAMMPS-AWSEM frustration analysis. 14 to 53x faster on a single GPU, byte-comparable to frustratometeR / frustrapy.

[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![Tests](https://img.shields.io/badge/tests-223_passing-brightgreen.svg)](tests/)
[![PyPI](https://img.shields.io/pypi/v/frustration-gpu.svg)](https://pypi.org/project/frustration-gpu/)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.20323294.svg)](https://doi.org/10.5281/zenodo.20323294)

```python
from frustration_gpu import compute_frustration

result = compute_frustration("5AON.pdb", mode="configurational")
print(result.pair_records.head())
```

Same physics as frustratometeR. 14x faster (median) than frustrapy on CPU, 53x faster on GPU for a 451-residue protein in mutational mode. FI Spearman is >= 0.9975 against the LAMMPS-AWSEM C++ reference on every panel run.

## Why

frustratometeR / frustrapy is the canonical implementation of Ferreiro-Wolynes frustration analysis, but it wraps a precompiled LAMMPS-AWSEM binary that has no GPU support. On large proteins, mutational-mode analysis runs ~N x 20 LAMMPS subprocesses and takes tens of seconds per structure, prohibitive at proteome scale.

This package re-derives the AWSEM Hamiltonian (water + burial + Debye-Huckel) and the Ferreiro frustration index in pure PyTorch, batched as tensor operations that run identically on CPU and CUDA. The math is traceable line-by-line to the upstream `fix_backbone.cpp`: no shortcuts, no approximations, no alternative physics.

## Benchmarks (Phase 5, 20-PDB panel)

Hardware: AMD Ryzen 9 5900X + RTX 4070 (12 GB), Windows 11 host, PyTorch 2.6.0+cu124. Frustrapy runs on a 32-core EPYC VM (`root@10.1.0.45`), single-PDB single-threaded, the apples-to-apples comparison that frustrapy users experience.

### Head-to-head vs frustrapy CPU (4 PDBs x 3 modes)

| PDB | N res | mode | frustrapy CPU (s) | ours GPU (ms) | Speedup |
|---|---|---|---|---|---|
| 5AON | 49  | configurational | 0.220  | 70.7  | 3.1x |
| 11BG | 248 | configurational | 0.320  | 206.4 | 1.6x |
| 1O3S | 200 | configurational | 0.340  | 159.8 | 2.1x |
| 3F9M | 451 | configurational | 0.420  | 346.3 | 1.2x |
| 5AON | 49  | mutational      | 0.810  | 70.5  | **11.5x** |
| 11BG | 248 | mutational      | 7.336  | 203.5 | **36.0x** |
| 1O3S | 200 | mutational      | 4.812  | 156.6 | **30.7x** |
| 3F9M | 451 | mutational      | 22.407 | 425.6 | **52.6x** |
| 5AON | 49  | singleresidue   | 0.263  | 19.7  | 13.4x |
| 11BG | 248 | singleresidue   | 0.898  | 54.3  | 16.5x |
| 1O3S | 200 | singleresidue   | 0.730  | 48.0  | 15.2x |
| 3F9M | 451 | singleresidue   | 2.103  | 107.6 | 19.5x |

Configurational mode is already fast in frustrapy (one scalar decoy ensemble), so the GPU speedup there is modest (1.2-3.1x), workload dominated by Python and CUDA-launch overhead. Mutational mode is where the GPU port wins (30-53x): frustrapy fans out ~N x 20 LAMMPS subprocesses while we run one fused-alpha tensor pass on GPU.

Geometric-mean speedup across the 12 head-to-head runs: 17.0x (median 14.3x).

> **Hardware comparison footnote.** Our timings come from a Windows 11 host with an AMD Ryzen 9 5900X plus an RTX 4070 (12 GB). frustrapy timings come from a Linux EPYC VM (32 cores allocated, no GPU). Both runs use single-threaded execution and identical kwargs (`n_decoys=1000`, `seq_dist=12`, `electrostatics_k=None`). The CPU-vs-CPU column is therefore biased by hardware mismatch and is not directly comparable; the headline GPU-vs-CPU comparison (our RTX 4070 vs frustrapy on EPYC CPU) is fair as a real-world deployment comparison: both numbers reflect what users on the typical hardware see.

Raw numbers: `benchmark/phase5_panel_results.csv`, `benchmark/phase5_frustrapy_comparison.csv`. Full writeup: `benchmark/phase5_results.md`.

### Stress test: 4PKN (8,689 residues)

| metric | value |
|---|---|
| N residues parsed | 8,689 |
| N native pairs | 62,911 |
| GPU wall-clock (configurational) | 17.6 s |
| FrstState distribution | 4,350 highly / 41,469 neutral / 17,092 minimally |

`torch.cuda.max_memory_allocated` reported a 22.4 GB high-water mark, exceeding the RTX 4070's 12 GB physical VRAM. This is the PyTorch caching allocator's transient peak (caches plus intermediates that are not all alive simultaneously), not a sustained working set. Real WDDM paging would dominate the wall-clock; the observed 17.6 s is consistent with the effective resident set fitting in VRAM. Alpha-chunking the auxiliary (N, N) tensors built outside the alpha-loop will reduce the reported peak below 8 GB at this size, tracked as a Phase 6 polish item.

## Install

```bash
git clone https://github.com/Hassan-Alhabeeb/frustration_gpu
cd frustration_gpu
pip install -e .
```

For CUDA, install the matching `torch` wheel from the PyTorch index first (see [pytorch.org/get-started](https://pytorch.org/get-started/locally/)); the package then auto-detects CUDA via `torch.cuda.is_available()`.

## Quickstart

```python
from frustration_gpu import compute_frustration

# Default is byte-comparable to LAMMPS-AWSEM + frustratometeR on a clean PDB.
result = compute_frustration("5AON.pdb", mode="configurational", device="auto")

# Top-5 most highly frustrated contacts
top5 = result.pair_records.nsmallest(5, "FrstIndex")
print(top5[["Res1", "Res2", "AA1", "AA2", "r_ij", "FrstIndex", "FrstState"]])

# Per-residue 5adens density
print(result.density_records.head())
```

10-minute walkthrough: [QUICKSTART.md](QUICKSTART.md). Validation evidence: [VALIDATION.md](VALIDATION.md).

## Status

- Configurational, mutational, singleresidue modes: all three implemented and validated.
- FI Spearman >= 0.9975 vs LAMMPS reference on the 10-PDB development panel (30/30 (PDB, mode) combos, lowest is 0.9975 on 3F9M singleresidue). The repo bundles the **4-PDB CI subset** (5AON, 11BG, 1O3S, 3F9M) needed to reproduce the bit-identity gates from a fresh clone; the full 10-PDB panel is reproducible by pointing `benchmark/run_phase5.py --pdb-dir <dir>` at the remaining six (PDB IDs in `VALIDATION.md`).
- CPU <-> GPU agreement at machine precision on the bundled 4-PDB panel and the 10-PDB development panel. Rounded outputs (default `precision=3`) match exactly; high-precision FI values agree to ~1e-15 ULP drift driven by reduction-order differences in `decoy_mean` / `decoy_std`, which the FI quantile absorbs at the printed precision.
- Drop-in `calculate_frustration(...)` alias for frustrapy users (`results_dir`, `graphics`, etc. accepted).
- Multi-chain handling, chain filter, residue subset filter, opt-in Debye-Huckel electrostatics.
- LAMMPS-compat flags (`include_dna`, `lammps_compat_altloc`) reproduce frustratometeR's 5adens output byte-comparable on protein-DNA and alt-conformer PDBs.
- Scales to 4PKN (8,689 residues) end-to-end on a single RTX 4070.
- Alpha-chunking for sub-12 GB VRAM at N >= 4,000 (Phase 6 polish, in progress).
- VMD `.tcl` / PyMOL `.pml` visualization output (Phase 6 polish).

## Features

- **Pure PyTorch.** No LAMMPS binary, no OpenMM dependency, no R, no precompiled C++. Runs anywhere `torch` does.
- **Float64 throughout.** No precision compromises for speed; CPU and CUDA agree to machine precision on V_water, V_burial, V_DH.
- **Deterministic.** Reproducible RNG via `seed=...`; frustrapy uses unseeded `srand(NULL)`.
- **Three modes.** Configurational (scalar decoy ensemble), mutational (per-pair decoy stats), singleresidue (per-residue FI).
- **Byte-comparable output.** Default writes `<stem>_tertiary_frustration.dat`, `<stem>_5adens.dat`, etc. in the same column schema as LAMMPS-AWSEM.
- **Explicit opt-in flags** for known frustrapy bugs (`include_dna`, `lammps_compat_altloc`). Defaults are physically clean, opt-ins reproduce the LAMMPS reference exactly.

## Caveats

- For very small proteins (N < 100) CUDA launch overhead can make GPU slower than CPU; use `device="cpu"`.
- One panel cell (5N9R mutational, N=356) shows GPU 33% slower than CPU. See VALIDATION.md section 7.
- Large proteins (>5,000 residues) report a high VRAM allocator peak; alpha-chunking work in progress.
- Sparse or fragmented structures: the configurational sampler now uses direct inverse-CDF sampling over the in-contact set (FIX-4, `frustration_gpu/decoys.py`). If a structure has zero in-contact pairs (highly fragmented or non-physical coords) the call raises a hard `RuntimeError` rather than silently emitting biased fallback samples. There is no rejection-sampler fallback warning in the current code path.

## Documentation

- [QUICKSTART.md](QUICKSTART.md), 10-minute end-to-end walkthrough.
- [VALIDATION.md](VALIDATION.md), numerical validation evidence, reproduction instructions.
- [docs/API.md](docs/API.md), full public function reference.
- [docs/frustrapy_vs_us.md](docs/frustrapy_vs_us.md), kwarg-by-kwarg migration guide.
- [docs/lammps_compat_fixes.md](docs/lammps_compat_fixes.md), the four LAMMPS-compat flags and why they exist.
- [docs/awsem_hamiltonian_spec.md](docs/awsem_hamiltonian_spec.md), Hamiltonian specification.
- Examples: [examples/](examples/) (`01_basic.py`, `02_three_modes.py`, ..., `07_frustrapy_drop_in.py`).

## Citation

If you use this software, please cite both the original AWSEM / frustration work and this port. See [CITATION.cff](CITATION.cff) for machine-readable citation metadata, and [NOTICE](NOTICE) for full algorithmic provenance.

This software is archived on Zenodo. The concept DOI `10.5281/zenodo.20323294` always resolves to the latest release; each version has its own DOI as well.

```bibtex
@software{alhabeeb_frustration_gpu_2026,
  author       = {Alhabeeb, Hassan},
  title        = {frustration\_gpu: Pure-PyTorch LAMMPS-AWSEM Frustration Analysis with GPU Acceleration},
  year         = 2026,
  publisher    = {Zenodo},
  doi          = {10.5281/zenodo.20323294},
  url          = {https://doi.org/10.5281/zenodo.20323294},
  orcid        = {0009-0001-4944-5567},
  version      = {0.1.1}
}
```

Primary references:

- **AWSEM**: Davtyan, A. et al. (2012) *AWSEM-MD: protein structure prediction using coarse-grained physical potentials and bioinformatically based local structure biasing.* J. Phys. Chem. B 116, 8494-8503. doi:10.1021/jp212541y
- **Frustration index**: Ferreiro, D. U. et al. (2007) *Localizing frustration in native proteins and protein assemblies.* PNAS 104, 19819-19824. doi:10.1073/pnas.0709915104
- **frustratometeR**: Rausch, A. O. et al. (2021) *FrustratometeR: an R-package to compute local frustration in protein structures, point mutants and MD simulations.* Bioinformatics 37, 3038-3040. doi:10.1093/bioinformatics/btab176
- **Frustratometer 2 server**: Parra, R. G. et al. (2016) *Protein Frustratometer 2: a tool to localize energetic frustration in protein molecules, now with electrostatics.* Nucleic Acids Res. 44, W356-W360. doi:10.1093/nar/gkw304
- **LAMMPS engine**: Thompson, A. P. et al. (2022) *LAMMPS: a flexible simulation tool for particle-based materials modeling.* Comp. Phys. Comm. 271, 108171. doi:10.1016/j.cpc.2021.108171
- **PyTorch**: Paszke, A. et al. (2019) *PyTorch: An Imperative Style, High-Performance Deep Learning Library.* NeurIPS 32, 8024-8035.
- **Biopython**: Cock, P. J. A. et al. (2009) *Biopython: freely available Python tools for computational molecular biology and bioinformatics.* Bioinformatics 25, 1422-1423. doi:10.1093/bioinformatics/btp163

## License

Apache License 2.0, see [LICENSE](LICENSE) and [NOTICE](NOTICE). The upstream AWSEM-MD and frustratometeR projects use GPL / academic-use licenses; we re-implement the algorithms from published specifications rather than redistributing their source.
