Coverage for biobb_mem/lipyphilic_biobb/lpp_assign_leaflets.py: 58%
43 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 Lipyphilic AssignLeaflets class and the command line interface."""
4from biobb_common.generic.biobb_object import BiobbObject, launcher
5import MDAnalysis as mda
6from biobb_mem.common import ignore_no_box
7from lipyphilic.leaflets.assign_leaflets import AssignLeaflets
8import pandas as pd
9import numpy as np
12class LPPAssignLeaflets(BiobbObject):
13 """
14 | biobb_mem LPPAssignLeaflets
15 | Wrapper of the LiPyphilic AssignLeaflets module for assigning lipids to leaflets in a bilayer.
16 | LiPyphilic is a Python package for analyzing MD simulations of lipid bilayers. The parameter names and defaults are the same as the ones in the official `Lipyphilic documentation <https://lipyphilic.readthedocs.io/en/latest/reference/analysis/leaflets.html>`_.
18 Args:
19 input_top_path (str): Path to the input structure or topology file. File type: input. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/data/A01JD/A01JD.pdb>`_. Accepted formats: crd (edam:format_3878), gro (edam:format_2033), mdcrd (edam:format_3878), mol2 (edam:format_3816), pdb (edam:format_1476), pdbqt (edam:format_1476), prmtop (edam:format_3881), psf (edam:format_3882), top (edam:format_3881), tpr (edam:format_2333), xml (edam:format_2332), xyz (edam:format_3887).
20 input_traj_path (str): Path to the input trajectory to be processed. File type: input. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/data/A01JD/A01JD.xtc>`_. Accepted formats: arc (edam:format_2333), crd (edam:format_3878), dcd (edam:format_3878), ent (edam:format_1476), gro (edam:format_2033), inpcrd (edam:format_3878), mdcrd (edam:format_3878), mol2 (edam:format_3816), nc (edam:format_3650), pdb (edam:format_1476), pdbqt (edam:format_1476), restrt (edam:format_3886), tng (edam:format_3876), trr (edam:format_3910), xtc (edam:format_3875), xyz (edam:format_3887).
21 output_leaflets_path (str): Path to the output leaflet assignments. File type: output. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/reference/lipyphilic_biobb/leaflets_data.csv>`_. Accepted formats: csv (edam:format_3752), npy (edam:format_4003).
22 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
23 * **start** (*int*) - (None) Starting frame for slicing.
24 * **stop** (*int*) - (None) Ending frame for slicing.
25 * **steps** (*int*) - (None) Step for slicing.
26 * **lipid_sel** (*str*) - ("all") Selection string for the lipids in a membrane. The selection should cover **all** residues in the membrane, including cholesterol.
27 * **midplane_sel** (*str*) - (None) Selection string for residues that may be midplane. Any residues not in this selection will be assigned to a leaflet regardless of its proximity to the midplane. The default is `None`, in which case all lipids will be assigned to either the upper or lower leaflet.
28 * **midplane_cutoff** (*float*) - (None) Minimum distance in *z* an atom must be from the midplane to be assigned to a leaflet rather than the midplane. The default is `0`, in which case all lipids will be assigned to either the upper or lower leaflet. Must be non-negative.
29 * **n_bins** (*int*) - (1) Number of bins in *x* and *y* to use to create a grid of membrane patches. Local membrane midpoints are computed for each patch, and lipids assigned a leaflet based on the distance to their local membrane midpoint. The default is `1`, which is equivalent to computing a single global midpoint.
30 * **ignore_no_box** (*bool*) - (True) 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.
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.
35 Examples:
36 This is a use example of how to use the building block from Python::
38 from biobb_mem.lipyphilic_biobb.lpp_assign_leaflets import lpp_assign_leaflets
39 prop = {
40 'lipid_sel': 'name GL1 GL2 ROH',
41 }
42 lpp_assign_leaflets(input_top_path='/path/to/myTopology.tpr',
43 input_traj_path='/path/to/myTrajectory.xtc',
44 output_leaflets_path='/path/to/leaflets.csv',
45 properties=prop)
47 Info:
48 * wrapped_software:
49 * name: LiPyphilic
50 * version: 0.11.0
51 * license: GPL-2.0
52 * ontology:
53 * name: EDAM
54 * schema: http://edamontology.org/EDAM.owl
56 """
58 def __init__(self,
59 input_top_path: str,
60 input_traj_path: str,
61 output_leaflets_path: str,
62 properties: dict | None = None,
63 **kwargs) -> None:
64 super().__init__(**locals())
66 def run(self) -> None:
67 """Execute the :class:`LPPAssignLeaflets <lipyphilic_biobb.lpp_assign_leaflets.LPPAssignLeaflets>` object."""
69 # Load the trajectory
70 u = mda.Universe(self.sandbox_file("input_top_path"), self.sandbox_file("input_traj_path"))
71 ignore_no_box(u, self.ignore_no_box, self.out_log, self.global_log)
72 # Create AssignLeaflets object
73 leaflets = AssignLeaflets(
74 universe=u,
75 lipid_sel=self.lipid_sel,
76 midplane_sel=self.midplane_sel,
77 midplane_cutoff=self.midplane_cutoff,
78 n_bins=self.n_bins
79 )
80 # Run the analysis
81 leaflets.run(start=self.start, stop=self.stop, step=self.steps)
83 out_format = self.stage_io_dict["out"]["output_leaflets_path"].split('.')[-1]
84 if out_format == 'csv':
85 # Save the results
86 frames = leaflets.leaflets.shape[1]
87 resnames = np.repeat(leaflets.membrane.resnames, frames)
88 resindices = np.tile(leaflets.membrane.resindices, frames)
89 frame_numbers = np.repeat(np.arange(frames), leaflets.membrane.n_residues)
91 df = pd.DataFrame({
92 'resname': resnames,
93 'resindex': resindices,
94 'frame': frame_numbers,
95 'leaflet_index': leaflets.leaflets.T.flatten()
96 })
98 # Save the DataFrame to a CSV file
99 df.to_csv(self.sandbox_file("output_leaflets_path"), index=False)
100 elif out_format == 'npy':
101 np.save(self.sandbox_file("output_leaflets_path"), leaflets.leaflets)
104lpp_assign_leaflets = launcher(LPPAssignLeaflets)
107def display_nglview(input_top_path: str, output_leaflets_path: str, frame: int = 0):
108 """
109 Visualize the leaflets of a membrane using NGLView.
111 Args:
112 input_top_path (str): Path to the input topology file.
113 output_leaflets_path (str): Path to the CSV file containing leaflet assignments.
114 frame (int, optional): Frame number to visualize. Default is 0.
115 Returns:
116 nglview.NGLWidget: An NGLView widget displaying the membrane leaflets.
117 """
119 try:
120 import nglview as nv
121 except ImportError:
122 raise ImportError('Please install the nglview package to visualize the leaflets.')
123 # Read the leaflets DataFrame
124 df = pd.read_csv(output_leaflets_path)
125 top_idx = df[(df['frame'] == frame) & (df['leaflet_index'] == 1)]['resindex'].values
126 bot_idx = df[(df['frame'] == frame) & (df['leaflet_index'] == -1)]['resindex'].values
127 # Load the topology and convert the resindices to resnums (nglview uses resnums)
128 u = mda.Universe(input_top_path)
129 top_resnum = u.residues[top_idx].resnums
130 bot_resnum = u.residues[bot_idx].resnums
131 # Create the view
132 view = nv.show_file(input_top_path)
133 view.update_ball_and_stick(selection='all', opacity=0.0) # delete membrane
134 view.add_ball_and_stick(selection=", ".join(map(str, top_resnum)), color='blue')
135 view.add_ball_and_stick(selection=", ".join(map(str, bot_resnum)), color='yellow')
136 return view
139if __name__ == '__main__':
140 LPPAssignLeaflets.main()