Coverage for biobb_mem/fatslim/fatslim_membranes.py: 35%
68 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 14:15 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 14:15 +0000
1#!/usr/bin/env python3
3"""Module containing the FATSLiM Membranes class and the command line interface."""
4from pathlib import Path
5import shutil
6from biobb_common.generic.biobb_object import launcher
7from biobb_common.tools import file_utils as fu
8from biobb_mem.fatslim.common import FatslimBase
9import MDAnalysis as mda
10import numpy as np
13class FatslimMembranes(FatslimBase):
14 """
15 | biobb_mem FatslimMembranes
16 | Wrapper of the `FATSLiM membranes <https://pythonhosted.org/fatslim/documentation/leaflets.html>`_ module for leaflet and membrane identification.
17 | FATSLiM is designed to provide efficient and robust analysis of physical parameters from MD trajectories, with a focus on processing large trajectory files quickly.
19 Args:
20 input_top_path (str): Path to the input topology file. File type: input. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/data/A01JD/A01JD.pdb>`_. Accepted formats: tpr (edam:format_2333), gro (edam:format_2033), g96 (edam:format_2033), pdb (edam:format_1476), brk (edam:format_2033), ent (edam:format_1476).
21 input_traj_path (str) (Optional): Path to the GROMACS trajectory file. File type: input. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/data/A01JD/A01JD.xtc>`_. Accepted formats: xtc (edam:format_3875), trr (edam:format_3910), cpt (edam:format_2333), gro (edam:format_2033), g96 (edam:format_2033), pdb (edam:format_1476), tng (edam:format_3876).
22 input_ndx_path (str) (Optional): Path to the input lipid headgroups index NDX file. File type: input. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/data/A01JD/A01JD.ndx>`_. Accepted formats: ndx (edam:format_2033).
23 output_ndx_path (str): Path to the output index NDX file. File type: output. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/reference/fatslim/leaflets.ndx>`_. Accepted formats: ndx (edam:format_2033).
24 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
25 * **selection** (*str*) - ("not protein and element P") Alternative ot the NDX file for choosing the Headgroups used in the identification using MDAnalysis `selection language <https://docs.mdanalysis.org/stable/documentation_pages/selections.html>`_.
26 * **cutoff** (*float*) - (2) Cutoff distance (in nm) to be used when leaflet identification is performed.
27 * **frame** (*int*) - (0) Index of the trajectory frame whose leaflets are identified (-1: the last frame).
28 * **ignore_no_box** (*bool*) - (False) Ignore the absence of box information in the trajectory. If the trajectory does not contain box information, the box will be set to the minimum and maximum positions of the atoms in the trajectory.
29 * **return_hydrogen** (*bool*) - (False) Include hydrogen atoms in the output index file.
30 * **binary_path** (*str*) - ("fatslim") Path to the fatslim executable binary.
31 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
32 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
33 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
34 * **container_path** (*str*) - (None) Container path definition.
35 * **container_image** (*str*) - ('afandiadib/ambertools:serial') Container image definition.
36 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
37 * **container_user_id** (*str*) - (None) Container user_id definition.
38 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
40 Examples:
41 This is a use example of how to use the building block from Python::
43 from biobb_mem.fatslim.fatslim_membranes import fatslim_membranes
44 prop = {
45 'selection': '(resname DPPC and name P8)',
46 'cutoff': 2.2
47 }
48 fatslim_membranes(input_top_path='/path/to/myTopology.tpr',
49 input_traj_path='/path/to/myTrajectory.xtc',
50 output_ndx_path='/path/to/newIndex.ndx',
51 properties=prop)
53 Info:
54 * wrapped_software:
55 * name: FATSLiM
56 * version: 0.2.2
57 * license: GNU
58 * ontology:
59 * name: EDAM
60 * schema: http://edamontology.org/EDAM.owl
62 """
64 def __init__(self, input_top_path: str, output_ndx_path: str, input_traj_path: str | None = None,
65 input_ndx_path: str | None = None, properties: dict | None = None, **kwargs) -> None:
66 super().__init__(**locals())
68 def run(self) -> None:
69 """Execute the :class:`FatslimMembranes <fatslim.fatslim_membranes.FatslimMembranes>` object."""
70 tmp_dir = Path(self.create_tmp_dir())
71 u, cmd = self.fatslim_cmd(tmp_dir, "membranes", {"headgroups": self.selection}, frame=self.frame)
72 self.cmd = cmd + [
73 "--output-index", self.staged_path(tmp_dir / "leaflets.ndx"),
74 "--cutoff", str(self.cutoff)
75 ]
76 self.run_biobb()
78 # fatslim adds the time of the frame (ns) to the name of the index: leaflets_0000.ndx
79 leaflets_ndx = next(tmp_dir.glob("leaflets_*.ndx"), None)
80 if leaflets_ndx is None:
81 fu.log("No leaflets index file: FATSLiM failed.", self.out_log, self.global_log)
82 return
83 output_ndx = self.sandbox_file("output_ndx_path")
84 shutil.move(leaflets_ndx, output_ndx)
85 # Fatslim ignore H atoms so we add them manually
86 if self.return_hydrogen:
87 # Parse the atoms indices of the membrane without Hs
88 leaflet_groups = parse_index(output_ndx)
89 with mda.selections.gromacs.SelectionWriter(output_ndx, mode='w') as ndx:
90 for key, value in leaflet_groups.items():
91 # Select the residues using atom indexes
92 res_sele = set(u.atoms[np.array(value)-1].residues.resindices)
93 # Use the rexindex to select all the atoms of the residue
94 sele = f"resindex {' '.join(map(str, res_sele))}"
95 ndx.write(u.select_atoms(sele), name=key)
98fatslim_membranes = launcher(FatslimMembranes)
101def parse_index(ndx):
102 """
103 Parses a GROMACS index file (.ndx) to extract leaflet groups.
105 Args:
106 ndx (str): Path to the GROMACS index file (.ndx).
107 Returns:
108 dict: A dictionary where keys are group names for each leaflet in format "membrane_1_leaflet_1" and values are lists of integers representing atom indices starting from 1.
109 """
111 # Read the leaflet.ndx file
112 with open(ndx, 'r') as file:
113 leaflet_data = file.readlines()
115 # Initialize dictionaries to store leaflet groups
116 leaflet_groups = {}
117 current_group = None
119 # Parse the leaflet.ndx file
120 for line in leaflet_data:
121 line = line.strip()
122 if line.startswith('[') and line.endswith(']'):
123 current_group = line[1:-1].strip()
124 leaflet_groups[current_group] = []
125 elif current_group is not None:
126 leaflet_groups[current_group].extend(map(int, line.split()))
127 return leaflet_groups
130def display_fatslim(input_top_path: str, lipid_sel: str, input_traj_path: str = None, output_ndx_path="leaflets.ndx", leaflets=True,
131 colors=['blue', 'cyan', 'yellow', 'orange', 'purple', 'magenta'], non_mem_color='red'):
132 """
133 Visualize the leaflets of a membrane using NGLView. The lipids in the membrane are colored according to their leaflet. The ones not in the membrane are colored in red.
135 Args:
136 input_top_path (str): Path to the input topology file.
137 input_traj_path (str, optional): Path to the input trajectory file. Default is None.
138 output_ndx_path (str, optional): Path to the output index file containing leaflet information. Default is "leaflets.ndx".
139 leaflets (bool, optional): If True, visualize individual leaflets. If False, visualize entire membranes. Default is True.
140 colors (list of str, optional): List of colors to use for visualizing the leaflets or membranes. Default is ['blue', 'cyan', 'yellow', 'orange', 'purple', 'magenta'].
141 non_mem_color (str, optional): Color to use for visualizing lipids not in the membrane. Default is 'red'.
142 Returns:
143 nglview.NGLWidget: An NGLView widget displaying the membrane leaflets.
144 """
145 try:
146 import nglview as nv
147 except ImportError:
148 raise ImportError('Please install the nglview package to visualize the membrane/s.')
150 u = mda.Universe(input_top_path, input_traj_path) if input_traj_path else mda.Universe(input_top_path)
151 # Visualize the system with NGLView
152 view = nv.show_mdanalysis(u)
153 view.clear_representations()
155 leaflet_groups = parse_index(output_ndx_path)
156 n_mems = len(leaflet_groups.keys())//2
158 non_mem_resn = set(u.select_atoms(lipid_sel).residues.resnums)
159 for n in range(n_mems):
160 # Convert atoms list to resnums (nglview uses cannot use resindex)
161 top_resn = u.atoms[np.array(leaflet_groups[f'membrane_{n+1}_leaflet_1'])-1].residues.resnums
162 bot_resn = u.atoms[np.array(leaflet_groups[f'membrane_{n+1}_leaflet_2'])-1].residues.resnums
163 non_mem_resn -= set(top_resn)
164 non_mem_resn -= set(bot_resn)
165 if leaflets:
166 view.add_point(selection=", ".join(map(str, top_resn)), color=colors[n*2]) # lipids in top leaflet
167 view.add_point(selection=", ".join(map(str, bot_resn)), color=colors[n*2+1]) # lipids in bot leaflet
168 else:
169 mem_resn = np.concatenate((top_resn, bot_resn))
170 view.add_point(selection=", ".join(map(str, mem_resn)), color=colors[n*2]) # lipids in membrane
171 if len(non_mem_resn) > 0:
172 view.add_point(selection=", ".join(map(str, non_mem_resn)), color=non_mem_color) # lipids without membrane
173 return view
176if __name__ == '__main__':
177 FatslimMembranes.main()