Coverage for biobb_analysis/gromacs/gmx_trjconv_str_ens.py: 80%
81 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-14 14:38 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-14 14:38 +0000
1#!/usr/bin/env python3
3"""Module containing the GMX TrjConvStr class and the command line interface."""
4import argparse
5from typing import Optional
6from biobb_common.generic.biobb_object import BiobbObject
7from biobb_common.configuration import settings
8from biobb_common.tools import file_utils as fu
9from biobb_common.tools.file_utils import launchlogger
10from 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
13class GMXTrjConvStrEns(BiobbObject):
14 """
15 | biobb_analysis GMXTrjConvStrEns
16 | Wrapper of the GROMACS trjconv module for extracting an ensemble of frames containing a selection of atoms from GROMACS compatible trajectory files.
17 | 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.
19 Args:
20 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).
21 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).
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_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).
24 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
25 * **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).
26 * **skip** (*int*) - (1) [0~10000|1] Only write every nr-th frame.
27 * **start** (*int*) - (0) [0~10000|1] Time of first frame to read from trajectory (default unit ps).
28 * **end** (*int*) - (0) [0~10000|1] Time of last frame to read from trajectory (default unit ps).
29 * **dt** (*int*) - (0) [0~10000|1] Only write frame when t MOD dt = first time (ps).
30 * **output_name** (*str*) - ("output") File name for ensemble of output files.
31 * **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).
32 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary.
33 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
34 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
35 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
36 * **container_path** (*str*) - (None) Container path definition.
37 * **container_image** (*str*) - ('gromacs/gromacs:2022.2') Container image definition.
38 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
39 * **container_working_dir** (*str*) - (None) Container working directory definition.
40 * **container_user_id** (*str*) - (None) Container user_id definition.
41 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
43 Examples:
44 This is a use example of how to use the building block from Python::
46 from biobb_analysis.gromacs.gmx_trjconv_str_ens import gmx_trjconv_str_ens
47 prop = {
48 'selection': 'System',
49 'start': 0,
50 'end': 10,
51 'dt': 1
52 }
53 gmx_trjconv_str_ens(input_traj_path='/path/to/myStructure.trr',
54 input_top_path='/path/to/myTopology.tpr',
55 output_str_ens_path='/path/to/newStructureEnsemble.zip',
56 input_index_path='/path/to/myIndex.ndx',
57 properties=prop)
59 Info:
60 * wrapped_software:
61 * name: GROMACS trjconv
62 * version: >=2019.1
63 * license: LGPL 2.1
64 * ontology:
65 * name: EDAM
66 * schema: http://edamontology.org/EDAM.owl
68 """
70 def __init__(self, input_traj_path, input_top_path, output_str_ens_path,
71 input_index_path=None, properties=None, **kwargs) -> None:
72 properties = properties or {}
74 # Call parent class constructor
75 super().__init__(properties)
76 self.locals_var_dict = locals().copy()
78 # Input/Output files
79 self.io_dict = {
80 "in": {"input_traj_path": input_traj_path, "input_top_path": input_top_path, "input_index_path": input_index_path},
81 "out": {"output_str_ens_path": output_str_ens_path}
82 }
84 # Properties specific for BB
85 self.selection = properties.get('selection', "System")
86 self.skip = properties.get('skip', 1)
87 self.start = properties.get('start', 0)
88 self.end = properties.get('end', 0)
89 self.dt = properties.get('dt', 0)
90 self.output_name = properties.get('output_name', "output")
91 self.output_type = properties.get('output_type', "pdb")
92 self.properties = properties
94 # Properties common in all GROMACS BB
95 self.binary_path = get_binary_path(properties, 'binary_path')
97 # Check the properties
98 self.check_properties(properties)
99 self.check_arguments()
101 def check_data_params(self, out_log, err_log):
102 """ Checks all the input/output paths and parameters """
103 self.io_dict["in"]["input_traj_path"] = check_traj_path(self.io_dict["in"]["input_traj_path"], out_log, self.__class__.__name__)
104 self.io_dict["in"]["input_top_path"] = check_input_path(self.io_dict["in"]["input_top_path"], out_log, self.__class__.__name__)
105 self.io_dict["in"]["input_index_path"] = check_index_path(self.io_dict["in"]["input_index_path"], out_log, self.__class__.__name__)
106 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__)
107 if not self.io_dict["in"]["input_index_path"]:
108 self.selection = get_selection(self.properties, out_log, self.__class__.__name__)
109 else:
110 self.selection = get_selection_index_file(self.properties, self.io_dict["in"]["input_index_path"], 'selection', out_log, self.__class__.__name__)
111 self.skip = get_skip(self.properties, out_log, self.__class__.__name__)
112 self.start = get_start(self.properties, out_log, self.__class__.__name__)
113 self.end = get_end(self.properties, out_log, self.__class__.__name__)
114 self.dt = get_dt(self.properties, out_log, self.__class__.__name__)
115 self.output_name = self.properties.get('output_name', 'output')
116 self.output_type = get_ot_str_ens(self.properties, out_log, self.__class__.__name__)
118 @launchlogger
119 def launch(self) -> int:
120 """Execute the :class:`GMXTrjConvStrEns <gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns>` gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns object."""
122 # check input/output paths and parameters
123 self.check_data_params(self.out_log, self.err_log)
125 # Setup Biobb
126 if self.check_restart():
127 return 0
129 # standard input
130 self.io_dict['in']['stdin_file_path'] = fu.create_stdin_file(f'{self.selection}')
131 self.stage_files()
133 # if container execution, output to container_volume_path, else to unique_dir
134 if self.container_path:
135 output = self.container_volume_path + '/' + self.output_name + '.' + self.output_type
136 else:
137 output = self.stage_io_dict.get("unique_dir", "") + '/' + self.output_name + '.' + self.output_type
139 self.cmd = [self.binary_path, 'trjconv',
140 '-f', self.stage_io_dict["in"]["input_traj_path"],
141 '-s', self.stage_io_dict["in"]["input_top_path"],
142 '-skip', self.skip,
143 '-b', self.start,
144 '-dt', self.dt,
145 '-sep',
146 '-o', output]
148 # checking 'end' gromacs 'bug'
149 if not str(self.end) == "0":
150 self.cmd.append('-e')
151 self.cmd.append(self.end)
153 if self.stage_io_dict["in"].get("input_index_path"):
154 self.cmd.extend(['-n', self.stage_io_dict["in"]["input_index_path"]])
156 # Add stdin input file
157 self.cmd.append('<')
158 self.cmd.append(self.stage_io_dict["in"]["stdin_file_path"])
160 # Run Biobb block
161 self.run_biobb()
163 # Copy files to host
164 self.copy_to_host()
166 if self.container_path:
167 process_output_trjconv_str_ens(self.stage_io_dict['unique_dir'],
168 self.io_dict["out"]["output_str_ens_path"],
169 self.stage_io_dict.get("unique_dir"),
170 self.output_name + '*', self.out_log)
171 else:
172 process_output_trjconv_str_ens(self.stage_io_dict.get("unique_dir"),
173 self.stage_io_dict["out"]["output_str_ens_path"],
174 self.io_dict["out"]["output_str_ens_path"],
175 self.output_name + '*.pdb', self.out_log)
177 self.tmp_files.extend([
178 self.stage_io_dict.get("unique_dir", ""),
179 self.io_dict['in'].get("stdin_file_path", "")
180 ])
181 self.remove_tmp_files()
183 self.check_arguments(output_files_created=True, raise_exception=False)
185 return self.return_code
188def gmx_trjconv_str_ens(input_traj_path: str, input_top_path: str, output_str_ens_path: str, input_index_path: Optional[str] = None, properties: Optional[dict] = None, **kwargs) -> int:
189 """Execute the :class:`GMXTrjConvStrEns <gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns>` class and
190 execute the :meth:`launch() <gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns.launch>` method."""
192 return GMXTrjConvStrEns(input_traj_path=input_traj_path,
193 input_top_path=input_top_path,
194 output_str_ens_path=output_str_ens_path,
195 input_index_path=input_index_path,
196 properties=properties).launch()
199def main():
200 """Command line execution of this building block. Please check the command line documentation."""
201 parser = argparse.ArgumentParser(description="Extracts an ensemble of frames containing a selection of atoms from GROMACS compatible trajectory files.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
202 parser.add_argument('--config', required=False, help='Configuration file')
204 # Specific args of each building block
205 required_args = parser.add_argument_group('required arguments')
206 required_args.add_argument('--input_traj_path', required=True, help='Path to the GROMACS trajectory file. Accepted formats: xtc, trr, cpt, gro, g96, pdb, tng.')
207 required_args.add_argument('--input_top_path', required=True, help='Path to the GROMACS input topology file. Accepted formats: tpr, gro, g96, pdb, brk, ent.')
208 parser.add_argument('--input_index_path', required=False, help="Path to the GROMACS index file. Accepted formats: ndx.")
209 required_args.add_argument('--output_str_ens_path', required=True, help='Path to the output file. Accepted formats: zip.')
211 args = parser.parse_args()
212 args.config = args.config or "{}"
213 properties = settings.ConfReader(config=args.config).get_prop_dic()
215 # Specific call of each building block
216 gmx_trjconv_str_ens(input_traj_path=args.input_traj_path,
217 input_top_path=args.input_top_path,
218 output_str_ens_path=args.output_str_ens_path,
219 input_index_path=args.input_index_path,
220 properties=properties)
223if __name__ == '__main__':
224 main()