Coverage for biobb_analysis/gromacs/gmx_trjconv_str_ens.py: 93%
68 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-08 10:47 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-08 10:47 +0000
1#!/usr/bin/env python3
3"""Module containing the GMX TrjConvStr 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 biobb_analysis.gromacs.common import get_binary_path, check_input_path, check_traj_path, check_index_path, get_selection_index_file, get_selection, check_out_str_ens_path, get_skip, get_start, get_end, get_dt, get_ot_str_ens, process_output_trjconv_str_ens
12class GMXTrjConvStrEns(BiobbObject):
13 """
14 | biobb_analysis GMXTrjConvStrEns
15 | Wrapper of the GROMACS trjconv module for extracting an ensemble of frames containing a selection of atoms from GROMACS compatible trajectory files.
16 | GROMACS trjconv module can convert trajectory files in many ways. See the `GROMACS trjconv <http://manual.gromacs.org/documentation/2018/onlinehelp/gmx-trjconv.html>`_ official documentation for further information.
18 Args:
19 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).
20 input_top_path (str): Path to the GROMACS input topology 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_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).
22 output_str_ens_path (str): Path to the output file. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/gromacs/ref_trjconv.str.ens.zip>`_. Accepted formats: zip (edam:format_3987).
23 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
24 * **selection** (*str*) - ("System") Group where the trjconv 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), DNA (all DNA atoms), RNA (all RNA atoms), Protein_DNA (all Protein-DNA complex atoms), Protein_RNA (all Protein-RNA complex atoms), Protein_DNA_RNA (all Protein-DNA-RNA complex atoms), DNA_RNA (all DNA-RNA complex atoms).
25 * **skip** (*int*) - (1) [0~10000|1] Only write every nr-th frame.
26 * **start** (*int*) - (0) [0~10000|1] Time of first frame to read from trajectory (default unit ps).
27 * **end** (*int*) - (0) [0~10000|1] Time of last frame to read from trajectory (default unit ps).
28 * **dt** (*int*) - (0) [0~10000|1] Only write frame when t MOD dt = first time (ps).
29 * **output_name** (*str*) - ("output") File name for ensemble of output files.
30 * **output_type** (*str*) - ("pdb") File type for ensemble of output files. Values: gro (Contains a molecular structure in Gromos87 format), g96 (Can be a GROMOS-96 initial/final configuration file or a coordinate trajectory file or a combination of both), pdb (Molecular structure files in the protein databank file format).
31 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary.
32 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
33 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
34 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
35 * **container_path** (*str*) - (None) Container path definition.
36 * **container_image** (*str*) - ('gromacs/gromacs:2022.2') Container image definition.
37 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
38 * **container_working_dir** (*str*) - (None) Container working directory definition.
39 * **container_user_id** (*str*) - (None) Container user_id definition.
40 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
42 Examples:
43 This is a use example of how to use the building block from Python::
45 from biobb_analysis.gromacs.gmx_trjconv_str_ens import gmx_trjconv_str_ens
46 prop = {
47 'selection': 'System',
48 'start': 0,
49 'end': 10,
50 'dt': 1
51 }
52 gmx_trjconv_str_ens(input_traj_path='/path/to/myStructure.trr',
53 input_top_path='/path/to/myTopology.tpr',
54 output_str_ens_path='/path/to/newStructureEnsemble.zip',
55 input_index_path='/path/to/myIndex.ndx',
56 properties=prop)
58 Info:
59 * wrapped_software:
60 * name: GROMACS trjconv
61 * version: >=2024.5
62 * license: LGPL 2.1
63 * ontology:
64 * name: EDAM
65 * schema: http://edamontology.org/EDAM.owl
67 """
69 def __init__(self, input_traj_path, input_top_path, output_str_ens_path,
70 input_index_path=None, properties=None, **kwargs) -> None:
71 properties = properties or {}
73 # Call parent class constructor
74 super().__init__(properties)
75 self.locals_var_dict = locals().copy()
77 # Input/Output files
78 self.io_dict = {
79 "in": {"input_traj_path": input_traj_path, "input_top_path": input_top_path, "input_index_path": input_index_path},
80 "out": {"output_str_ens_path": output_str_ens_path}
81 }
83 # Properties specific for BB
84 self.selection = properties.get('selection', "System")
85 self.skip = properties.get('skip', 1)
86 self.start = properties.get('start', 0)
87 self.end = properties.get('end', 0)
88 self.dt = properties.get('dt', 0)
89 self.output_name = properties.get('output_name', "output")
90 self.output_type = properties.get('output_type', "pdb")
91 self.properties = properties
93 # Properties common in all GROMACS BB
94 self.binary_path = get_binary_path(properties, 'binary_path')
96 # Check the properties
97 self.check_init(properties)
99 def check_data_params(self, out_log, err_log):
100 """ Checks all the input/output paths and parameters """
101 self.io_dict["in"]["input_traj_path"] = check_traj_path(self.io_dict["in"]["input_traj_path"], out_log, self.__class__.__name__)
102 self.io_dict["in"]["input_top_path"] = check_input_path(self.io_dict["in"]["input_top_path"], out_log, self.__class__.__name__)
103 self.io_dict["in"]["input_index_path"] = check_index_path(self.io_dict["in"]["input_index_path"], out_log, self.__class__.__name__)
104 self.io_dict["out"]["output_str_ens_path"] = check_out_str_ens_path(self.io_dict["out"]["output_str_ens_path"], out_log, self.__class__.__name__)
105 if not self.io_dict["in"]["input_index_path"]:
106 self.selection = get_selection(self.properties, out_log, self.__class__.__name__)
107 else:
108 self.selection = get_selection_index_file(self.properties, self.io_dict["in"]["input_index_path"], 'selection', out_log, self.__class__.__name__)
109 self.skip = get_skip(self.properties, out_log, self.__class__.__name__)
110 self.start = get_start(self.properties, out_log, self.__class__.__name__)
111 self.end = get_end(self.properties, out_log, self.__class__.__name__)
112 self.dt = get_dt(self.properties, out_log, self.__class__.__name__)
113 self.output_name = self.properties.get('output_name', 'output')
114 self.output_type = get_ot_str_ens(self.properties, out_log, self.__class__.__name__)
116 @launchlogger
117 def launch(self) -> int:
118 """Execute the :class:`GMXTrjConvStrEns <gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns>` object."""
120 # check input/output paths and parameters
121 self.check_data_params(self.out_log, self.err_log)
123 # Setup Biobb
124 if self.check_restart():
125 return 0
127 # standard input
128 self.io_dict['in']['stdin_file_path'] = fu.create_stdin_file(f'{self.selection}')
129 self.stage_files()
131 # if container execution, output to container_volume_path, else to unique_dir
132 if self.container_path:
133 output = self.container_volume_path + '/' + self.output_name + '.' + self.output_type
134 else:
135 output = self.stage_io_dict.get("unique_dir", "") + '/' + self.output_name + '.' + self.output_type
137 self.cmd = [self.binary_path, 'trjconv',
138 '-f', self.stage_io_dict["in"]["input_traj_path"],
139 '-s', self.stage_io_dict["in"]["input_top_path"],
140 '-skip', str(self.skip),
141 '-b', str(self.start),
142 '-dt', str(self.dt),
143 '-sep',
144 '-o', output]
146 # checking 'end' gromacs 'bug'
147 if not str(self.end) == "0":
148 self.cmd.append('-e')
149 self.cmd.append(str(self.end))
151 if self.stage_io_dict["in"].get("input_index_path"):
152 self.cmd.extend(['-n', self.stage_io_dict["in"]["input_index_path"]])
154 # Add stdin input file
155 self.cmd.append('<')
156 self.cmd.append(self.stage_io_dict["in"]["stdin_file_path"])
158 # Run Biobb block
159 self.run_biobb()
161 # Copy files to host
162 self.copy_to_host()
164 if self.container_path:
165 process_output_trjconv_str_ens(self.stage_io_dict['unique_dir'],
166 self.io_dict["out"]["output_str_ens_path"],
167 self.stage_io_dict.get("unique_dir"),
168 self.output_name + '*', self.out_log)
169 else:
170 process_output_trjconv_str_ens(self.stage_io_dict.get("unique_dir"),
171 self.stage_io_dict["out"]["output_str_ens_path"],
172 self.io_dict["out"]["output_str_ens_path"],
173 self.output_name + f'*.{self.output_type}', self.out_log)
175 self.tmp_files.append(self.io_dict['in'].get("stdin_file_path", ""))
176 self.remove_tmp_files()
177 self.check_arguments(output_files_created=True, raise_exception=False)
179 return self.return_code
182def gmx_trjconv_str_ens(input_traj_path: str,
183 input_top_path: str,
184 output_str_ens_path: str,
185 input_index_path: Optional[str] = None,
186 properties: Optional[dict] = None,
187 **kwargs) -> int:
188 """Execute the :class:`GMXTrjConvStrEns <gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns>` class and
189 execute the :meth:`launch() <gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns.launch>` method."""
190 return GMXTrjConvStrEns(**dict(locals())).launch()
193gmx_trjconv_str_ens.__doc__ = GMXTrjConvStrEns.__doc__
194main = GMXTrjConvStrEns.get_main(gmx_trjconv_str_ens, "Extracts an ensemble of frames containing a selection of atoms from GROMACS compatible trajectory files.")
196if __name__ == '__main__':
197 main()