Coverage for biobb_analysis/ambertools/cpptraj_rms.py: 96%
75 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 Cpptraj Rms class and the command line interface."""
5from typing import Optional
6from pathlib import PurePath
7from biobb_common.generic.biobb_object import BiobbObject
8from biobb_common.tools.file_utils import launchlogger
9from biobb_analysis.ambertools.common import get_default_value, check_top_path, check_traj_path, check_out_path, get_binary_path, get_in_parameters, get_negative_mask, setup_structure, get_mask, get_reference_rms
12class CpptrajRms(BiobbObject):
13 """
14 | biobb_analysis CpptrajRms
15 | Wrapper of the Ambertools Cpptraj module for calculating the Root Mean Square deviation (RMSd) of a given cpptraj compatible trajectory.
16 | Cpptraj (the successor to ptraj) is the main program in Ambertools for processing coordinate trajectories and data files. The parameter names and defaults are the same as the ones in the official `Cpptraj manual <https://raw.githubusercontent.com/Amber-MD/cpptraj/master/doc/CpptrajManual.pdf>`_.
18 Args:
19 input_top_path (str): Path to the input structure or topology file. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/ambertools/cpptraj.parm.top>`_. Accepted formats: top (edam:format_3881), pdb (edam:format_1476), prmtop (edam:format_3881), parmtop (edam:format_3881), zip (edam:format_3987).
20 input_traj_path (str): Path to the input trajectory to be processed. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/ambertools/cpptraj.traj.dcd>`_. Accepted formats: mdcrd (edam:format_3878), crd (edam:format_3878), cdf (edam:format_3650), netcdf (edam:format_3650), nc (edam:format_3650), restart (edam:format_3886), ncrestart (edam:format_3886), restartnc (edam:format_3886), dcd (edam:format_3878), charmm (edam:format_3887), cor (edam:format_2033), pdb (edam:format_1476), mol2 (edam:format_3816), trr (edam:format_3910), gro (edam:format_2033), binpos (edam:format_3885), xtc (edam:format_3875), cif (edam:format_1477), arc (edam:format_2333), sqm (edam:format_2033), sdf (edam:format_3814), conflib (edam:format_2033).
21 input_exp_path (str) (Optional): Path to the experimental reference file (required if reference = experimental). File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/ambertools/experimental.1e5t.pdb>`_. Accepted formats: pdb (edam:format_1476).
22 output_cpptraj_path (str): Path to the output processed analysis. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/ambertools/ref_cpptraj.rms.first.dat>`_. Accepted formats: dat (edam:format_1637), agr (edam:format_2033), xmgr (edam:format_2033), gnu (edam:format_2033).
23 output_traj_path (str) (Optional): Path to the output processed trajectory. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/ambertools/cpptraj.traj.dcd>`_. Accepted formats: mdcrd (edam:format_3878), crd (edam:format_3878), cdf (edam:format_3650), netcdf (edam:format_3650), nc (edam:format_3650), restart (edam:format_3886), ncrestart (edam:format_3886), restartnc (edam:format_3886), dcd (edam:format_3878), charmm (edam:format_3887), cor (edam:format_2033), pdb (edam:format_1476), mol2 (edam:format_3816), trr (edam:format_3910), gro (edam:format_2033), binpos (edam:format_3885), xtc (edam:format_3875), cif (edam:format_1477), arc (edam:format_2333), sqm (edam:format_2033), sdf (edam:format_3814), conflib (edam:format_2033).
24 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
25 * **start** (*int*) - (1) [1~100000|1] Starting frame for slicing
26 * **end** (*int*) - (-1) [-1~100000|1] Ending frame for slicing
27 * **steps** (*int*) - (1) [1~100000|1] Step for slicing
28 * **mask** (*str*) - ("all-atoms") Mask definition. Values: c-alpha (All c-alpha atoms; protein only), backbone (Backbone atoms), all-atoms (All system atoms), heavy-atoms (System heavy atoms; not hydrogen), side-chain (All not backbone atoms), solute (All system atoms except solvent atoms), ions (All ion molecules), solvent (All solvent atoms), AnyAmberFromatMask (Amber atom selection syntax like `@*`).
29 * **reference** (*str*) - ("first") Reference definition. Values: first (Use the first trajectory frame as reference), average (Use the average of all trajectory frames as reference), experimental (Use the experimental structure as reference).
30 * **nofit** (*bool*) - (False) Do not perform best-fit RMSD
31 * **norotate** (*bool*) - (False) Translate but do not rotate coordinates
32 * **nomod** (*bool*) - (False) Do not modify coordinates
33 * **binary_path** (*str*) - ("cpptraj") Path to the cpptraj executable binary.
34 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
35 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
36 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
37 * **container_path** (*str*) - (None) Container path definition.
38 * **container_image** (*str*) - ('afandiadib/ambertools:serial') Container image definition.
39 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
40 * **container_working_dir** (*str*) - (None) Container working directory definition.
41 * **container_user_id** (*str*) - (None) Container user_id definition.
42 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
44 Examples:
45 This is a use example of how to use the building block from Python::
47 from biobb_analysis.ambertools.cpptraj_rms import cpptraj_rms
48 prop = {
49 'start': 1,
50 'end': -1,
51 'steps': 1,
52 'mask': 'c-alpha',
53 'reference': 'first'
54 }
55 cpptraj_rms(input_top_path='/path/to/myTopology.top',
56 input_traj_path='/path/to/myTrajectory.dcd',
57 output_cpptraj_path='/path/to/newAnalysis.dat',
58 input_exp_path= '/path/to/myExpStructure.pdb',
59 output_traj_path='/path/to/newTrajectory.netcdf',
60 properties=prop)
62 Info:
63 * wrapped_software:
64 * name: Ambertools Cpptraj
65 * version: >=22.5
66 * license: GNU
67 * ontology:
68 * name: EDAM
69 * schema: http://edamontology.org/EDAM.owl
71 """
73 def __init__(self, input_top_path, input_traj_path, output_cpptraj_path,
74 input_exp_path=None, output_traj_path=None, properties=None, **kwargs) -> None:
75 properties = properties or {}
77 # Call parent class constructor
78 super().__init__(properties)
79 self.locals_var_dict = locals().copy()
81 # Input/Output files
82 self.io_dict = {
83 "in": {"input_top_path": input_top_path, "input_traj_path": input_traj_path, "input_exp_path": input_exp_path},
84 "out": {"output_cpptraj_path": output_cpptraj_path, "output_traj_path": output_traj_path}
85 }
87 # Properties specific for BB
88 self.instructions_file = get_default_value('instructions_file')
89 self.start = properties.get('start', 1)
90 self.end = properties.get('end', -1)
91 self.steps = properties.get('steps', 1)
92 self.mask = properties.get('mask', 'all-atoms')
93 self.reference = properties.get('reference', 'first')
94 self.nofit = properties.get('nofit', False)
95 self.norotate = properties.get('norotate', False)
96 self.nomod = properties.get('nomod', False)
97 self.properties = properties
98 self.binary_path = get_binary_path(properties, 'binary_path')
100 # Check the properties
101 self.check_init(properties)
103 def check_data_params(self, out_log, err_log):
104 """ Checks all the input/output paths and parameters """
105 self.io_dict["in"]["input_top_path"], self.input_top_path_orig = check_top_path(self.io_dict["in"]["input_top_path"], out_log, self.__class__.__name__)
106 self.io_dict["in"]["input_traj_path"] = check_traj_path(self.io_dict["in"]["input_traj_path"], out_log, self.__class__.__name__)
107 self.io_dict["out"]["output_cpptraj_path"] = check_out_path(self.io_dict["out"]["output_cpptraj_path"], out_log, self.__class__.__name__)
108 if self.io_dict["out"]["output_traj_path"]:
109 self.io_dict["out"]["output_traj_path"] = check_out_path(self.io_dict["out"]["output_traj_path"], out_log, self.__class__.__name__)
110 self.in_parameters = {'start': self.start, 'end': self.end, 'step': self.steps, 'mask': self.mask, 'reference': self.reference}
112 def create_instructions_file(self, container_io_dict, out_log, err_log):
113 """Creates an input file using the properties file settings"""
114 instructions_list = []
115 # different path if container execution or not
116 if self.container_path:
117 self.instructions_file = str(PurePath(self.container_volume_path).joinpath(self.instructions_file))
118 else:
119 self.instructions_file = self.create_tmp_file(self.instructions_file)
121 # parm
122 instructions_list.append('parm ' + container_io_dict["in"]["input_top_path"])
124 # trajin
125 in_params = get_in_parameters(self.in_parameters, out_log)
126 instructions_list.append('trajin ' + container_io_dict["in"]["input_traj_path"] + ' ' + in_params)
128 # Set up
129 instructions_list += setup_structure(self)
131 # mask
132 mask = self.in_parameters.get('mask', '')
133 ref_mask = ''
134 if mask:
135 strip_mask = get_negative_mask(mask, out_log)
136 ref_mask = get_mask(mask, out_log)
137 instructions_list.append('strip ' + strip_mask)
139 # reference
140 reference = self.in_parameters.get('reference', '')
141 inp_exp_pth = None
142 if "input_exp_path" in container_io_dict["in"]:
143 inp_exp_pth = container_io_dict["in"]["input_exp_path"]
144 instructions_list += get_reference_rms(reference, container_io_dict["out"]["output_cpptraj_path"], inp_exp_pth, ref_mask, True,
145 self.__class__.__name__, out_log, self.nofit, self.norotate, self.nomod)
147 # trajout
148 if ("output_traj_path" in container_io_dict["out"]):
149 instructions_list.append('trajout ' + container_io_dict["out"]["output_traj_path"])
151 # create .in file
152 with open(self.instructions_file, 'w') as mdp:
153 for line in instructions_list:
154 mdp.write(line.strip() + '\n')
156 return self.instructions_file
158 @launchlogger
159 def launch(self) -> int:
160 """Execute the :class:`CpptrajRms <ambertools.cpptraj_rms.CpptrajRms>` object."""
162 # check input/output paths and parameters
163 self.check_data_params(self.out_log, self.err_log)
165 # Setup Biobb
166 if self.check_restart():
167 return 0
168 self.stage_files()
170 # create instructions file
171 self.create_instructions_file(self.stage_io_dict, self.out_log, self.err_log)
173 # create cmd and launch execution
174 self.cmd = [self.binary_path, '-i', self.instructions_file]
176 # Run Biobb block
177 self.run_biobb()
179 # Copy files to host
180 self.copy_to_host()
182 # remove temporary folder(s)
183 self.remove_tmp_files()
184 self.check_arguments(output_files_created=True, raise_exception=False)
186 return self.return_code
189def cpptraj_rms(input_top_path: str, input_traj_path: str, output_cpptraj_path: str, input_exp_path: Optional[str] = None, output_traj_path: Optional[str] = None, properties: Optional[dict] = None, **kwargs) -> int:
190 """Execute the :class:`CpptrajRms <ambertools.cpptraj_rms.CpptrajRms>` class and
191 execute the :meth:`launch() <ambertools.cpptraj_rms.CpptrajRms.launch>` method."""
192 return CpptrajRms(**dict(locals())).launch()
195cpptraj_rms.__doc__ = CpptrajRms.__doc__
196main = CpptrajRms.get_main(cpptraj_rms, "Calculates the Root Mean Square deviation (RMSd) of a given cpptraj compatible trajectory.")
198if __name__ == '__main__':
199 main()