Python API Reference
Comprehensive documentation for the zsasa Python bindings.
Looking for the auto-generated API reference? See the Python Autodoc (pdoc).
Overview#
The Python bindings provide:
- NumPy integration: Pass coordinates and radii as NumPy arrays
- Two algorithms: Shrake-Rupley (fast) and Lee-Richards (precise)
- Multi-threading: Automatic parallelization across CPU cores
- Atom classification: CCD (default), static PROTOR, NACCESS, and OONS classifiers
- RSA calculation: Relative Solvent Accessibility
- Per-residue aggregation: Aggregate atom SASA to residue level
- Directory batch processing: Process entire directories of structure files
- Library integrations: gemmi, BioPython, Biotite, MDTraj, MDAnalysis (see Integrations)
- Trajectory-file guidance: use pyztraj for direct Python trajectory I/O and trajectory-native analysis;
zsasa.xtcandzsasa.dcdare retained for legacy compatibility
Contents#
| Document | Description |
|---|---|
| Core API | calculate_sasa, batch API, directory processing |
| Classifier | Atom classification, RSA calculation |
| Analysis | Per-residue aggregation, examples |
| Legacy Native XTC Reader | Compatibility XTC and DCD readers and trajectory SASA functions (zsasa.xtc, zsasa.dcd); prefer pyztraj for new trajectory-file workflows |
For structure file parsing and MD trajectory integrations, see Integrations.
Installation#
From PyPI (Recommended)#
pip install zsasa
# or
uv add zsasaPre-built wheels are available for Linux (x86_64, aarch64), macOS (x86_64, arm64), and Windows (x86_64). Python 3.11-3.13 supported.
From Source (Development)#
Requires Zig 0.16.0+.
cd zsasa/python
pip install -e .
# or
uv pip install -e .Optional Dependencies#
# For structure file support
pip install zsasa[gemmi] # gemmi (fast mmCIF/PDB)
pip install zsasa[biopython] # BioPython
pip install zsasa[biotite] # Biotite (also works with AtomWorks)
# For MD trajectory analysis
pip install mdtraj # MDTraj integration
pip install MDAnalysis # MDAnalysis integration
pip install pyztraj # Direct trajectory-file I/O (XTC/TRR/DCD/NC)
# All integrations
pip install zsasa[all]
# With uv
uv add zsasa[gemmi] # or any extra aboveHow the Native Library Is Found#
The package is a thin layer over the libzsasa shared library (libzsasa.so, libzsasa.dylib or zsasa.dll). A wheel from PyPI contains the library, so there is nothing to configure. The library is looked for in this order, and the first one found is loaded:
- The file named by the
ZSASA_LIBenvironment variable. - The package directory (the copy bundled in a wheel), and in a source checkout
zig-out/lib(zig-out/binon Windows). When a checkout has both and they differ, the newer one is loaded and a warning names the other. - The environment of the running interpreter:
<sys.prefix>/lib, on Windows<sys.prefix>\Library\bin, then the same directory undersys.base_prefix(a virtual environment created on top of such an environment). This is where a package manager that ships the library on its own, such as conda, installs it. /usr/local/liband/usr/lib.
The current directory is never searched. Whatever is found must have the C ABI version this version of the package was written for; otherwise loading fails with an ImportError that names the file.
python -m zsasa and the zsasa console script run the native zsasa binary: the one bundled in the wheel, or else <sys.prefix>/bin/zsasa (Windows: <sys.prefix>\Library\bin\zsasa.exe), then the same under sys.base_prefix. A script at that path is never run, because in an installation without a bundled binary it is the console script itself.
Packaging Without Bundled Binaries#
For a package manager that ships libzsasa and the zsasa binary as packages of their own, build the wheel with ZSASA_NO_BUNDLE=1:
ZSASA_NO_BUNDLE=1 python -m pip wheel --no-deps ./pythonNothing is compiled or bundled, Zig is not needed, and the wheel is pure Python (zsasa-<version>-py3-none-any.whl). Installed next to the library and the binary (steps 3 and 4 above), it behaves like the wheel from PyPI. Two things to take care of:
- Install the library of the same zsasa version: the package checks the ABI version of the library, and it calls functions that an older library does not have.
- The wheel still declares the
zsasaconsole script. On Linux and macOSpipwrites it to<prefix>/bin/zsasa, the path of the native binary in such an environment, so install the native binary after the wheel or leave the console script out of the package. If the script stays,zsasareports that no native binary was found instead of running one.
Quick Start#
Basic SASA Calculation#
import numpy as np
from zsasa import calculate_sasa
# Define atom coordinates (N, 3) and radii (N,)
coords = np.array([
[0.0, 0.0, 0.0],
[3.0, 0.0, 0.0],
])
radii = np.array([1.5, 1.5])
# Calculate SASA
result = calculate_sasa(coords, radii)
print(f"Total: {result.total_area:.2f} Ų")
print(f"Per-atom: {result.atom_areas}")From Structure Files (Recommended)#
# With gemmi (pip install zsasa[gemmi])
from zsasa.integrations.gemmi import calculate_sasa_from_structure
result = calculate_sasa_from_structure("protein.cif")
print(f"Total: {result.total_area:.1f} Ų")
print(f"Polar: {result.polar_area:.1f} Ų")
print(f"Apolar: {result.apolar_area:.1f} Ų")Per-Residue Analysis with RSA#
from zsasa.integrations.gemmi import calculate_sasa_from_structure
from zsasa import aggregate_from_result
result = calculate_sasa_from_structure("protein.cif")
residues = aggregate_from_result(result)
for res in residues:
rsa_str = f"{res.rsa:.1%}" if res.rsa is not None else "N/A"
print(f"{res.chain_id}:{res.residue_name}{res.residue_id}: RSA={rsa_str}")Directory Batch Processing#
from zsasa import process_directory
result = process_directory("path/to/structures/")
print(f"Processed {result.successful}/{result.total_files} files")
for i in range(result.total_files):
if result.status[i] == 1:
print(f" {result.filenames[i]}: SASA={result.total_sasa[i]:.1f} Ų")MD Trajectory Analysis#
import MDAnalysis as mda
from zsasa.mdanalysis import SASAAnalysis
u = mda.Universe("topology.pdb", "trajectory.xtc")
sasa = SASAAnalysis(u, select="protein")
sasa.run()
print(f"Mean SASA: {sasa.results.mean_total_area:.2f} Ų")Error Handling#
Common Exceptions#
| Exception | Cause |
|---|---|
ValueError |
Invalid input (shape mismatch, negative radii) |
FileNotFoundError |
Structure file not found |
IndexError |
Invalid model index |
ImportError |
Missing optional dependency (gemmi, biopython, biotite) |
MemoryError |
Out of memory during calculation |
RuntimeError |
Calculation error |
Utility Functions#
get_version#
def get_version() -> strReturns the library version string.
from zsasa import get_version
print(get_version()) # e.g., "0.9.1"Generate Autodoc Locally#
You can generate the full API reference locally using pdoc:
cd python
uv run pdoc zsasa --output-dir /tmp/python-autodoc
# Open /tmp/python-autodoc/zsasa.html in browserOr serve with live reload:
cd python
uv run pdoc zsasa
# Opens http://localhost:8080 automatically