diff --git a/CHANGELOG.md b/CHANGELOG.md index 843d301..a006f31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- Added `remove-lipids` (`remove_cavity_lipids`) to detect and remove lipids + packed inside a protein cavity (e.g. a beta barrel interior), ported from + the standalone MemGen `remove_cavity_lipids.py` script. Lipid residues are + recognized from a bundled `lipid_fragments.json`, optionally overridden + with `--lipid-fragments-json`. + ## 0.2.0 - 2026-07-29 - Added configurable cap inversion through the Python API and command-line interface. diff --git a/README.md b/README.md index e815d2e..097d5bd 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # MolPACD **MolPACD** is the **Molecular Pore Aperture Cap Designer**. It designs, adds, -analyzes, and removes molecular aperture caps in protein structures. +analyzes, and removes molecular aperture caps in protein structures, and +removes lipids packed inside protein cavities. The first implementation is derived from the MemGen beta-barrel water-cap script, but generalizes the workflow for PDB and mmCIF structures with configurable axes, @@ -91,6 +92,13 @@ non-cap atoms are not removed accidentally. If metadata is absent, or if you override metadata values such as residue name, chain, or atom name, removal requires `--force`. +Remove lipids packed inside a protein cavity (e.g. by packmol-memgen inside a +beta barrel interior): + +```bash +molpacd remove-lipids packed.pdb -o cleaned.pdb +``` + ## Format Notes MolPACD reads PDB and mmCIF files and writes minimal PDB/mmCIF outputs focused diff --git a/docs/advanced-api.md b/docs/advanced-api.md index 4a02199..5976f0d 100644 --- a/docs/advanced-api.md +++ b/docs/advanced-api.md @@ -7,6 +7,14 @@ import-root API. ::: molpacd.capper +## Cavity Lipid Removal + +::: molpacd.cavity_lipids + +## Lipid Names + +::: molpacd.lipids + ## Data Models ::: molpacd.models diff --git a/docs/cli.md b/docs/cli.md index 3e2aaf1..5025c76 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -79,3 +79,33 @@ Additional options: - `--force`: allow removal by residue/chain/atom match when metadata is absent or overridden. - `--json`: write machine-readable JSON. + +## Remove Cavity Lipids + +Remove lipids that packing tools (such as packmol-memgen) placed inside a +protein cavity, e.g. the interior of a beta barrel, instead of only in the +surrounding bilayer. + +```bash +molpacd remove-lipids packed.pdb -o cleaned.pdb +molpacd remove-lipids packed.pdb -o cleaned.pdb --cavity-radius 8.0 --margin 2.0 --json +``` + +The cavity is estimated from the protein's CA atoms (falling back to all +protein atoms if none are found): a principal axis and center from PCA, and +an inner radius from the average backbone radius. Lipid residues (grouped by +chain and residue number, since a lipid is often stored as separate head/tail +fragment residues) whose center of mass falls inside that cavity, plus +`--margin`, are removed. + +Lipid residue names are recognized from a bundled `lipid_fragments.json` +mapping full lipid names (e.g. `POPC`) to their head/tail fragment residue +names (e.g. `OL`, `PA`, `PC`). Additional options: + +- `--cavity-radius`: override the automatically estimated inner radius, in + Angstrom. +- `--margin`: additional margin added around the estimated cavity boundary + (default: 2.0 Angstrom). +- `--lipid-fragments-json`: path to a `lipid_fragments.json` file overriding + the bundled lipid fragment list. +- `--json`: write machine-readable JSON. diff --git a/docs/examples.md b/docs/examples.md index d98d0d6..7dbd5f1 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -28,3 +28,16 @@ molpacd remove capped.pdb -o decapped.pdb --json Removal uses MolPACD metadata when present. If metadata is absent, or if you intentionally override metadata values, pass `--force` with explicit matching criteria. + +## Remove Lipids Packed Inside A Cavity + +```bash +molpacd remove-lipids packed.pdb -o cleaned.pdb --json +``` + +Override the estimated cavity radius or margin when the automatic estimate +needs adjustment: + +```bash +molpacd remove-lipids packed.pdb -o cleaned.pdb --cavity-radius 8.0 --margin 3.0 +``` diff --git a/docs/index.md b/docs/index.md index b80e0a4..b3af72e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -2,8 +2,8 @@ **MolPACD** is the **Molecular Pore Aperture Cap Designer**. It provides a Python API and command line interface for analyzing pore openings, adding -molecular aperture caps, and removing MolPACD-generated caps from protein -structure files. +molecular aperture caps, removing MolPACD-generated caps, and removing lipids +packed inside protein cavities, from protein structure files. MolPACD works with PDB and mmCIF inputs and writes minimal PDB/mmCIF outputs focused on atom records plus MolPACD provenance metadata. @@ -38,7 +38,8 @@ make docs-serve ## Start Here - Follow the [Quick Start](quickstart.md) for common CLI and Python examples. -- Use the [Command Line](cli.md) reference for `analyze`, `add`, and `remove`. +- Use the [Command Line](cli.md) reference for `analyze`, `add`, `remove`, and + `remove-lipids`. - Browse the [Basic API](api.md) for the import-root interface. - Use the [Advanced API](advanced-api.md) for module-level details. diff --git a/docs/quickstart.md b/docs/quickstart.md index eacd60b..2245e90 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -68,6 +68,15 @@ requires `--force`. molpacd remove capped.pdb -o decapped.pdb --resname DUM --chain Z --force ``` +## Remove Cavity Lipids + +```bash +molpacd remove-lipids packed.pdb -o cleaned.pdb --json +``` + +The cavity is estimated from the protein's CA atoms; override it with +`--cavity-radius` and `--margin` if needed. + ## Python API ```python diff --git a/pyproject.toml b/pyproject.toml index e175f48..915badb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,7 +67,7 @@ Issues = "https://github.com/BlankenbergLab/molpacd/issues" where = ["src"] [tool.setuptools.package-data] -molpacd = ["py.typed"] +molpacd = ["py.typed", "data/lipid_fragments.json"] [tool.pytest.ini_options] addopts = "-ra" diff --git a/src/molpacd/__init__.py b/src/molpacd/__init__.py index b93e21d..88c2ea6 100644 --- a/src/molpacd/__init__.py +++ b/src/molpacd/__init__.py @@ -2,18 +2,31 @@ from molpacd._version import __version__ from molpacd.capper import add_caps, analyze_structure, remove_caps +from molpacd.cavity_lipids import remove_cavity_lipids +from molpacd.cavity_lipids_pdb import remove_cavity_lipids_pdb from molpacd.io import read_structure, write_structure -from molpacd.models import AnalysisResult, CapOptions, CapResult, RemoveResult +from molpacd.models import ( + AnalysisResult, + CapOptions, + CapResult, + CavityLipidOptions, + CavityLipidResult, + RemoveResult, +) __all__ = [ "AnalysisResult", "CapOptions", "CapResult", + "CavityLipidOptions", + "CavityLipidResult", "RemoveResult", "__version__", "add_caps", "analyze_structure", "read_structure", "remove_caps", + "remove_cavity_lipids", + "remove_cavity_lipids_pdb", "write_structure", ] diff --git a/src/molpacd/cavity_lipids.py b/src/molpacd/cavity_lipids.py new file mode 100644 index 0000000..4684529 --- /dev/null +++ b/src/molpacd/cavity_lipids.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +from typing import Optional, Tuple + +import numpy as np + +from molpacd.geometry import ( + barrel_radii, + coord_tuple, + coords_from_atoms, + point_inside_cylinder, + principal_axis_pca, +) +from molpacd.lipids import classify_lipid_atoms, load_lipid_residue_names +from molpacd.models import ( + CavityLipidOptions, + CavityLipidResult, + StructureData, + validate_cavity_lipid_options, +) + + +def remove_cavity_lipids( + structure: StructureData, + options: Optional[CavityLipidOptions] = None, +) -> Tuple[StructureData, CavityLipidResult]: + """Remove lipids packed inside a protein cavity (e.g. a beta barrel). + + Packmol-memgen can pack lipid tails into a protein's interior cavity + instead of only around its exterior. This estimates the cavity from the + protein's CA atoms and removes lipid residues whose center of mass falls + inside it, leaving lipids in the surrounding bilayer untouched. + + This operates on an already-parsed `StructureData` (PDB or mmCIF, via + `molpacd.io.read_structure`), so writing the result back out goes through + molpacd's generic structure writer and does not reproduce the exact + formatting of the original input file. To preserve a PDB file's original + formatting exactly, use `remove_cavity_lipids_pdb` instead. + """ + options = options or CavityLipidOptions() + validate_cavity_lipid_options(options) + _ensure_single_model(structure) + + lipid_residue_names = load_lipid_residue_names(options.lipid_fragments_json) + protein_atoms, lipid_residues, _other_atoms = classify_lipid_atoms( + structure.atoms, lipid_residue_names + ) + if not protein_atoms: + raise ValueError("no protein atoms found; cannot determine a cavity") + + ca_atoms = [atom for atom in protein_atoms if atom.name.strip().upper() == "CA"] + axis_atoms = ca_atoms if ca_atoms else protein_atoms + axis_coords = coords_from_atoms(axis_atoms) + + center, axis = principal_axis_pca(axis_coords) + inner_radius, outer_radius, z_min, z_max = barrel_radii(axis_coords, center, axis) + if options.cavity_radius is not None: + inner_radius = options.cavity_radius + + removed_keys = { + key + for key, atoms in lipid_residues.items() + if point_inside_cylinder( + np.mean(coords_from_atoms(atoms), axis=0), + center, + axis, + inner_radius, + z_min, + z_max, + options.margin, + ) + } + + kept_atoms = [ + atom + for atom in structure.atoms + if not ( + atom.resname.strip().upper() in lipid_residue_names + and (atom.chain_id, atom.res_seq) in removed_keys + ) + ] + + result = CavityLipidResult( + total_lipid_residues=len(lipid_residues), + removed_lipid_residues=len(removed_keys), + kept_lipid_residues=len(lipid_residues) - len(removed_keys), + center=coord_tuple(center), + axis=coord_tuple(axis), + inner_radius=float(inner_radius), + outer_radius=float(outer_radius), + z_min=float(z_min), + z_max=float(z_max), + margin=options.margin, + ) + cleaned = structure.with_atoms(kept_atoms) + return cleaned, result + + +def _ensure_single_model(structure: StructureData) -> None: + model_ids = structure.model_ids() + if len(model_ids) > 1: + raise ValueError( + "multi-model structures are not supported for cavity lipid removal; " + "split the structure into a single model first" + ) + + +__all__ = ["remove_cavity_lipids"] diff --git a/src/molpacd/cavity_lipids_pdb.py b/src/molpacd/cavity_lipids_pdb.py new file mode 100644 index 0000000..c1dc1b1 --- /dev/null +++ b/src/molpacd/cavity_lipids_pdb.py @@ -0,0 +1,209 @@ +from __future__ import annotations + +import contextlib +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from tempfile import NamedTemporaryFile +from typing import Dict, List, Optional, Sequence, Set, Tuple, Union + +import numpy as np +from numpy.typing import NDArray + +from molpacd.geometry import barrel_radii, point_inside_cylinder, principal_axis_pca +from molpacd.lipids import AMINO_ACID_RESIDUE_NAMES, load_lipid_residue_names +from molpacd.models import CavityLipidOptions, CavityLipidResult, validate_cavity_lipid_options + +_PDB_EXTENSIONS = {".pdb", ".ent"} + + +@dataclass(frozen=True) +class _RawAtom: + line_index: int + model: int + name: str + resname: str + chain_id: str + res_seq: int + x: float + y: float + z: float + + +def remove_cavity_lipids_pdb( + input_path: Union[str, Path], + output_path: Union[str, Path], + options: Optional[CavityLipidOptions] = None, +) -> CavityLipidResult: + """Remove cavity lipids from a PDB file, preserving its original formatting. + + Unlike `molpacd.cavity_lipids.remove_cavity_lipids`, this reads and + writes raw PDB text directly instead of going through molpacd's + Biopython-based structure I/O. Every line that is not part of a removed + lipid residue is copied through byte-for-byte from the input file, so + column widths, TER records, segment IDs, and any other fields molpacd's + generic writer does not reproduce are preserved exactly. This also + avoids residue-numbering edge cases in large multi-chain packmol-memgen + output where Biopython's structure builder can silently drop atoms. + """ + options = options or CavityLipidOptions() + validate_cavity_lipid_options(options) + + input_path = Path(input_path) + output_path = Path(output_path) + if input_path.suffix.lower() not in _PDB_EXTENSIONS: + raise ValueError(f"unsupported input format for {input_path}; expected a PDB file") + if output_path.suffix.lower() not in _PDB_EXTENSIONS: + raise ValueError(f"unsupported output format for {output_path}; expected a PDB file") + + lines = input_path.read_text().splitlines(keepends=True) + atoms = _parse_pdb_atoms(lines) + if not atoms: + raise ValueError(f"no ATOM/HETATM records found in {input_path}") + if len({atom.model for atom in atoms}) > 1: + raise ValueError( + "multi-model structures are not supported for cavity lipid removal; " + "split the structure into a single model first" + ) + + lipid_residue_names = load_lipid_residue_names(options.lipid_fragments_json) + protein_atoms, lipid_residues = _classify_raw_atoms(atoms, lipid_residue_names) + if not protein_atoms: + raise ValueError("no protein atoms found; cannot determine a cavity") + + ca_atoms = [atom for atom in protein_atoms if atom.name.strip().upper() == "CA"] + axis_atoms = ca_atoms if ca_atoms else protein_atoms + axis_coords = _coords(axis_atoms) + + center, axis = principal_axis_pca(axis_coords) + inner_radius, outer_radius, z_min, z_max = barrel_radii(axis_coords, center, axis) + if options.cavity_radius is not None: + inner_radius = options.cavity_radius + + removed_keys: Set[Tuple[str, int]] = set() + removed_line_indices: Set[int] = set() + for key, residue_atoms in lipid_residues.items(): + residue_center = np.mean(_coords(residue_atoms), axis=0) + if point_inside_cylinder( + residue_center, center, axis, inner_radius, z_min, z_max, options.margin + ): + removed_keys.add(key) + removed_line_indices.update(atom.line_index for atom in residue_atoms) + + result = CavityLipidResult( + total_lipid_residues=len(lipid_residues), + removed_lipid_residues=len(removed_keys), + kept_lipid_residues=len(lipid_residues) - len(removed_keys), + center=(float(center[0]), float(center[1]), float(center[2])), + axis=(float(axis[0]), float(axis[1]), float(axis[2])), + inner_radius=float(inner_radius), + outer_radius=float(outer_radius), + z_min=float(z_min), + z_max=float(z_max), + margin=options.margin, + ) + _write_pdb(lines, removed_line_indices, result, output_path) + return result + + +def _parse_pdb_atoms(lines: Sequence[str]) -> List[_RawAtom]: + atoms: List[_RawAtom] = [] + model = 1 + for index, line in enumerate(lines): + if line.startswith("MODEL"): + with contextlib.suppress(ValueError): + model = int(line[10:14]) + continue + if not line.startswith(("ATOM", "HETATM")): + continue + try: + name = line[12:16].strip() + resname = line[17:20].strip() + chain_id = line[21].strip() or " " + res_seq = int(line[22:26]) + x = float(line[30:38]) + y = float(line[38:46]) + z = float(line[46:54]) + except (ValueError, IndexError) as exc: + raise ValueError( + f"malformed PDB ATOM/HETATM record at line {index + 1}: {line!r}" + ) from exc + atoms.append( + _RawAtom( + line_index=index, + model=model, + name=name, + resname=resname, + chain_id=chain_id, + res_seq=res_seq, + x=x, + y=y, + z=z, + ) + ) + return atoms + + +def _classify_raw_atoms( + atoms: Sequence[_RawAtom], lipid_residue_names: Set[str] +) -> Tuple[List[_RawAtom], Dict[Tuple[str, int], List[_RawAtom]]]: + protein_atoms: List[_RawAtom] = [] + lipid_residues: Dict[Tuple[str, int], List[_RawAtom]] = defaultdict(list) + for atom in atoms: + resname = atom.resname.strip().upper() + if resname in AMINO_ACID_RESIDUE_NAMES: + protein_atoms.append(atom) + elif resname in lipid_residue_names: + lipid_residues[(atom.chain_id, atom.res_seq)].append(atom) + return protein_atoms, dict(lipid_residues) + + +def _coords(atoms: Sequence[_RawAtom]) -> NDArray[np.float64]: + return np.array([[atom.x, atom.y, atom.z] for atom in atoms], dtype=float) + + +def _write_pdb( + lines: Sequence[str], + removed_line_indices: Set[int], + result: CavityLipidResult, + output_path: Path, +) -> None: + remark_lines = [ + "REMARK Processed by molpacd remove-lipids\n", + f"REMARK Removed {result.removed_lipid_residues} of " + f"{result.total_lipid_residues} lipid residues from the cavity\n", + ] + output_lines: List[str] = [] + inserted = False + for index, line in enumerate(lines): + # `atoms` is guaranteed non-empty by the caller, so some line here + # always starts with ATOM/HETATM/MODEL and this always fires once. + if not inserted and line.startswith(("ATOM", "HETATM", "MODEL")): + output_lines.extend(remark_lines) + inserted = True + if index in removed_line_indices: + continue + output_lines.append(line) + _write_text_atomic(output_path, "".join(output_lines)) + + +def _write_text_atomic(path: Path, text: str) -> None: + temp_path: Optional[Path] = None + try: + with NamedTemporaryFile( + "w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + delete=False, + ) as handle: + temp_path = Path(handle.name) + handle.write(text) + temp_path.replace(path) + finally: + if temp_path is not None and temp_path.exists(): + temp_path.unlink() + + +__all__ = ["remove_cavity_lipids_pdb"] diff --git a/src/molpacd/cli.py b/src/molpacd/cli.py index 38e7e1e..ea80568 100644 --- a/src/molpacd/cli.py +++ b/src/molpacd/cli.py @@ -9,8 +9,9 @@ from molpacd._version import __version__ from molpacd.capper import add_caps, analyze_structure, remove_caps +from molpacd.cavity_lipids_pdb import remove_cavity_lipids_pdb from molpacd.io import read_structure, write_structure -from molpacd.models import AnalysisResult, CapOptions, CapResult +from molpacd.models import AnalysisResult, CapOptions, CapResult, CavityLipidOptions def main(argv: Optional[Sequence[str]] = None) -> int: @@ -87,6 +88,34 @@ def build_parser() -> argparse.ArgumentParser: ) remove.add_argument("--json", action="store_true", help="write machine-readable JSON") remove.set_defaults(func=_cmd_remove) + + remove_lipids = subparsers.add_parser( + "remove-lipids", help="remove lipids packed inside a protein cavity" + ) + remove_lipids.add_argument("input", type=Path) + remove_lipids.add_argument("-o", "--output", type=Path, required=True) + remove_lipids.add_argument( + "--cavity-radius", + "-r", + type=float, + default=None, + help="override automatic cavity radius detection (in Angstrom)", + ) + remove_lipids.add_argument( + "--margin", + "-m", + type=float, + default=2.0, + help="additional margin around the cavity (default: 2.0 Angstrom)", + ) + remove_lipids.add_argument( + "--lipid-fragments-json", + type=Path, + default=None, + help="path to a lipid_fragments.json overriding the bundled lipid fragment list", + ) + remove_lipids.add_argument("--json", action="store_true", help="write machine-readable JSON") + remove_lipids.set_defaults(func=_cmd_remove_lipids) return parser @@ -206,6 +235,29 @@ def _cmd_remove(args: argparse.Namespace) -> int: return 0 +def _cmd_remove_lipids(args: argparse.Namespace) -> int: + options = CavityLipidOptions( + cavity_radius=args.cavity_radius, + margin=args.margin, + lipid_fragments_json=str(args.lipid_fragments_json) if args.lipid_fragments_json else None, + ) + result = remove_cavity_lipids_pdb(args.input, args.output, options) + payload = asdict(result) + payload["output"] = str(args.output) + payload["wrote"] = str(args.output) + + if args.json: + print(json.dumps(payload, indent=2, sort_keys=True)) + return 0 + + print( + f"removed {result.removed_lipid_residues} of {result.total_lipid_residues} " + f"lipid residues from the cavity (kept {result.kept_lipid_residues})" + ) + print(f"wrote {args.output}") + return 0 + + def _print_analysis(analysis: AnalysisResult) -> None: print(f"axis: {_format_vector(analysis.axis)}") print(f"center: {_format_vector(analysis.center)}") diff --git a/src/molpacd/data/lipid_fragments.json b/src/molpacd/data/lipid_fragments.json new file mode 100644 index 0000000..67fae18 --- /dev/null +++ b/src/molpacd/data/lipid_fragments.json @@ -0,0 +1,1255 @@ +{ + "AHPA": [ + "AR", + "DHA", + "PH-" + ], + "AHPC": [ + "AR", + "DHA", + "PC" + ], + "AHPE": [ + "AR", + "DHA", + "PE" + ], + "AHPG": [ + "AR", + "DHA", + "PGR" + ], + "AHPS": [ + "AR", + "DHA", + "PS" + ], + "ALPA": [ + "AR", + "LAL", + "PH-" + ], + "ALPC": [ + "AR", + "LAL", + "PC" + ], + "ALPE": [ + "AR", + "LAL", + "PE" + ], + "ALPG": [ + "AR", + "LAL", + "PGR" + ], + "ALPS": [ + "AR", + "LAL", + "PS" + ], + "AMPA": [ + "AR", + "MY", + "PH-" + ], + "AMPC": [ + "AR", + "MY", + "PC" + ], + "AMPE": [ + "AR", + "MY", + "PE" + ], + "AMPG": [ + "AR", + "MY", + "PGR" + ], + "AMPS": [ + "AR", + "MY", + "PS" + ], + "AOPA": [ + "AR", + "OL", + "PH-" + ], + "AOPC": [ + "AR", + "OL", + "PC" + ], + "AOPE": [ + "AR", + "OL", + "PE" + ], + "AOPG": [ + "AR", + "OL", + "PGR" + ], + "AOPS": [ + "AR", + "OL", + "PS" + ], + "APPA": [ + "AR", + "PA", + "PH-" + ], + "APPC": [ + "AR", + "PA", + "PC" + ], + "APPE": [ + "AR", + "PA", + "PE" + ], + "APPG": [ + "AR", + "PA", + "PGR" + ], + "APPS": [ + "AR", + "PA", + "PS" + ], + "ASM": [ + "AR", + "SA", + "SPM" + ], + "ASPA": [ + "AR", + "PH-", + "ST" + ], + "ASPC": [ + "AR", + "PC", + "ST" + ], + "ASPE": [ + "AR", + "PE", + "ST" + ], + "ASPG": [ + "AR", + "PGR", + "ST" + ], + "ASPS": [ + "AR", + "PS", + "ST" + ], + "CHL1": [ + "CHL" + ], + "DAPA": [ + "AR", + "PH-" + ], + "DAPC": [ + "AR", + "PC" + ], + "DAPE": [ + "AR", + "PE" + ], + "DAPG": [ + "AR", + "PGR" + ], + "DAPS": [ + "AR", + "PS" + ], + "DHPA": [ + "DHA", + "PH-" + ], + "DHPC": [ + "DHA", + "PC" + ], + "DHPE": [ + "DHA", + "PE" + ], + "DHPG": [ + "DHA", + "PGR" + ], + "DHPS": [ + "DHA", + "PS" + ], + "DLPA": [ + "LAL", + "PH-" + ], + "DLPC": [ + "LAL", + "PC" + ], + "DLPE": [ + "LAL", + "PE" + ], + "DLPG": [ + "LAL", + "PGR" + ], + "DLPS": [ + "LAL", + "PS" + ], + "DMPA": [ + "MY", + "PH-" + ], + "DMPC": [ + "MY", + "PC" + ], + "DMPE": [ + "MY", + "PE" + ], + "DMPG": [ + "MY", + "PGR" + ], + "DMPS": [ + "MY", + "PS" + ], + "DOPA": [ + "OL", + "PH-" + ], + "DOPC": [ + "OL", + "PC" + ], + "DOPE": [ + "OL", + "PE" + ], + "DOPG": [ + "OL", + "PGR" + ], + "DOPS": [ + "OL", + "PS" + ], + "DPPA": [ + "PA", + "PH-" + ], + "DPPC": [ + "PA", + "PC" + ], + "DPPE": [ + "PA", + "PE" + ], + "DPPG": [ + "PA", + "PGR" + ], + "DPPS": [ + "PA", + "PS" + ], + "DSPA": [ + "PH-", + "ST" + ], + "DSPC": [ + "PC", + "ST" + ], + "DSPE": [ + "PE", + "ST" + ], + "DSPG": [ + "PGR", + "ST" + ], + "DSPS": [ + "PS", + "ST" + ], + "HAPA": [ + "AR", + "DHA", + "PH-" + ], + "HAPC": [ + "AR", + "DHA", + "PC" + ], + "HAPE": [ + "AR", + "DHA", + "PE" + ], + "HAPG": [ + "AR", + "DHA", + "PGR" + ], + "HAPS": [ + "AR", + "DHA", + "PS" + ], + "HLPA": [ + "DHA", + "LAL", + "PH-" + ], + "HLPC": [ + "DHA", + "LAL", + "PC" + ], + "HLPE": [ + "DHA", + "LAL", + "PE" + ], + "HLPG": [ + "DHA", + "LAL", + "PGR" + ], + "HLPS": [ + "DHA", + "LAL", + "PS" + ], + "HMPA": [ + "DHA", + "MY", + "PH-" + ], + "HMPC": [ + "DHA", + "MY", + "PC" + ], + "HMPE": [ + "DHA", + "MY", + "PE" + ], + "HMPG": [ + "DHA", + "MY", + "PGR" + ], + "HMPS": [ + "DHA", + "MY", + "PS" + ], + "HOPA": [ + "DHA", + "OL", + "PH-" + ], + "HOPC": [ + "DHA", + "OL", + "PC" + ], + "HOPE": [ + "DHA", + "OL", + "PE" + ], + "HOPG": [ + "DHA", + "OL", + "PGR" + ], + "HOPS": [ + "DHA", + "OL", + "PS" + ], + "HPPA": [ + "DHA", + "PA", + "PH-" + ], + "HPPC": [ + "DHA", + "PA", + "PC" + ], + "HPPE": [ + "DHA", + "PA", + "PE" + ], + "HPPG": [ + "DHA", + "PA", + "PGR" + ], + "HPPS": [ + "DHA", + "PA", + "PS" + ], + "HSM": [ + "DHA", + "SA", + "SPM" + ], + "HSPA": [ + "DHA", + "PH-", + "ST" + ], + "HSPC": [ + "DHA", + "PC", + "ST" + ], + "HSPE": [ + "DHA", + "PE", + "ST" + ], + "HSPG": [ + "DHA", + "PGR", + "ST" + ], + "HSPS": [ + "DHA", + "PS", + "ST" + ], + "LAPA": [ + "AR", + "LAL", + "PH-" + ], + "LAPC": [ + "AR", + "LAL", + "PC" + ], + "LAPE": [ + "AR", + "LAL", + "PE" + ], + "LAPG": [ + "AR", + "LAL", + "PGR" + ], + "LAPS": [ + "AR", + "LAL", + "PS" + ], + "LHPA": [ + "DHA", + "LAL", + "PH-" + ], + "LHPC": [ + "DHA", + "LAL", + "PC" + ], + "LHPE": [ + "DHA", + "LAL", + "PE" + ], + "LHPG": [ + "DHA", + "LAL", + "PGR" + ], + "LHPS": [ + "DHA", + "LAL", + "PS" + ], + "LMPA": [ + "LAL", + "MY", + "PH-" + ], + "LMPC": [ + "LAL", + "MY", + "PC" + ], + "LMPE": [ + "LAL", + "MY", + "PE" + ], + "LMPG": [ + "LAL", + "MY", + "PGR" + ], + "LMPS": [ + "LAL", + "MY", + "PS" + ], + "LOPA": [ + "LAL", + "OL", + "PH-" + ], + "LOPC": [ + "LAL", + "OL", + "PC" + ], + "LOPE": [ + "LAL", + "OL", + "PE" + ], + "LOPG": [ + "LAL", + "OL", + "PGR" + ], + "LOPS": [ + "LAL", + "OL", + "PS" + ], + "LPPA": [ + "LAL", + "PA", + "PH-" + ], + "LPPC": [ + "LAL", + "PA", + "PC" + ], + "LPPE": [ + "LAL", + "PA", + "PE" + ], + "LPPG": [ + "LAL", + "PA", + "PGR" + ], + "LPPS": [ + "LAL", + "PA", + "PS" + ], + "LSM": [ + "LAL", + "SA", + "SPM" + ], + "LSPA": [ + "LAL", + "PH-", + "ST" + ], + "LSPC": [ + "LAL", + "PC", + "ST" + ], + "LSPE": [ + "LAL", + "PE", + "ST" + ], + "LSPG": [ + "LAL", + "PGR", + "ST" + ], + "LSPS": [ + "LAL", + "PS", + "ST" + ], + "MAPA": [ + "AR", + "MY", + "PH-" + ], + "MAPC": [ + "AR", + "MY", + "PC" + ], + "MAPE": [ + "AR", + "MY", + "PE" + ], + "MAPG": [ + "AR", + "MY", + "PGR" + ], + "MAPS": [ + "AR", + "MY", + "PS" + ], + "MHPA": [ + "DHA", + "MY", + "PH-" + ], + "MHPC": [ + "DHA", + "MY", + "PC" + ], + "MHPE": [ + "DHA", + "MY", + "PE" + ], + "MHPG": [ + "DHA", + "MY", + "PGR" + ], + "MHPS": [ + "DHA", + "MY", + "PS" + ], + "MLPA": [ + "LAL", + "MY", + "PH-" + ], + "MLPC": [ + "LAL", + "MY", + "PC" + ], + "MLPE": [ + "LAL", + "MY", + "PE" + ], + "MLPG": [ + "LAL", + "MY", + "PGR" + ], + "MLPS": [ + "LAL", + "MY", + "PS" + ], + "MOPA": [ + "MY", + "OL", + "PH-" + ], + "MOPC": [ + "MY", + "OL", + "PC" + ], + "MOPE": [ + "MY", + "OL", + "PE" + ], + "MOPG": [ + "MY", + "OL", + "PGR" + ], + "MOPS": [ + "MY", + "OL", + "PS" + ], + "MPPA": [ + "MY", + "PA", + "PH-" + ], + "MPPC": [ + "MY", + "PA", + "PC" + ], + "MPPE": [ + "MY", + "PA", + "PE" + ], + "MPPG": [ + "MY", + "PA", + "PGR" + ], + "MPPS": [ + "MY", + "PA", + "PS" + ], + "MSM": [ + "MY", + "SA", + "SPM" + ], + "MSPA": [ + "MY", + "PH-", + "ST" + ], + "MSPC": [ + "MY", + "PC", + "ST" + ], + "MSPE": [ + "MY", + "PE", + "ST" + ], + "MSPG": [ + "MY", + "PGR", + "ST" + ], + "MSPS": [ + "MY", + "PS", + "ST" + ], + "OAPA": [ + "AR", + "OL", + "PH-" + ], + "OAPC": [ + "AR", + "OL", + "PC" + ], + "OAPE": [ + "AR", + "OL", + "PE" + ], + "OAPG": [ + "AR", + "OL", + "PGR" + ], + "OAPS": [ + "AR", + "OL", + "PS" + ], + "OHPA": [ + "DHA", + "OL", + "PH-" + ], + "OHPC": [ + "DHA", + "OL", + "PC" + ], + "OHPE": [ + "DHA", + "OL", + "PE" + ], + "OHPG": [ + "DHA", + "OL", + "PGR" + ], + "OHPS": [ + "DHA", + "OL", + "PS" + ], + "OLPA": [ + "LAL", + "OL", + "PH-" + ], + "OLPC": [ + "LAL", + "OL", + "PC" + ], + "OLPE": [ + "LAL", + "OL", + "PE" + ], + "OLPG": [ + "LAL", + "OL", + "PGR" + ], + "OLPS": [ + "LAL", + "OL", + "PS" + ], + "OMPA": [ + "MY", + "OL", + "PH-" + ], + "OMPC": [ + "MY", + "OL", + "PC" + ], + "OMPE": [ + "MY", + "OL", + "PE" + ], + "OMPG": [ + "MY", + "OL", + "PGR" + ], + "OMPS": [ + "MY", + "OL", + "PS" + ], + "OPPA": [ + "OL", + "PA", + "PH-" + ], + "OPPC": [ + "OL", + "PA", + "PC" + ], + "OPPE": [ + "OL", + "PA", + "PE" + ], + "OPPG": [ + "OL", + "PA", + "PGR" + ], + "OPPS": [ + "OL", + "PA", + "PS" + ], + "OSM": [ + "OL", + "SA", + "SPM" + ], + "OSPA": [ + "OL", + "PH-", + "ST" + ], + "OSPC": [ + "OL", + "PC", + "ST" + ], + "OSPE": [ + "OL", + "PE", + "ST" + ], + "OSPG": [ + "OL", + "PGR", + "ST" + ], + "OSPS": [ + "OL", + "PS", + "ST" + ], + "PAPA": [ + "AR", + "PA", + "PH-" + ], + "PAPC": [ + "PA", + "PC", + "AR" + ], + "PAPE": [ + "AR", + "PA", + "PE" + ], + "PAPG": [ + "PA", + "PGR", + "AR" + ], + "PAPS": [ + "AR", + "PA", + "PS" + ], + "PHPA": [ + "DHA", + "PA", + "PH-" + ], + "PHPC": [ + "DHA", + "PA", + "PC" + ], + "PHPE": [ + "DHA", + "PA", + "PE" + ], + "PHPG": [ + "DHA", + "PA", + "PGR" + ], + "PHPS": [ + "DHA", + "PA", + "PS" + ], + "PLPA": [ + "LAL", + "PA", + "PH-" + ], + "PLPC": [ + "LAL", + "PA", + "PC" + ], + "PLPE": [ + "LAL", + "PA", + "PE" + ], + "PLPG": [ + "LAL", + "PA", + "PGR" + ], + "PLPS": [ + "LAL", + "PA", + "PS" + ], + "PMPA": [ + "MY", + "PA", + "PH-" + ], + "PMPC": [ + "MY", + "PA", + "PC" + ], + "PMPE": [ + "MY", + "PA", + "PE" + ], + "PMPG": [ + "MY", + "PA", + "PGR" + ], + "PMPS": [ + "MY", + "PA", + "PS" + ], + "POPA": [ + "OL", + "PA", + "PH-" + ], + "POPC": [ + "PA", + "PC", + "OL" + ], + "POPE": [ + "OL", + "PA", + "PE" + ], + "POPG": [ + "OL", + "PA", + "PGR" + ], + "POPS": [ + "OL", + "PA", + "PS" + ], + "PSM": [ + "PA", + "SA", + "SPM" + ], + "PSPA": [ + "PA", + "PH-", + "ST" + ], + "PSPC": [ + "PA", + "PC", + "ST" + ], + "PSPE": [ + "PA", + "PE", + "ST" + ], + "PSPG": [ + "PA", + "PGR", + "ST" + ], + "PSPS": [ + "PA", + "PS", + "ST" + ], + "SAPA": [ + "AR", + "PH-", + "ST" + ], + "SAPC": [ + "AR", + "PC", + "ST" + ], + "SAPE": [ + "AR", + "PE", + "ST" + ], + "SAPG": [ + "AR", + "PGR", + "ST" + ], + "SAPS": [ + "AR", + "PS", + "ST" + ], + "SDPA": [ + "DHA", + "PH-", + "ST" + ], + "SDPC": [ + "DHA", + "PC", + "ST" + ], + "SDPE": [ + "DHA", + "PE", + "ST" + ], + "SDPG": [ + "DHA", + "PGR", + "ST" + ], + "SDPS": [ + "DHA", + "PS", + "ST" + ], + "SHPA": [ + "DHA", + "PH-", + "ST" + ], + "SHPC": [ + "DHA", + "PC", + "ST" + ], + "SHPE": [ + "DHA", + "PE", + "ST" + ], + "SHPG": [ + "DHA", + "PGR", + "ST" + ], + "SHPS": [ + "DHA", + "PS", + "ST" + ], + "SLPA": [ + "LAL", + "PH-", + "ST" + ], + "SLPC": [ + "LAL", + "PC", + "ST" + ], + "SLPE": [ + "LAL", + "PE", + "ST" + ], + "SLPG": [ + "LAL", + "PGR", + "ST" + ], + "SLPS": [ + "LAL", + "PS", + "ST" + ], + "SMPA": [ + "MY", + "PH-", + "ST" + ], + "SMPC": [ + "MY", + "PC", + "ST" + ], + "SMPE": [ + "MY", + "PE", + "ST" + ], + "SMPG": [ + "MY", + "PGR", + "ST" + ], + "SMPS": [ + "MY", + "PS", + "ST" + ], + "SOPA": [ + "OL", + "PH-", + "ST" + ], + "SOPC": [ + "OL", + "PC", + "ST" + ], + "SOPE": [ + "OL", + "PE", + "ST" + ], + "SOPG": [ + "OL", + "PGR", + "ST" + ], + "SOPS": [ + "OL", + "PS", + "ST" + ], + "SPPA": [ + "PA", + "PH-", + "ST" + ], + "SPPC": [ + "PA", + "PC", + "ST" + ], + "SPPE": [ + "PA", + "PE", + "ST" + ], + "SPPG": [ + "PA", + "PGR", + "ST" + ], + "SPPS": [ + "PA", + "PS", + "ST" + ], + "SSM": [ + "SA", + "SPM", + "ST" + ] +} diff --git a/src/molpacd/geometry.py b/src/molpacd/geometry.py index 21702cb..7c7b49c 100644 --- a/src/molpacd/geometry.py +++ b/src/molpacd/geometry.py @@ -132,7 +132,7 @@ def _opening_from_projection( return Opening( side="negative" if side == "negative" else "positive", atom_count=int(indices.size), - centroid=_coord_tuple(centroid), + centroid=coord_tuple(centroid), radius=radius, projection=projection, ) @@ -205,5 +205,63 @@ def filter_collisions( return np.array(kept, dtype=float), skipped -def _coord_tuple(values: NDArray[np.float64]) -> Tuple[float, float, float]: +def principal_axis_pca( + coords: NDArray[np.float64], +) -> Tuple[NDArray[np.float64], NDArray[np.float64]]: + """Center and PCA principal axis of a point cloud, oriented toward +z.""" + center = np.mean(coords, axis=0) + centered = coords - center + covariance = np.cov(centered, rowvar=False) + eigenvalues, eigenvectors = np.linalg.eigh(covariance) + axis = eigenvectors[:, int(np.argmax(eigenvalues))] + if axis[2] < 0: + axis = -axis + return center, normalize_vector(axis) + + +def barrel_radii( + coords: NDArray[np.float64], + center: NDArray[np.float64], + axis: NDArray[np.float64], +) -> Tuple[float, float, float, float]: + """Estimate a beta-barrel-like inner/outer radius and axial extent. + + Returns ``(inner_radius, outer_radius, z_min, z_max)`` relative to + ``center``/``axis``. The inner radius is approximated as 60% of the mean + radial distance, which is typical for beta barrel backbone geometry. + """ + relative = coords - center + projections = np.dot(relative, axis) + z_min = float(np.min(projections)) + z_max = float(np.max(projections)) + + axial = np.outer(projections, axis) + radial = relative - axial + distances = np.linalg.norm(radial, axis=1) + + inner_radius = float(np.mean(distances)) * 0.6 + outer_radius = float(np.max(distances)) + return inner_radius, outer_radius, z_min, z_max + + +def point_inside_cylinder( + point: NDArray[np.float64], + center: NDArray[np.float64], + axis: NDArray[np.float64], + inner_radius: float, + z_min: float, + z_max: float, + margin: float, +) -> bool: + """Whether `point` falls inside the axial cylinder defined by the other arguments.""" + relative = point - center + z_proj = float(np.dot(relative, axis)) + if z_proj < z_min - margin or z_proj > z_max + margin: + return False + radial = relative - z_proj * axis + radial_distance = float(np.linalg.norm(radial)) + return radial_distance < inner_radius + margin + + +def coord_tuple(values: NDArray[np.float64]) -> Tuple[float, float, float]: return (float(values[0]), float(values[1]), float(values[2])) diff --git a/src/molpacd/lipids.py b/src/molpacd/lipids.py new file mode 100644 index 0000000..f87df32 --- /dev/null +++ b/src/molpacd/lipids.py @@ -0,0 +1,402 @@ +from __future__ import annotations + +import json +from collections import defaultdict +from importlib import resources +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Set, Tuple, Union + +from molpacd.models import AtomRecord + +# Standard amino acid residue names, including common AMBER/CHARMM +# protonation-state variants, used to identify protein atoms. +AMINO_ACID_RESIDUE_NAMES: Set[str] = { + "ALA", + "ARG", + "ASN", + "ASP", + "CYS", + "GLN", + "GLU", + "GLY", + "HIS", + "ILE", + "LEU", + "LYS", + "MET", + "PHE", + "PRO", + "SER", + "THR", + "TRP", + "TYR", + "VAL", + "HID", + "HIE", + "HIP", + "HSD", + "HSE", + "HSP", # histidine protonation variants + "CYX", + "CYM", + "ASH", + "GLH", + "LYN", # other protonation/disulfide variants +} + +# Packmol-memgen (lipid21 / AMBER lipid builder) writes each lipid into the +# structure as separate head/tail *fragment* residues (e.g. POPC becomes +# "OL", "PA", "PC" residues), not as one residue named after the full lipid. +# These fallback sets mirror data/lipid_fragments.json and are merged with it +# so lipid detection keeps working even if that file cannot be read. +_FALLBACK_LIPID_FRAGMENT_CODES: Set[str] = { + "AR", + "CHL", + "DHA", + "LAL", + "MY", + "OL", + "PA", + "PC", + "PE", + "PGR", + "PH-", + "PS", + "SA", + "SPM", + "ST", +} + +_FALLBACK_FULL_LIPID_NAMES: Set[str] = { + "AHPA", + "AHPC", + "AHPE", + "AHPG", + "AHPS", + "ALPA", + "ALPC", + "ALPE", + "ALPG", + "ALPS", + "AMPA", + "AMPC", + "AMPE", + "AMPG", + "AMPS", + "AOPA", + "AOPC", + "AOPE", + "AOPG", + "AOPS", + "APPA", + "APPC", + "APPE", + "APPG", + "APPS", + "ASM", + "ASPA", + "ASPC", + "ASPE", + "ASPG", + "ASPS", + "CHL1", + "DAPA", + "DAPC", + "DAPE", + "DAPG", + "DAPS", + "DHPA", + "DHPC", + "DHPE", + "DHPG", + "DHPS", + "DLPA", + "DLPC", + "DLPE", + "DLPG", + "DLPS", + "DMPA", + "DMPC", + "DMPE", + "DMPG", + "DMPS", + "DOPA", + "DOPC", + "DOPE", + "DOPG", + "DOPS", + "DPPA", + "DPPC", + "DPPE", + "DPPG", + "DPPS", + "DSPA", + "DSPC", + "DSPE", + "DSPG", + "DSPS", + "HAPA", + "HAPC", + "HAPE", + "HAPG", + "HAPS", + "HLPA", + "HLPC", + "HLPE", + "HLPG", + "HLPS", + "HMPA", + "HMPC", + "HMPE", + "HMPG", + "HMPS", + "HOPA", + "HOPC", + "HOPE", + "HOPG", + "HOPS", + "HPPA", + "HPPC", + "HPPE", + "HPPG", + "HPPS", + "HSM", + "HSPA", + "HSPC", + "HSPE", + "HSPG", + "HSPS", + "LAPA", + "LAPC", + "LAPE", + "LAPG", + "LAPS", + "LHPA", + "LHPC", + "LHPE", + "LHPG", + "LHPS", + "LMPA", + "LMPC", + "LMPE", + "LMPG", + "LMPS", + "LOPA", + "LOPC", + "LOPE", + "LOPG", + "LOPS", + "LPPA", + "LPPC", + "LPPE", + "LPPG", + "LPPS", + "LSM", + "LSPA", + "LSPC", + "LSPE", + "LSPG", + "LSPS", + "MAPA", + "MAPC", + "MAPE", + "MAPG", + "MAPS", + "MHPA", + "MHPC", + "MHPE", + "MHPG", + "MHPS", + "MLPA", + "MLPC", + "MLPE", + "MLPG", + "MLPS", + "MOPA", + "MOPC", + "MOPE", + "MOPG", + "MOPS", + "MPPA", + "MPPC", + "MPPE", + "MPPG", + "MPPS", + "MSM", + "MSPA", + "MSPC", + "MSPE", + "MSPG", + "MSPS", + "OAPA", + "OAPC", + "OAPE", + "OAPG", + "OAPS", + "OHPA", + "OHPC", + "OHPE", + "OHPG", + "OHPS", + "OLPA", + "OLPC", + "OLPE", + "OLPG", + "OLPS", + "OMPA", + "OMPC", + "OMPE", + "OMPG", + "OMPS", + "OPPA", + "OPPC", + "OPPE", + "OPPG", + "OPPS", + "OSM", + "OSPA", + "OSPC", + "OSPE", + "OSPG", + "OSPS", + "PAPA", + "PAPC", + "PAPE", + "PAPG", + "PAPS", + "PHPA", + "PHPC", + "PHPE", + "PHPG", + "PHPS", + "PLPA", + "PLPC", + "PLPE", + "PLPG", + "PLPS", + "PMPA", + "PMPC", + "PMPE", + "PMPG", + "PMPS", + "POPA", + "POPC", + "POPE", + "POPG", + "POPS", + "PSM", + "PSPA", + "PSPC", + "PSPE", + "PSPG", + "PSPS", + "SAPA", + "SAPC", + "SAPE", + "SAPG", + "SAPS", + "SDPA", + "SDPC", + "SDPE", + "SDPG", + "SDPS", + "SHPA", + "SHPC", + "SHPE", + "SHPG", + "SHPS", + "SLPA", + "SLPC", + "SLPE", + "SLPG", + "SLPS", + "SMPA", + "SMPC", + "SMPE", + "SMPG", + "SMPS", + "SOPA", + "SOPC", + "SOPE", + "SOPG", + "SOPS", + "SPPA", + "SPPC", + "SPPE", + "SPPG", + "SPPS", + "SSM", +} + +# A few common alternate/legacy names not present in data/lipid_fragments.json +# that still show up in some packmol-memgen / CHARMM-GUI style structures. +_EXTRA_LIPID_RESIDUE_NAMES: Set[str] = {"PG", "PI", "POPI", "DOPI", "DPPI", "CHOL", "LA"} + +_FALLBACK_LIPID_RESIDUE_NAMES: Set[str] = ( + _FALLBACK_LIPID_FRAGMENT_CODES | _FALLBACK_FULL_LIPID_NAMES | _EXTRA_LIPID_RESIDUE_NAMES +) + + +def load_lipid_fragments( + lipid_fragments_json: Optional[Union[str, Path]] = None, +) -> Dict[str, List[str]]: + """Load the lipid-name to head/tail-fragment mapping. + + With no path given, loads the copy of ``lipid_fragments.json`` bundled + with the package. Pass an explicit path to load a different or updated + mapping instead (for example, a newer copy from a MemGen checkout). + """ + if lipid_fragments_json is not None: + with Path(lipid_fragments_json).open(encoding="utf-8") as handle: + data = json.load(handle) + else: + with ( + resources.files("molpacd") + .joinpath("data/lipid_fragments.json") + .open("r", encoding="utf-8") as handle + ): + data = json.load(handle) + if not isinstance(data, dict): + raise ValueError("lipid_fragments.json must contain a JSON object") + return data + + +def load_lipid_residue_names(lipid_fragments_json: Optional[Union[str, Path]] = None) -> Set[str]: + """Build the set of residue names that should be treated as lipid atoms. + + Combines every full lipid name and every head/tail fragment code from + ``load_lipid_fragments`` with a hardcoded fallback set mirroring the + bundled data, so lipid detection keeps working even in the unlikely case + the bundled or overriding JSON file cannot be fully read. + """ + data = load_lipid_fragments(lipid_fragments_json) + names = set(_FALLBACK_LIPID_RESIDUE_NAMES) + names.update(name.upper() for name in data) + for fragments in data.values(): + names.update(str(fragment).upper() for fragment in fragments) + return names + + +def classify_lipid_atoms( + atoms: Sequence[AtomRecord], lipid_residue_names: Set[str] +) -> Tuple[List[AtomRecord], Dict[Tuple[str, int], List[AtomRecord]], List[AtomRecord]]: + """Split atoms into protein, lipid residues, and everything else. + + Lipid residues are grouped by ``(chain_id, res_seq)`` since a single + lipid is typically stored as several same-numbered head/tail fragment + residues. + """ + protein_atoms: List[AtomRecord] = [] + lipid_residues: Dict[Tuple[str, int], List[AtomRecord]] = defaultdict(list) + other_atoms: List[AtomRecord] = [] + + for atom in atoms: + resname = atom.resname.strip().upper() + if resname in AMINO_ACID_RESIDUE_NAMES: + protein_atoms.append(atom) + elif resname in lipid_residue_names: + lipid_residues[(atom.chain_id, atom.res_seq)].append(atom) + else: + other_atoms.append(atom) + + return protein_atoms, dict(lipid_residues), other_atoms diff --git a/src/molpacd/models.py b/src/molpacd/models.py index 4ea00f6..6d9f60a 100644 --- a/src/molpacd/models.py +++ b/src/molpacd/models.py @@ -127,6 +127,34 @@ class RemoveResult: atom_name: Optional[str] +@dataclass(frozen=True) +class CavityLipidOptions: + cavity_radius: Optional[float] = None + margin: float = 2.0 + lipid_fragments_json: Optional[str] = None + + +@dataclass(frozen=True) +class CavityLipidResult: + total_lipid_residues: int + removed_lipid_residues: int + kept_lipid_residues: int + center: Tuple[float, float, float] + axis: Tuple[float, float, float] + inner_radius: float + outer_radius: float + z_min: float + z_max: float + margin: float + + +def validate_cavity_lipid_options(options: CavityLipidOptions) -> None: + if options.margin < 0: + raise ValueError("margin must be zero or greater") + if options.cavity_radius is not None and options.cavity_radius <= 0: + raise ValueError("cavity_radius must be greater than zero") + + def validate_cap_options(options: CapOptions) -> None: if options.selection not in {"ca", "backbone", "all"}: raise ValueError("selection must be one of ca, backbone, or all") diff --git a/tests/test_cavity_lipids.py b/tests/test_cavity_lipids.py new file mode 100644 index 0000000..8cf5c9e --- /dev/null +++ b/tests/test_cavity_lipids.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import json +import math +from dataclasses import replace +from pathlib import Path +from typing import List + +import numpy as np +import pytest + +from molpacd.cavity_lipids import remove_cavity_lipids +from molpacd.geometry import principal_axis_pca +from molpacd.models import AtomRecord, CavityLipidOptions, StructureData + + +def _barrel_ca_atoms(radius: float = 8.0) -> List[AtomRecord]: + """A ring of CA atoms stacked along z, approximating a beta barrel.""" + atoms: List[AtomRecord] = [] + serial = 1 + for z in range(-15, 16, 5): + for i in range(12): + angle = 2 * math.pi * i / 12 + atoms.append( + AtomRecord( + record="ATOM", + serial=serial, + name="CA", + resname="ALA", + chain_id="P", + res_seq=serial, + x=radius * math.cos(angle), + y=radius * math.sin(angle), + z=float(z), + ) + ) + serial += 1 + return atoms + + +def _lipid_atom(res_seq: int, x: float, y: float, z: float, resname: str = "PC") -> AtomRecord: + return AtomRecord( + record="ATOM", + serial=1000 + res_seq, + name="C1", + resname=resname, + chain_id="L", + res_seq=res_seq, + x=x, + y=y, + z=z, + ) + + +def _structure(lipids: List[AtomRecord]) -> StructureData: + return StructureData(atoms=[*_barrel_ca_atoms(), *lipids], source_format="pdb") + + +def test_removes_only_lipids_whose_center_falls_inside_the_cavity() -> None: + inside = _lipid_atom(1, 0.0, 0.0, 0.0) # dead center of the barrel + outside_radially = _lipid_atom(2, 20.0, 0.0, 0.0) # in the bilayer, not the pore + outside_axially = _lipid_atom(3, 0.0, 0.0, 50.0) # far past the barrel's z-range + structure = _structure([inside, outside_radially, outside_axially]) + + cleaned, result = remove_cavity_lipids(structure) + + assert result.total_lipid_residues == 3 + assert result.removed_lipid_residues == 1 + assert result.kept_lipid_residues == 2 + kept_keys = {(atom.chain_id, atom.res_seq) for atom in cleaned.atoms if atom.chain_id == "L"} + assert kept_keys == {("L", 2), ("L", 3)} + assert len(cleaned.atoms) == len(structure.atoms) - 1 + + +def test_cavity_radius_override_widens_the_removed_region() -> None: + outside_radially = _lipid_atom(2, 20.0, 0.0, 0.0) + structure = _structure([outside_radially]) + + _, default_result = remove_cavity_lipids(structure) + assert default_result.removed_lipid_residues == 0 + + _, widened_result = remove_cavity_lipids(structure, CavityLipidOptions(cavity_radius=25.0)) + assert widened_result.removed_lipid_residues == 1 + + +def test_margin_option_is_recorded_and_expands_the_boundary() -> None: + # Just past the default inner radius + margin (8 * 0.6 + 2.0 = 6.8). + borderline = _lipid_atom(1, 7.5, 0.0, 0.0) + structure = _structure([borderline]) + + _, tight_result = remove_cavity_lipids(structure, CavityLipidOptions(margin=0.0)) + assert tight_result.removed_lipid_residues == 0 + + _, loose_result = remove_cavity_lipids(structure, CavityLipidOptions(margin=5.0)) + assert loose_result.removed_lipid_residues == 1 + assert loose_result.margin == 5.0 + + +def test_lipid_fragments_json_override_recognizes_additional_residue_names( + tmp_path: Path, +) -> None: + novel = _lipid_atom(1, 0.0, 0.0, 0.0, resname="ZZZ") + structure = _structure([novel]) + + _, default_result = remove_cavity_lipids(structure) + assert default_result.total_lipid_residues == 0 # "ZZZ" isn't a known lipid name + + override = tmp_path / "custom.json" + override.write_text(json.dumps({"WEIRD": ["ZZZ"]}), encoding="utf-8") + + _, override_result = remove_cavity_lipids( + structure, CavityLipidOptions(lipid_fragments_json=str(override)) + ) + assert override_result.total_lipid_residues == 1 + assert override_result.removed_lipid_residues == 1 + + +def test_invalid_options_are_rejected() -> None: + structure = _structure([]) + + with pytest.raises(ValueError, match="margin"): + remove_cavity_lipids(structure, CavityLipidOptions(margin=-1.0)) + + with pytest.raises(ValueError, match="cavity_radius"): + remove_cavity_lipids(structure, CavityLipidOptions(cavity_radius=0.0)) + + +def test_requires_protein_atoms() -> None: + structure = StructureData(atoms=[_lipid_atom(1, 0.0, 0.0, 0.0)], source_format="pdb") + + with pytest.raises(ValueError, match="no protein atoms"): + remove_cavity_lipids(structure) + + +def test_rejects_multi_model_structures() -> None: + structure = _structure([_lipid_atom(1, 0.0, 0.0, 0.0)]) + multimodel = structure.with_atoms([replace(structure.atoms[0], model=2), *structure.atoms[1:]]) + + with pytest.raises(ValueError, match="multi-model"): + remove_cavity_lipids(multimodel) + + +def test_preserves_existing_structure_metadata() -> None: + structure = _structure([_lipid_atom(1, 0.0, 0.0, 0.0)]) + tagged = structure.with_atoms(structure.atoms, metadata={"resname": "DUM"}) + + cleaned, _ = remove_cavity_lipids(tagged) + + assert cleaned.metadata == {"resname": "DUM"} + + +def test_principal_axis_flips_a_raw_negative_z_eigenvector() -> None: + # These points' raw covariance eigenvector (before the z>=0 convention + # is enforced) points toward negative z; verifies the flip is applied. + coords = np.array( + [ + [0.33962000824864264, 0.42377135285334727, 3.7122741773625885], + [0.3827571602707609, 0.3194142202523809, -3.5891330853862047], + [-1.9016352983759945, -0.10891472790742324, -8.037318485206766], + [1.0801634125378852, -0.2887665059953775, 0.8347535610700986], + [-0.8496059556101431, -0.5106224678981267, -0.11533061686586776], + ] + ) + + _, axis = principal_axis_pca(coords) + + assert axis[2] >= 0 + + +def test_falls_back_to_all_protein_atoms_when_no_ca_atoms_present() -> None: + backbone_only = [replace(atom, name="N") for atom in _barrel_ca_atoms()] + structure = StructureData( + atoms=[*backbone_only, _lipid_atom(1, 0.0, 0.0, 0.0)], source_format="pdb" + ) + + _, result = remove_cavity_lipids(structure) + + assert result.removed_lipid_residues == 1 diff --git a/tests/test_cavity_lipids_pdb.py b/tests/test_cavity_lipids_pdb.py new file mode 100644 index 0000000..bf125d2 --- /dev/null +++ b/tests/test_cavity_lipids_pdb.py @@ -0,0 +1,242 @@ +from __future__ import annotations + +import math +from pathlib import Path +from typing import List + +import pytest + +from molpacd.cavity_lipids_pdb import remove_cavity_lipids_pdb +from molpacd.models import CavityLipidOptions + + +def _pdb_line( + record: str, + serial: int, + name: str, + resname: str, + chain: str, + res_seq: int, + x: float, + y: float, + z: float, + tail: str = "", +) -> str: + return ( + f"{record:<6}" + f"{serial:>5d} " + f"{name:<4}" + f" " + f"{resname:>3} " + f"{chain}" + f"{res_seq:>4d}" + f" " + f"{x:>8.3f}" + f"{y:>8.3f}" + f"{z:>8.3f}" + f"{1.00:>6.2f}" + f"{0.00:>6.2f}" + f"{tail}\n" + ) + + +def _barrel_and_lipid_lines() -> List[str]: + lines: List[str] = ["HEADER SYNTHETIC BARREL\n", "CRYST1 1 1 1 90 90 90 P 1\n"] + serial = 1 + for z in range(-15, 16, 5): + for i in range(12): + angle = 2 * math.pi * i / 12 + lines.append( + _pdb_line( + "ATOM", + serial, + "CA", + "ALA", + "P", + serial, + 8.0 * math.cos(angle), + 8.0 * math.sin(angle), + float(z), + ) + ) + serial += 1 + # A lipid dead center of the barrel (should be removed), with a + # packmol-memgen-style segment-id tail field past the standard columns. + lines.append(_pdb_line("ATOM", 9001, "C1", "PC", "L", 1, 0.0, 0.0, 0.0, tail=" MEMB ")) + # A lipid out in the bilayer (should be kept), same tail styling. + lines.append( + _pdb_line("ATOM", 9002, "C1", "PC", "L", 2, 20.0, 0.0, 0.0, tail=" MEMB ") + ) + lines.append("END\n") + return lines + + +def _write(path: Path, lines: List[str]) -> None: + path.write_text("".join(lines)) + + +def test_preserves_kept_lines_byte_for_byte(tmp_path: Path) -> None: + input_path = tmp_path / "packed.pdb" + output_path = tmp_path / "cleaned.pdb" + lines = _barrel_and_lipid_lines() + _write(input_path, lines) + + result = remove_cavity_lipids_pdb(input_path, output_path) + + assert result.total_lipid_residues == 2 + assert result.removed_lipid_residues == 1 + + output_text = output_path.read_text() + # Every kept original line (header, CRYST1, protein, the kept lipid, END) + # must appear byte-for-byte, including the packmol-style segid tail. + for line in lines: + if "L 1" in line and "PC " in line: + assert line not in output_text + else: + assert line in output_text + + +def test_inserts_remark_before_first_coordinate_line(tmp_path: Path) -> None: + input_path = tmp_path / "packed.pdb" + output_path = tmp_path / "cleaned.pdb" + _write(input_path, _barrel_and_lipid_lines()) + + remove_cavity_lipids_pdb(input_path, output_path) + + output_lines = output_path.read_text().splitlines() + header_index = output_lines.index("HEADER SYNTHETIC BARREL") + remark_index = next(i for i, line in enumerate(output_lines) if "REMARK" in line) + first_atom_index = next(i for i, line in enumerate(output_lines) if line.startswith("ATOM")) + + assert header_index < remark_index < first_atom_index + assert "Removed 1 of 2 lipid residues" in output_lines[remark_index + 1] + + +def test_reused_chain_letters_across_ter_separated_segments_are_not_dropped( + tmp_path: Path, +) -> None: + # Mirrors real packmol-memgen output: many independent lipid molecules, + # each terminated with TER, reusing a small set of chain letters and + # residue numbers. Biopython's structure builder can silently drop such + # atoms (see the io.py limitation this module works around); this raw + # parser must account for every ATOM/HETATM line regardless. + lines = _barrel_and_lipid_lines()[:-1] # drop the trailing END for now + extra: List[str] = [] + for i in range(3, 8): + extra.append(_pdb_line("ATOM", 9000 + i, "C1", "PC", "L", i, 30.0 + i, 0.0, 0.0)) + extra.append("TER\n") + lines = lines + extra + ["END\n"] + input_atom_lines = [line for line in lines if line.startswith(("ATOM", "HETATM"))] + input_path = tmp_path / "packed.pdb" + output_path = tmp_path / "cleaned.pdb" + _write(input_path, lines) + + result = remove_cavity_lipids_pdb(input_path, output_path) + + # 2 original lipid residues + 5 more distinct ones (unique resseq each). + assert result.total_lipid_residues == 7 + assert result.removed_lipid_residues == 1 + + output_atom_lines = [ + line + for line in output_path.read_text().splitlines(keepends=True) + if line.startswith(("ATOM", "HETATM")) + ] + # Every input atom line is accounted for: either still present in the + # output, or explicitly removed as part of the one cavity-bound residue. + assert len(output_atom_lines) == len(input_atom_lines) - 1 + assert set(output_atom_lines) == set(input_atom_lines) - { + line for line in input_atom_lines if "L 1" in line and " PC " in line + } + + +def test_rejects_non_pdb_extensions(tmp_path: Path) -> None: + input_path = tmp_path / "packed.cif" + input_path.write_text("data_x\n") + output_path = tmp_path / "cleaned.pdb" + + with pytest.raises(ValueError, match="expected a PDB file"): + remove_cavity_lipids_pdb(input_path, output_path) + + pdb_input = tmp_path / "packed.pdb" + _write(pdb_input, _barrel_and_lipid_lines()) + with pytest.raises(ValueError, match="expected a PDB file"): + remove_cavity_lipids_pdb(pdb_input, tmp_path / "cleaned.cif") + + +def test_rejects_malformed_atom_records(tmp_path: Path) -> None: + input_path = tmp_path / "bad.pdb" + input_path.write_text("ATOM 1 CA ALA A 1 not-a-number\n") + + with pytest.raises(ValueError, match="malformed PDB"): + remove_cavity_lipids_pdb(input_path, tmp_path / "out.pdb") + + +def test_rejects_files_with_no_atom_records(tmp_path: Path) -> None: + input_path = tmp_path / "empty.pdb" + input_path.write_text("HEADER EMPTY\nEND\n") + + with pytest.raises(ValueError, match="no ATOM/HETATM records"): + remove_cavity_lipids_pdb(input_path, tmp_path / "out.pdb") + + +def test_requires_protein_atoms(tmp_path: Path) -> None: + input_path = tmp_path / "lipids-only.pdb" + _write(input_path, [_pdb_line("ATOM", 1, "C1", "PC", "L", 1, 0.0, 0.0, 0.0)]) + + with pytest.raises(ValueError, match="no protein atoms"): + remove_cavity_lipids_pdb(input_path, tmp_path / "out.pdb") + + +def test_rejects_multi_model_structures(tmp_path: Path) -> None: + lines = ["MODEL 1\n", *_barrel_and_lipid_lines()[:-1], "ENDMDL\n"] + lines += ["MODEL 2\n", *_barrel_and_lipid_lines()[2:-1], "ENDMDL\n", "END\n"] + input_path = tmp_path / "multimodel.pdb" + _write(input_path, lines) + + with pytest.raises(ValueError, match="multi-model"): + remove_cavity_lipids_pdb(input_path, tmp_path / "out.pdb") + + +def test_ter_records_are_never_touched_even_for_removed_residues(tmp_path: Path) -> None: + # A TER directly after the removed lipid's atoms, and one after the kept + # lipid's atoms: both must survive untouched, exactly where they were in + # the input, regardless of which residue's atoms were removed. + base_lines = _barrel_and_lipid_lines() + removed_atom_index = next( + i for i, line in enumerate(base_lines) if "L 1" in line and " PC " in line + ) + kept_atom_index = next( + i for i, line in enumerate(base_lines) if "L 2" in line and " PC " in line + ) + lines = [*base_lines[: removed_atom_index + 1], "TER\n", *base_lines[removed_atom_index + 1 :]] + kept_atom_index += 1 # shifted by the TER inserted above + lines = [*lines[: kept_atom_index + 1], "TER\n", *lines[kept_atom_index + 1 :]] + input_path = tmp_path / "packed.pdb" + output_path = tmp_path / "cleaned.pdb" + _write(input_path, lines) + ter_count_in = sum(1 for line in lines if line.startswith("TER")) + assert ter_count_in == 2 + + result = remove_cavity_lipids_pdb(input_path, output_path) + + assert result.removed_lipid_residues == 1 + output_lines = output_path.read_text().splitlines(keepends=True) + ter_count_out = sum(1 for line in output_lines if line.startswith("TER")) + assert ter_count_out == 2 + for line in lines: + if line.startswith("TER"): + assert line in output_lines + + +def test_cavity_radius_and_margin_options_are_applied(tmp_path: Path) -> None: + input_path = tmp_path / "packed.pdb" + output_path = tmp_path / "cleaned.pdb" + _write(input_path, _barrel_and_lipid_lines()) + + result = remove_cavity_lipids_pdb( + input_path, output_path, CavityLipidOptions(cavity_radius=25.0, margin=0.0) + ) + + # With a widened cavity radius, the bilayer lipid at radius 20 is also removed. + assert result.removed_lipid_residues == 2 diff --git a/tests/test_cli.py b/tests/test_cli.py index 740acf5..28bf6c8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,17 +1,70 @@ from __future__ import annotations import json +import math import runpy import sys from pathlib import Path +from typing import List import pytest from molpacd.cli import main +from molpacd.io import write_structure +from molpacd.models import AtomRecord, StructureData FIXTURE = Path(__file__).parent / "data" / "2iww.pdb" +def _cavity_lipid_fixture(path: Path) -> None: + atoms: List[AtomRecord] = [] + serial = 1 + for z in range(-15, 16, 5): + for i in range(12): + angle = 2 * math.pi * i / 12 + atoms.append( + AtomRecord( + record="ATOM", + serial=serial, + name="CA", + resname="ALA", + chain_id="P", + res_seq=serial, + x=8.0 * math.cos(angle), + y=8.0 * math.sin(angle), + z=float(z), + ) + ) + serial += 1 + atoms.append( + AtomRecord( + record="ATOM", + serial=9001, + name="C1", + resname="PC", + chain_id="L", + res_seq=1, + x=0.0, + y=0.0, + z=0.0, + ) + ) + atoms.append( + AtomRecord( + record="ATOM", + serial=9002, + name="C1", + resname="PC", + chain_id="L", + res_seq=2, + x=20.0, + y=0.0, + z=0.0, + ) + ) + write_structure(StructureData(atoms=atoms, source_format="pdb"), path) + + def test_cli_analyze_json(capsys: pytest.CaptureFixture[str]) -> None: assert main(["analyze", str(FIXTURE), "--axis", "z", "--json"]) == 0 @@ -97,6 +150,52 @@ def test_cli_add_json_and_remove_outputs( assert decapped_json.exists() +def test_cli_remove_lipids_text_and_json( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + fixture = tmp_path / "packed.pdb" + _cavity_lipid_fixture(fixture) + cleaned_text = tmp_path / "cleaned-text.pdb" + cleaned_json = tmp_path / "cleaned-json.pdb" + + assert main(["remove-lipids", str(fixture), "-o", str(cleaned_text)]) == 0 + output = capsys.readouterr().out + assert "removed 1 of 2 lipid residues" in output + assert "wrote" in output + assert cleaned_text.exists() + + assert main(["remove-lipids", str(fixture), "-o", str(cleaned_json), "--json"]) == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["total_lipid_residues"] == 2 + assert payload["removed_lipid_residues"] == 1 + assert payload["kept_lipid_residues"] == 1 + assert payload["wrote"] == str(cleaned_json) + assert cleaned_json.exists() + + +def test_cli_remove_lipids_cavity_radius_and_margin_overrides(tmp_path: Path) -> None: + fixture = tmp_path / "packed.pdb" + _cavity_lipid_fixture(fixture) + cleaned = tmp_path / "cleaned.pdb" + + assert ( + main( + [ + "remove-lipids", + str(fixture), + "-o", + str(cleaned), + "--cavity-radius", + "25", + "--margin", + "0", + "--json", + ] + ) + == 0 + ) + + def test_cli_reports_errors_and_debug_reraises( tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: diff --git a/tests/test_lipids.py b/tests/test_lipids.py new file mode 100644 index 0000000..8799271 --- /dev/null +++ b/tests/test_lipids.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from molpacd.lipids import ( + AMINO_ACID_RESIDUE_NAMES, + classify_lipid_atoms, + load_lipid_fragments, + load_lipid_residue_names, +) +from molpacd.models import AtomRecord + + +def _atom(**overrides: object) -> AtomRecord: + values = { + "record": "ATOM", + "serial": 1, + "name": "C1", + "resname": "PA", + "chain_id": "A", + "res_seq": 1, + "x": 0.0, + "y": 0.0, + "z": 0.0, + } + values.update(overrides) + return AtomRecord(**values) + + +def test_load_lipid_fragments_returns_bundled_mapping() -> None: + data = load_lipid_fragments() + + assert set(data["POPC"]) == {"OL", "PA", "PC"} + assert "DOPE" in data + + +def test_load_lipid_residue_names_includes_fragments_and_full_names() -> None: + names = load_lipid_residue_names() + + # Full lipid name and its head/tail fragment codes should both resolve. + assert "POPC" in names + assert {"OL", "PA", "PC"} <= names + # Fragments only reachable through the bundled JSON (not the old + # hardcoded script list) must also be present. + assert {"AR", "DHA", "LAL", "PGR", "PH-", "SA", "SPM", "CHL"} <= names + + +def test_load_lipid_residue_names_accepts_explicit_override(tmp_path: Path) -> None: + override = tmp_path / "custom.json" + override.write_text(json.dumps({"XYZ": ["FOO", "BAR"]}), encoding="utf-8") + + names = load_lipid_residue_names(override) + + assert {"XYZ", "FOO", "BAR"} <= names + # Fallback names are still merged in for robustness. + assert "POPC" in names + + +def test_load_lipid_fragments_rejects_non_object_json(tmp_path: Path) -> None: + bad = tmp_path / "bad.json" + bad.write_text(json.dumps(["not", "an", "object"]), encoding="utf-8") + + with pytest.raises(ValueError, match="JSON object"): + load_lipid_fragments(bad) + + +def test_classify_lipid_atoms_groups_by_chain_and_residue_number() -> None: + lipid_names = load_lipid_residue_names() + atoms = [ + _atom(name="CA", resname="ALA", res_seq=1), + _atom(name="C1", resname="PA", chain_id="A", res_seq=10), + _atom(name="C2", resname="PA", chain_id="A", res_seq=10), + _atom(name="C1", resname="OL", chain_id="A", res_seq=11), + _atom(name="O", resname="WAT", chain_id="W", res_seq=1), + ] + + protein, lipids, other = classify_lipid_atoms(atoms, lipid_names) + + assert [atom.resname for atom in protein] == ["ALA"] + assert set(lipids.keys()) == {("A", 10), ("A", 11)} + assert len(lipids[("A", 10)]) == 2 + assert [atom.resname for atom in other] == ["WAT"] + + +def test_amino_acid_residue_names_covers_common_variants() -> None: + assert {"ALA", "HIE", "HID", "HIP", "CYX"} <= AMINO_ACID_RESIDUE_NAMES diff --git a/tests/test_molpacd.py b/tests/test_molpacd.py index 3234281..1bb2cee 100644 --- a/tests/test_molpacd.py +++ b/tests/test_molpacd.py @@ -11,11 +11,13 @@ from molpacd import ( CapOptions, + CavityLipidOptions, __version__, add_caps, analyze_structure, read_structure, remove_caps, + remove_cavity_lipids, write_structure, ) @@ -175,6 +177,16 @@ def test_remove_rejects_invalid_metadata_ranges(metadata: dict[str, str], match: remove_caps(structure) +def test_remove_cavity_lipids_on_lipid_free_fixture_is_a_no_op() -> None: + structure = read_structure(FIXTURE) + + cleaned, result = remove_cavity_lipids(structure, CavityLipidOptions(margin=2.0)) + + assert result.total_lipid_residues == 0 + assert result.removed_lipid_residues == 0 + assert len(cleaned.atoms) == len(structure.atoms) + + def test_write_and_read_mmcif_round_trip(tmp_path: Path) -> None: structure = read_structure(FIXTURE) cif_path = tmp_path / "fixture.cif"