Coverage for biobb_mem/mdanalysis_biobb/mda_hole.py: 46%

61 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 MDAnalysis HOLE class and the command line interface.""" 

4import re 

5import numpy as np 

6import pandas as pd 

7from biobb_common.generic.biobb_object import BiobbObject, launcher 

8from biobb_common.tools import file_utils as fu 

9import MDAnalysis as mda 

10from mdahole2.analysis import HoleAnalysis 

11 

12 

13class MDAHole(BiobbObject): 

14 """ 

15 | biobb_mem MDAHole 

16 | Wrapper of the MDAnalysis HOLE module for analyzing ion channel pores or transporter pathways. 

17 | MDAnalysis HOLE provides an interface to the HOLE suite of tools to analyze pore dimensions and properties along a channel or transporter pathway. The parameter names and defaults follow the `MDAnalysis HOLE <https://www.mdanalysis.org/mdahole2/api.html>`_ implementation. 

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_hole_path (str): Path to the output HOLE analysis results. File type: output. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/reference/mdanalysis_biobb/hole.vmd>`_. Accepted formats: vmd (edam:format_2330). 

23 output_csv_path (str): Path to the output CSV file containing the radius and coordinates of the pore. File type: output. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/reference/mdanalysis_biobb/hole_profile.csv>`_. Accepted formats: csv (edam:format_3752). 

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

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

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

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

28 * **executable** (*str*) - ("hole") Path to the HOLE executable. 

29 * **select** (*str*) - ("protein") The selection string to create an atom selection that the HOLE analysis is applied to. 

30 * **cpoint** (*list*) - (None) Coordinates of a point inside the pore (Å). If None, tries to guess based on the geometry. 

31 * **cvect** (*list*) - (None) Search direction vector. If None, tries to guess based on the geometry. 

32 * **sample** (*float*) - (0.2) Distance of sample points in Å. This value determines how many points in the pore profile are calculated. 

33 * **end_radius** (*float*) - (22) Radius in Å, which is considered to be the end of the pore. 

34 * **dot_density** (*int*) - (15) [5~35] Density of facets for generating a 3D pore representation. 

35 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files. 

36 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist. 

37 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

38 

39 Examples: 

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

41 

42 from biobb_mem.mdanalysis_biobb.mda_hole import mda_hole 

43 prop = { 

44 'select': 'protein', 

45 'executable': 'hole' 

46 } 

47 mda_hole(input_top_path='/path/to/myTopology.pdb', 

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

49 output_hole_path='/path/to/hole_analysis.vmd', 

50 output_csv_path='/path/to/hole_profile.csv', 

51 properties=prop) 

52 

53 Info: 

54 * wrapped_software: 

55 * name: MDAnalysis 

56 * version: 2.7.0 

57 * license: GNU 

58 * ontology: 

59 * name: EDAM 

60 * schema: http://edamontology.org/EDAM.owl 

61 """ 

62 

63 def __init__(self, input_top_path: str, input_traj_path: str, output_hole_path: str, output_csv_path: str | None = None, 

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

65 super().__init__(**locals()) 

66 

67 def run(self) -> None: 

68 """Execute the :class:`MDAHole <mdanalysis_biobb.mda_hole.MDAHole>` object.""" 

69 

70 # Load the universe 

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

72 self.sandbox_file("input_traj_path")) 

73 # HoleAnalysis writes its files (hole000.out, simple2.rad...) in the current directory: the sandbox. 

74 # Its tmpdir argument does not move them, and HOLE limits the file paths to 70 characters. 

75 with fu.change_dir(self.stage_io_dict["unique_dir"]): 

76 # Create HoleAnalysis object 

77 hole = HoleAnalysis( 

78 universe=u, 

79 select=self.select, 

80 cpoint=self.cpoint, 

81 cvect=self.cvect, 

82 sample=self.sample, 

83 executable=self.executable, 

84 end_radius=self.end_radius 

85 ) 

86 # Run the analysis with step parameter 

87 hole.run( 

88 start=self.start, 

89 stop=self.stop, 

90 step=self.steps 

91 ) 

92 # Save the results to a CSV file 

93 all_frames = [] 

94 for frame in hole.results.profiles.keys(): 

95 rxn_coord = hole.results.profiles[frame].rxn_coord 

96 radius = hole.results.profiles[frame].radius 

97 df_frame = pd.DataFrame({'Frame': frame, 'Pore Coordinate': rxn_coord, 'Radius': radius}) 

98 all_frames.append(df_frame) 

99 # Concatenate all frames into a single DataFrame 

100 df_all_frames = pd.concat(all_frames, ignore_index=True) 

101 df_all_frames.to_csv(self.sandbox_file("output_csv_path"), index=False) 

102 

103 hole.create_vmd_surface( 

104 self.sandbox_file("output_hole_path"), 

105 dot_density=self.dot_density 

106 ) 

107 hole.delete_temporary_files() 

108 

109 

110mda_hole = launcher(MDAHole) 

111 

112 

113def display_hole(input_top_path: str, input_traj_path: str, 

114 output_hole_path: str = 'hole.vmd', 

115 frame: int = 0, opacity: float = 0.9): 

116 """ 

