Coverage for biobb_analysis/gromacs/gmx_trjconv_trj.py: 86%
76 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.file_utils import launchlogger
8import biobb_common.tools.file_utils as fu
9import biobb_analysis.gromacs.common as gro_common
12class GMXTrjConvTrj(BiobbObject):
13 """
14 | biobb_analysis GMXTrjConvTrj
15 | Wrapper of the GROMACS trjconv module for converting between GROMACS compatible trajectory file formats and/or extracts a selection of atoms.
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) (Optional): 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_traj_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.trj.xtc>`_. 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).
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 * **start** (*int*) - (0) [0~10000|1] Time of first frame to read from trajectory (default unit ps).
26 * **end** (*int*) - (0) [0~10000|1] Time of last frame to read from trajectory (default unit ps).
27 * **dt** (*int*) - (0) [0~10000|1] Only write frame when t MOD dt = first time (ps).
28 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary.
29 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
30 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
31 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
32 * **container_path** (*str*) - (None) Container path definition.
33 * **container_image** (*str*) - ('gromacs/gromacs:2022.2') Container image definition.
34 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
35 * **container_working_dir** (*str*) - (None) Container working directory definition.
36 * **container_user_id** (*str*) - (None) Container user_id definition.
37 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
39 Examples:
40 This is a use example of how to use the building block from Python::
42 from biobb_analysis.gromacs.gmx_trjconv_trj import gmx_trjconv_trj
43 prop = {
44 'selection': 'System',
45 'start': 0,
46 'end': 0
47 }
48 gmx_trjconv_trj(input_traj_path='/path/to/myStructure.trr',
49 output_traj_path='/path/to/newTrajectory.xtc',
50 input_index_path='/path/to/myIndex.ndx',
51 properties=prop)
53 Info:
54 * wrapped_software:
55 * name: GROMACS trjconv
56 * version: >=2024.5
57 * license: LGPL 2.1
58 * ontology:
59 * name: EDAM
60 * schema: http://edamontology.org/EDAM.owl
62 """
64 def __init__(self, input_traj_path,
65 output_traj_path, input_index_path=None, input_top_path=None, properties=None, **kwargs) -> None:
66 properties = properties or {}
68 # Call parent class constructor
69 super().__init__(properties)
70 self.locals_var_dict = locals().copy()
72 # Input/Output files
73 self.io_dict = {
74 "in": {"input_traj_path": input_traj_path, "input_index_path": input_index_path, "input_top_path": input_top_path},
75 "out": {"output_traj_path": output_traj_path}
76 }
78 # Properties specific for BB
79 if not self.io_dict["in"]["input_index_path"] and not self.io_dict["in"]["input_top_path"]:
80 self.selection = properties.get('selection', "")
81 else:
82 self.selection = properties.get('selection', "System")
83 self.start = properties.get('start')
84 self.end = properties.get('end')
85 self.dt = properties.get('dt')
86 self.properties = properties
88 # Properties common in all GROMACS BB
89 self.binary_path = gro_common.get_binary_path(properties, 'binary_path')
91 # Check the properties
92 self.check_init(properties)
94 def check_data_params(self, out_log, err_log):
95 """ Checks all the input/output paths and parameters """
96 self.io_dict["in"]["input_traj_path"] = gro_common.check_traj_path(self.io_dict["in"]["input_traj_path"], out_log, self.__class__.__name__)
97 self.io_dict["in"]["input_index_path"] = gro_common.check_index_path(self.io_dict["in"]["input_index_path"], out_log, self.__class__.__name__)
98 if self.io_dict["in"]["input_top_path"]:
99 self.io_dict["in"]["input_top_path"] = gro_common.check_input_path(self.io_dict["in"]["input_top_path"], out_log, self.__class__.__name__)
100 self.io_dict["out"]["output_traj_path"] = gro_common.check_out_traj_path(self.io_dict["out"]["output_traj_path"], out_log, self.__class__.__name__)
101 '''if not self.io_dict["in"]["input_index_path"]:
102 self.selection = get_selection(self.properties, out_log, self.__class__.__name__)
103 else:
104 self.selection = get_selection_index_file(self.properties, self.io_dict["in"]["input_index_path"], 'selection', out_log, self.__class__.__name__)'''
105 if self.io_dict["in"]["input_top_path"] and not self.io_dict["in"]["input_index_path"]:
106 self.selection = gro_common.get_selection(self.properties, out_log, self.__class__.__name__)
107 elif self.io_dict["in"]["input_index_path"]:
108 self.selection = gro_common.get_selection_index_file(self.properties, self.io_dict["in"]["input_index_path"], 'selection', out_log, self.__class__.__name__)
109 elif not self.io_dict["in"]["input_top_path"] and not self.io_dict["in"]["input_index_path"]:
110 self.selection = ""
111 else:
112 return True
113 self.start = gro_common.get_start(self.properties, out_log, self.__class__.__name__)
114 self.end = gro_common.get_end(self.properties, out_log, self.__class__.__name__)
115 self.dt = gro_common.get_dt(self.properties, out_log, self.__class__.__name__)
117 @launchlogger
118 def launch(self) -> int:
119 """Execute the :class:`GMXTrjConvTrj <gromacs.gmx_trjconv_trj.GMXTrjConvTrj>` object."""
121 # check input/output paths and parameters
122 self.check_data_params(self.out_log, self.err_log)
124 # if not input_index_path and not input_top_path provided, selection must be empty, otherwise exit
125 if not self.io_dict["in"]["input_index_path"] and not self.io_dict["in"]["input_top_path"] and self.selection != '':
126 fu.log(self.__class__.__name__ + ': If not input_index_path and not input_top_path provided, selection must be empty', self.out_log)
127 raise SystemExit(self.__class__.__name__ + ': If not input_index_path and not input_top_path provided, selection must be empty')
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.selection}')
135 self.stage_files()
137 self.cmd = [self.binary_path, 'trjconv', '-f', self.stage_io_dict["in"]["input_traj_path"]]
139 print(f"self.start: {self.start}")
140 print(f"self.end: {self.end}")
141 print(f"self.dt: {self.dt}")
143 if self.start:
144 self.cmd.extend(['-b', str(self.start)])
145 if self.end:
146 self.cmd.extend(['-e', str(self.end)])
147 if self.dt:
148 self.cmd.extend(['-dt', str(self.dt)])
150 self.cmd.extend(['-o', self.stage_io_dict["out"]["output_traj_path"]])
152 if "input_index_path" in self.stage_io_dict["in"]:
153 self.cmd.extend(['-n', self.stage_io_dict["in"]["input_index_path"]])
155 if "input_top_path" in self.stage_io_dict["in"]:
156 self.cmd.extend(['-s', self.stage_io_dict["in"]["input_top_path"]])
158 # Add stdin input file
159 self.cmd.append('<')
160 self.cmd.append(self.stage_io_dict["in"]["stdin_file_path"])
162 # Run Biobb block
163 self.run_biobb()
165 # Copy files to host
166 self.copy_to_host()
167 self.tmp_files.append(self.io_dict['in'].get("stdin_file_path", ""))
168 self.remove_tmp_files()
169 self.check_arguments(output_files_created=True, raise_exception=False)
171 return self.return_code
174def gmx_trjconv_trj(input_traj_path: str,
175 output_traj_path: str,
176 input_index_path: Optional[str] = None,
177 input_top_path: Optional[str] = None,
178 properties: Optional[dict] = None,
179 **kwargs) -> int:
180 """Execute the :class:`GMXTrjConvTrj <gromacs.gmx_trjconv_trj.GMXTrjConvTrj>` class and
181 execute the :meth:`launch() <gromacs.gmx_trjconv_trj.GMXTrjConvTrj.launch>` method."""
182 return GMXTrjConvTrj(**dict(locals())).launch()
185gmx_trjconv_trj.__doc__ = GMXTrjConvTrj.__doc__
186main = GMXTrjConvTrj.get_main(
187 gmx_trjconv_trj,
188 "Converts between GROMACS compatible trajectory file formats and/or extracts a selection of atoms."
189)
191if __name__ == '__main__':
192 main()