Coverage for biobb_mem/lipyphilic_biobb/lpp_zpositions.py: 79%

29 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-11-30 14:15 +0000

1#!/usr/bin/env python3 

2 

3"""Module containing the Lipyphilic ZPositions class and the command line interface.""" 

4 

5from biobb_common.generic.biobb_object import BiobbObject, launcher 

6import MDAnalysis as mda 

7from biobb_mem.common import ignore_no_box 

8from lipyphilic.analysis.z_positions import ZPositions 

9import pandas as pd 

10import numpy as np 

11 

12 

13class LPPZPositions(BiobbObject): 

14 """ 

15 | biobb_mem LPPZPositions 

16 | Wrapper of the LiPyphilic ZPositions module for calculating the z distance of lipids to the bilayer center. 

17 | 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/z_pos.html>`_. 

18 

19 Args: 

20 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). 

21 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). 

22 output_positions_path (str): Path to the output z positions. File type: output. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/reference/lipyphilic_biobb/zpositions.csv>`_. Accepted formats: csv (edam:format_3752). 

23 properties (dic - Python dictionary object containing the tool parameters, not input/output files): 

24 * **start** (*int*) - (None) Starting frame for slicing. 

25 * **stop** (*int*) - (None) Ending frame for slicing. 

26 * **steps** (*int*) - (None) Step for slicing. 

27 * **lipid_sel** (*str*) - ("all") Selection string for the lipids in a membrane. The selection should cover **all** residues in the membrane, including cholesterol. 

28 * **height_sel** (*str*) - ("all") Atom selection for the molecules for which the z position will be calculated. 

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*) - (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. 

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 

35 Examples: 

36 This is a use example of how to use the building block from Python:: 

37 

38 from biobb_mem.lipyphilic_biobb.lpp_zpositions import lpp_zpositions 

39 prop = { 

40 'lipid_sel': 'name GL1 GL2 ROH', 

41 } 

42 lpp_zpositions(input_top_path='/path/to/myTopology.tpr', 

43 input_traj_path='/path/to/myTrajectory.xtc', 

44 output_positions_path='/path/to/zpositions.csv.csv', 

45 properties=prop) 

46 

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 

55 

56 """ 

57 

58 def __init__(self, input_top_path: str, input_traj_path: str, output_positions_path: str, 

59 properties: dict | None = None, **kwargs) -> None: 

60 super().__init__(**locals()) 

61 

62 def run(self) -> None: 

63 """Execute the :class:`LPPZPositions <lipyphilic_biobb.lpp_zpositions.LPPZPositions>` object.""" 

64 

65 # Load the trajectory 

66 u = mda.Universe(self.sandbox_file("input_top_path"), self.sandbox_file("input_traj_path")) 

67 ignore_no_box(u, self.ignore_no_box, self.out_log, self.global_log) 

68 

69 # Create ZPositions object 

70 positions = ZPositions( 

71 universe=u, 

72 lipid_sel=self.lipid_sel, 

73 height_sel=self.height_sel, 

74 n_bins=self.n_bins 

75 ) 

76 # Run the analysis 

77 positions.run(start=self.start, stop=self.stop, step=self.steps) 

78 # Save the results 

79 frames = positions.z_positions.shape[1] 

80 resnames = np.repeat(positions._height_atoms.resnames, frames) 

81 resindices = np.tile(positions._height_atoms.resindices, frames) 

82 frame_numbers = np.repeat(np.arange(frames), positions._height_atoms.n_residues) 

83 

84 df = pd.DataFrame({ 

85 'resname': resnames, 

86 'resindex': resindices, 

87 'frame': frame_numbers, 

88 'zposition': positions.z_positions.T.flatten() 

89 }) 

90 

91 # Save the DataFrame to a CSV file 

92 df.to_csv(self.sandbox_file("output_positions_path"), index=False) 

93 

94 

95lpp_zpositions = launcher(LPPZPositions) 

96 

97 

98def frame_df(output_positions_path): 

99 """ 

100 Processes a CSV file containing z-position data and calculates the mean positive, mean negative, 

101 thickness, and standard deviation of thickness for each frame. 

102 

103 Args: 

104 output_positions_path (str): Path to the CSV file containing z-position data. 

105 Returns: 

106 pandas.DataFrame: A DataFrame with the following columns: 

107 - mean_positive: Mean of positive z-positions for each frame. 

108 - mean_negative: Mean of negative z-positions for each frame. 

109 - thickness: Difference between mean_positive and mean_negative for each frame. 

110 - std_thickness: Standard deviation of the absolute z-positions for each frame. 

111 """ 

112 

113 df = pd.read_csv(output_positions_path) 

114 grouped = df.groupby('frame')['zposition'].agg( 

115 mean_positive=lambda x: x[x > 0].mean(), 

116 mean_negative=lambda x: x[x < 0].mean(), 

117 std_positive=lambda x: x[x > 0].std(), 

118 std_negative=lambda x: x[x < 0].std() 

119 ) 

120 grouped['thickness'] = grouped['mean_positive'] - grouped['mean_negative'] 

121 grouped['std_thickness'] = df.groupby('frame')['zposition'].apply(lambda x: x.abs().std()) 

122 return grouped 

123 

124 

125if __name__ == '__main__': 

126 LPPZPositions.main()