117 Visualize a channel using NGLView from a VMD file. 

118 

119 Args: 

120 input_top_path (str): Path to the input topology file. 

121 output_hole_path (str, optional): Path to the VMD file containing the channel data. Default is 'hole.vmd'. 

122 frame (int, optional): Frame index to visualize. Default is 0. 

123 opacity (float, optional): Opacity of the visualization. Default is 0.9. 

124 Returns: 

125 nglview.NGLWidget: NGLView widget for visualizing the channel. 

126 """ 

127 

128 try: 

129 import nglview as nv 

130 except ImportError: 

131 raise ImportError('Please install the nglview package to visualize the channel.') 

132 

133 # Read the VMD file and parse triangles 

134 with open(output_hole_path, 'r') as f: 

135 lines = f.readlines() 

136 

137 # Find lines with triangle coordinates 

138 trinorms = [] 

139 for i, line in enumerate(lines): 

140 if i > 3 and 'set triangle' in line: 

141 vmd_set = re.sub(r'set triangles\(\d+\)', '', line) # Remove set triangles(i) 

142 vmd_set = re.sub(r'\{(\s*-?\d[^\s]*)(\s*-?\d[^\s]*)(\s*-?\d[^}]*)\}', r'[\1,\2,\3]', vmd_set) # Convert { x y z } to [x,y,z] 

143 vmd_set = vmd_set.replace('{', '[').replace('}', ']') # Convert { to [ and } to ] 

144 vmd_set = re.sub(r'\]\s*\[', '], [', vmd_set) # Add commas between brackets 

145 vmd_set = eval(vmd_set.strip()) # Evaluate string as list 

146 # different hole colors 

147 trinorms.append(vmd_set) 

148 # Create a list of positions, colors, and normals 

149 colors = np.array([[1, 0, 0], # red 

150 [0, 1, 0], # green 

151 [0, 0, 1]]) # blue 

152 poss, cols, nors = [], [], [] 

153 for i, color in enumerate(colors): 

154 if len(trinorms[frame][i]) > 0: 

155 col_dat = np.array(trinorms[frame][i]) 

156 poss.append(col_dat[:, :3, :].flatten()) # 3 first elements are positions 

157 cols.append((np.zeros(col_dat.shape[0]*18).reshape(-1, 3) + color).flatten()) # 3 colors for each vertex 

158 nors.append(col_dat[:, 3:, :].flatten()) # 3 last elements are normals 

159 poss = np.concatenate(poss) 

160 cols = np.concatenate(cols) 

161 nors = np.concatenate(nors) 

162 # Create NGLView widget 

163 u = mda.Universe(input_top_path, input_traj_path) 

164 view = nv.show_mdanalysis(u) 

165 # view.clear_representations() 

166 mesh = ('mesh', poss, cols) 

167 view._add_shape([mesh], name='my_shape') 

168 view.update_representation(component=1, repr_index=0, opacity=opacity) 

169 return view 

170 

171 

172if __name__ == '__main__': 

173 MDAHole.main()