Coverage for biobb_analysis/gromacs/gmx_cluster.py: 83%
72 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-06-02 08:53 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-06-02 08:53 +0000
1#!/usr/bin/env python3
3"""Module containing the GMX Cluster class and the command line interface."""
5from typing import Optional
6from biobb_common.generic.biobb_object import BiobbObject
7from biobb_common.tools import file_utils as fu
8from biobb_common.tools.file_utils import launchlogger
9from pathlib import PurePath
10from biobb_analysis.gromacs.common import check_input_path, check_traj_path, check_index_path, check_out_pdb_path, get_binary_path, get_image_selection, get_selection_index_file, get_dista, get_method, get_cutoff
13class GMXCluster(BiobbObject):
14 """
15 | biobb_analysis GMXCluster
16 | Wrapper of the GROMACS cluster module for clustering structures from a given GROMACS compatible trajectory.
17 | `GROMACS cluster <http://manual.gromacs.org/current/onlinehelp/gmx-cluster.html>`_ can cluster structures using several different methods. Distances between structures can be determined from a trajectory. RMS deviation after fitting or RMS deviation of atom-pair distances can be used to define the distance between structures.
19 Args:
20 input_structure_path (str): Path to the input structure file. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/gromacs/topology.tpr>`_. 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): Path to the GROMACS trajectory file. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/gromacs/trajectory.trr>`_. 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_index_path (str) (Optional): Path to the GROMACS index file. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/gromacs/index.ndx>`_. Accepted formats: ndx (edam:format_2033).
23 output_pdb_path (str): Path to the output cluster file. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/gromacs/ref_cluster.pdb>`_. 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).
24 output_cluster_log_path (str) (Optional): Path to the output log file. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/gromacs/gmx_cluster_cluster.log>`_. Accepted formats: log (edam:format_2330).
25 output_rmsd_cluster_xpm_path (str) (Optional):Path to the output X PixMap compatible matrix file. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/gromacs/gmx_cluster_rmsd-clust.xpm>`_. Accepted formats: xpm (edam:format_3599).
26 output_rmsd_dist_xvg_path (str) (Optional): Path to xvgr/xmgr file. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/gromacs/gmx_cluster_rmsd-dist.xvg>`_. Accepted formats: xvg (edam:format_2330).
27 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
28 * **fit_selection** (*str*) - ("System") Group where the fitting will be performed. If **input_index_path** provided, check the file for the accepted values. Values: System (all atoms in the system), Protein (all protein atoms), Protein-H (protein atoms excluding hydrogens), C-alpha (C-alpha atoms), Backbone (protein backbone atoms: N; C-alpha and C), MainChain (protein main chain atoms: N; C-alpha; C and O; including oxygens in C-terminus), MainChain+Cb (protein main chain atoms including C-beta), MainChain+H (protein main chain atoms including backbone amide hydrogens and hydrogens on the N-terminus), SideChain (protein side chain atoms: that is all atoms except N; C-alpha; C; O; backbone amide hydrogens and oxygens in C-terminus and hydrogens on the N-terminus), SideChain-H (protein side chain atoms excluding all hydrogens), Prot-Masses (protein atoms excluding dummy masses), non-Protein (all non-protein atoms), Water (water molecules), SOL (water molecules), non-Water (anything not covered by the Water group), Ion (any name matching an Ion entry in residuetypes.dat), NA (all NA atoms), CL (all CL atoms), Water_and_ions (combination of the Water and Ions groups).
29 * **output_selection** (*str*) - ("System") Group that is going to be written in the output trajectory. If **input_index_path** provided, check the file for the accepted values. Values: System (all atoms in the system), Protein (all protein atoms), Protein-H (protein atoms excluding hydrogens), C-alpha (C-alpha atoms), Backbone (protein backbone atoms: N; C-alpha and C), MainChain (protein main chain atoms: N; C-alpha; C and O; including oxygens in C-terminus), MainChain+Cb (protein main chain atoms including C-beta), MainChain+H (protein main chain atoms including backbone amide hydrogens and hydrogens on the N-terminus), SideChain (protein side chain atoms: that is all atoms except N; C-alpha; C; O; backbone amide hydrogens and oxygens in C-terminus and hydrogens on the N-terminus), SideChain-H (protein side chain atoms excluding all hydrogens), Prot-Masses (protein atoms excluding dummy masses), non-Protein (all non-protein atoms), Water (water molecules), SOL (water molecules), non-Water (anything not covered by the Water group), Ion (any name matching an Ion entry in residuetypes.dat), NA (all NA atoms), CL (all CL atoms), Water_and_ions (combination of the Water and Ions groups).
30 * **dista** (*bool*) - (False) Use RMSD of distances instead of RMS deviation.
31 * **nofit** (*bool*) - (False) Do not use least squares fitting before RMSD calculation.
32 * **method** (*str*) - ("linkage") Method for cluster determination. Values: linkage (Add a structure to a cluster when its distance to any element of the cluster is less than cutoff), jarvis-patrick (Add a structure to a cluster when this structure and a structure in the cluster have each other as neighbors and they have a least P neighbors in common), monte-carlo (Reorder the RMSD matrix using Monte Carlo such that the order of the frames is using the smallest possible increments), diagonalization (Diagonalize the RMSD matrix), gromos (Count number of neighbors using cut-off and take structure with largest number of neighbors with all its neighbors as cluster and eliminate it from the pool of clusters).
33 * **cutoff** (*float*) - (0.1) [0~10|0.1] RMSD cut-off (nm) for two structures to be neighbor.
34 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary.
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 * **container_path** (*str*) - (None) Container path definition.
39 * **container_image** (*str*) - ('gromacs/gromacs:2022.2') Container image definition.
40 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
41 * **container_working_dir** (*str*) - (None) Container working directory definition.
42 * **container_user_id** (*str*) - (None) Container user_id definition.
43 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
45 Examples:
46 This is a use example of how to use the building block from Python::
48 from biobb_analysis.gromacs.gmx_cluster import gmx_cluster
49 prop = {
50 'fit_selection': 'System',
51 'output_selection': 'System',
52 'method': 'linkage'
53 }
54 gmx_cluster(input_structure_path='/path/to/myStructure.tpr',
55 input_traj_path='/path/to/myTrajectory.trr',
56 input_index_path='/path/to/myIndex.ndx',
57 output_pdb_path='/path/to/newStructure.pdb',
58 properties=prop)
60 Info:
61 * wrapped_software:
62 * name: GROMACS cluster
63 * version: >=2024.5
64 * license: LGPL 2.1
65 * ontology:
66 * name: EDAM
67 * schema: http://edamontology.org/EDAM.owl
69 """
71 def __init__(self, input_structure_path, input_traj_path, output_pdb_path,
72 input_index_path=None, output_cluster_log_path=None, output_rmsd_cluster_xpm_path=None,
73 output_rmsd_dist_xvg_path=None, properties=None, **kwargs) -> None:
74 properties = properties or {}
76 # Call parent class constructor
77 super().__init__(properties)
78 self.locals_var_dict = locals().copy()
80 # Input/Output files
81 self.io_dict = {
82 "in": {"input_structure_path": input_structure_path,
83 "input_traj_path": input_traj_path,
84 "input_index_path": input_index_path},
85 "out": {"output_pdb_path": output_pdb_path,
86 "output_cluster_log_path": output_cluster_log_path,
87 "output_rmsd_cluster_xpm_path": output_rmsd_cluster_xpm_path,
88 "output_rmsd_dist_xvg_path": output_rmsd_dist_xvg_path}
89 }
91 # Properties specific for BB
92 self.fit_selection = properties.get('fit_selection', "System")
93 self.output_selection = properties.get('output_selection', "System")
94 self.method = properties.get('method', "linkage")
95 self.dista = properties.get('dista', False)
96 self.nofit = properties.get('nofit', False)
97 self.cutoff = properties.get('cutoff', 0.1)
98 self.properties = properties
100 # Properties common in all GROMACS BB
101 self.binary_path = get_binary_path(properties, 'binary_path')
103 # Check the properties
104 self.check_init(properties)
106 def check_data_params(self, out_log, err_log):
107 """ Checks all the input/output paths and parameters """
108 self.io_dict["in"]["input_structure_path"] = check_input_path(self.io_dict["in"]["input_structure_path"], out_log, self.__class__.__name__)
109 self.io_dict["in"]["input_traj_path"] = check_traj_path(self.io_dict["in"]["input_traj_path"], out_log, self.__class__.__name__)
110 self.io_dict["in"]["input_index_path"] = check_index_path(self.io_dict["in"]["input_index_path"], out_log, self.__class__.__name__)
111 self.io_dict["out"]["output_pdb_path"] = check_out_pdb_path(self.io_dict["out"]["output_pdb_path"], out_log, self.__class__.__name__)
112 if not self.io_dict["in"]["input_index_path"]:
113 self.fit_selection = get_image_selection(self.properties, 'fit_selection', out_log, self.__class__.__name__)
114 self.output_selection = get_image_selection(self.properties, 'output_selection', out_log, self.__class__.__name__)
115 else:
116 self.fit_selection = get_selection_index_file(self.properties, self.io_dict["in"]["input_index_path"], 'fit_selection', out_log, self.__class__.__name__)
117 self.output_selection = get_selection_index_file(self.properties, self.io_dict["in"]["input_index_path"], 'output_selection', out_log, self.__class__.__name__)
118 self.dista = get_dista(self.properties, out_log, self.__class__.__name__)
119 self.method = get_method(self.properties, out_log, self.__class__.__name__)
120 self.cutoff = get_cutoff(self.properties, out_log, self.__class__.__name__)
122 @launchlogger
123 def launch(self) -> int:
124 """Execute the :class:`GMXCluster <gromacs.gmx_cluster.GMXCluster>` object."""
126 # check input/output paths and parameters
127 self.check_data_params(self.out_log, self.err_log)
129 # Setup Biobb
130 if self.check_restart():
131 return 0
133 # standard input
134 self.io_dict['in']['stdin_file_path'] = fu.create_stdin_file(f'{self.fit_selection} {self.output_selection}')
135 self.stage_files()
137 # Optional output files
138 if self.container_path:
139 dist_fn = self.stage_io_dict['out'].get('output_rmsd_dist_xvg_path') or 'rmsd-dist.xvg'
140 rmsd_fn = self.stage_io_dict['out'].get('output_rmsd_cluster_xpm_path') or 'rmsd-clust.xpm'
141 clust_fn = self.stage_io_dict['out'].get('output_cluster_log_path') or 'cluster.log'
142 dist = str(PurePath(self.container_volume_path).joinpath(dist_fn))
143 rmsd = str(PurePath(self.container_volume_path).joinpath(rmsd_fn))
144 clust = str(PurePath(self.container_volume_path).joinpath(clust_fn))
145 else:
146 dist = self.stage_io_dict['out'].get('output_rmsd_dist_xvg_path') or self.create_tmp_file('rmsd-dist.xvg')
147 rmsd = self.stage_io_dict['out'].get('output_rmsd_cluster_xpm_path') or self.create_tmp_file('rmsd-clust.xpm')
148 clust = self.stage_io_dict['out'].get('output_cluster_log_path') or self.create_tmp_file('cluster.log')
150 self.cmd = [self.binary_path, 'cluster',
151 '-g', clust,
152 '-dist', dist,
153 '-o', rmsd,
154 '-s', self.stage_io_dict["in"]["input_structure_path"],
155 '-f', self.stage_io_dict["in"]["input_traj_path"],
156 '-cl', self.stage_io_dict["out"]["output_pdb_path"],
157 '-cutoff', str(self.cutoff),
158 '-method', self.method]
160 if self.stage_io_dict["in"].get("input_index_path"):
161 self.cmd.extend(['-n', self.stage_io_dict["in"]["input_index_path"]])
163 if self.dista:
164 self.cmd.append('-dista')
166 if self.nofit:
167 self.cmd.append('-nofit')
169 # Add stdin input file
170 self.cmd.append('<')
171 self.cmd.append(self.stage_io_dict["in"]["stdin_file_path"])
173 # Run Biobb block
174 self.run_biobb()
175 # Copy files to host
176 self.copy_to_host()
177 self.tmp_files.append(self.io_dict['in'].get("stdin_file_path", ""))
178 self.remove_tmp_files()
179 self.check_arguments(output_files_created=True, raise_exception=False)
181 return self.return_code
184def gmx_cluster(input_structure_path: str,
185 input_traj_path: str,
186 output_pdb_path: str,
187 input_index_path: Optional[str] = None,
188 output_cluster_log_path: Optional[str] = None,
189 output_rmsd_cluster_xpm_path: Optional[str] = None,
190 output_rmsd_dist_xvg_path: Optional[str] = None,
191 properties: Optional[dict] = None,
192 **kwargs) -> int:
193 """Create the :class:`GMXCluster <gromacs.gmx_cluster.GMXCluster>` class and
194 execute the :meth:`launch() <gromacs.gmx_cluster.GMXCluster.launch>` method."""
195 return GMXCluster(**dict(locals())).launch()
198gmx_cluster.__doc__ = GMXCluster.__doc__
199main = GMXCluster.get_main(gmx_cluster, "Creates cluster structures from a given GROMACS compatible trajectory.")
201if __name__ == '__main__':
202 main()