Coverage for biobb_amber / cpptraj / cpptraj_randomize_ions.py: 93%
57 statements
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-15 15:57 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-15 15:57 +0000
1#!/usr/bin/env python3
3"""Module containing the CpptrajRandomizeIons 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 import file_utils as fu
9from biobb_common.tools.file_utils import launchlogger
10from biobb_amber.cpptraj.common import check_input_path, check_output_path
13class CpptrajRandomizeIons(BiobbObject):
14 """
15 | biobb_amber.cpptraj.cpptraj_randomize_ions CpptrajRandomizeIons
16 | Wrapper of the `AmberTools (AMBER MD Package) cpptraj tool <https://ambermd.org/AmberTools.php>`_ module.
17 | Swap specified ions with randomly selected solvent molecules using cpptraj tool from the AmberTools MD package.
19 Args:
20 input_top_path (str): Input topology file (AMBER ParmTop). File type: input. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/data/cpptraj/structure.ions.parmtop>`_. Accepted formats: top (edam:format_3881), parmtop (edam:format_3881), prmtop (edam:format_3881).
21 input_crd_path (str): Input coordinates file (AMBER crd). File type: input. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/data/cpptraj/structure.ions.crd>`_. Accepted formats: crd (edam:format_3878), mdcrd (edam:format_3878), inpcrd (edam:format_3878).
22 output_pdb_path (str): Structure PDB file with randomized ions. File type: output. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/reference/cpptraj/structure.randIons.pdb>`_. Accepted formats: pdb (edam:format_1476).
23 output_crd_path (str): Structure CRD file with coordinates including randomized ions. File type: output. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/reference/cpptraj/structure.randIons.crd>`_. Accepted formats: crd (edam:format_3878), mdcrd (edam:format_3878), inpcrd (edam:format_3878).
24 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
25 * **ion_mask** (*str*) - (":K+,Cl-,Na+") Ions to be randomized. Cpptraj mask syntax can be found at the official `Cpptraj manual <https://amber-md.github.io/cpptraj/CPPTRAJ.xhtml>`_.
26 * **solute_mask** (*str*) - (":DA,DC,DG,DT,D?3,D?5") Solute (or set of atoms) around which the ions can get no closer than the distance specified. Cpptraj mask syntax can be found at the official `Cpptraj manual <https://amber-md.github.io/cpptraj/CPPTRAJ.xhtml>`_.
27 * **distance** (*float*) - (5.0) Minimum distance cutoff for the ions around the defined solute.
28 * **overlap** (*float*) - (3.5) Minimum distance between ions.
29 * **binary_path** (*str*) - ("cpptraj") Path to the cpptraj executable binary.
30 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
31 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
32 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
33 * **container_path** (*str*) - (None) Container path definition.
34 * **container_image** (*str*) - ('afandiadib/ambertools:serial') Container image definition.
35 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
36 * **container_working_dir** (*str*) - (None) Container working directory definition.
37 * **container_user_id** (*str*) - (None) Container user_id definition.
38 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
40 Examples:
41 This is a use example of how to use the building block from Python::
43 from biobb_amber.cpptraj.cpptraj_randomize_ions import cpptraj_randomize_ions
44 prop = {
45 'remove_tmp': True
46 }
47 cpptraj_randomize_ions(input_top_path='/path/to/topology.top',
48 input_crd_path='/path/to/coordinates.crd',
49 output_pdb_path='/path/to/newStructure.pdb',
50 output_crd_path='/path/to/newCoordinates.crd',
51 properties=prop)
53 Info:
54 * wrapped_software:
55 * name: AmberTools cpptraj
56 * version: >20.9
57 * license: LGPL 2.1
58 * ontology:
59 * name: EDAM
60 * schema: http://edamontology.org/EDAM.owl
62 """
64 def __init__(self, input_top_path: str, input_crd_path: str, output_pdb_path: str, output_crd_path: str, properties, **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': {
75 'input_top_path': input_top_path,
76 'input_crd_path': input_crd_path
77 },
78 'out': {
79 'output_pdb_path': output_pdb_path,
80 'output_crd_path': output_crd_path
81 }
82 }
84 # Properties specific for BB
85 self.properties = properties
86 self.ion_mask = properties.get('ion_mask', ":K+,Cl-,Na+")
87 self.solute_mask = properties.get('solute_mask', ":DA,DC,DG,DT,D?3,D?5")
88 self.distance = properties.get('distance', 5.0)
89 self.overlap = properties.get('overlap', 3.5)
90 self.binary_path = properties.get('binary_path', 'cpptraj')
92 # Check the properties
93 self.check_properties(properties)
94 self.check_arguments()
96 def check_data_params(self, out_log, err_log):
97 """ Checks input/output paths correctness """
99 # Check input(s)
100 self.io_dict["in"]["input_top_path"] = check_input_path(self.io_dict["in"]["input_top_path"], "input_top_path", False, out_log, self.__class__.__name__)
101 self.io_dict["in"]["input_crd_path"] = check_input_path(self.io_dict["in"]["input_crd_path"], "input_crd_path", False, out_log, self.__class__.__name__)
103 # Check output(s)
104 self.io_dict["out"]["output_pdb_path"] = check_output_path(self.io_dict["out"]["output_pdb_path"], "output_pdb_path", False, out_log, self.__class__.__name__)
105 self.io_dict["out"]["output_crd_path"] = check_output_path(self.io_dict["out"]["output_crd_path"], "output_crd_path", False, out_log, self.__class__.__name__)
107 @launchlogger
108 def launch(self):
109 """Launches the execution of the CpptrajRandomizeIons module."""
111 # check input/output paths and parameters
112 self.check_data_params(self.out_log, self.err_log)
114 # Setup Biobb
115 if self.check_restart():
116 return 0
117 self.stage_files()
119 if self.container_path:
120 instructions_file = str(PurePath(self.stage_io_dict['unique_dir']).joinpath("cpptraj.in"))
121 instructions_file_path = str(PurePath(self.container_volume_path).joinpath("cpptraj.in"))
122 else:
123 self.tmp_folder = fu.create_unique_dir()
124 instructions_file = str(PurePath(self.tmp_folder).joinpath("cpptraj.in"))
125 fu.log('Creating %s temporary folder' % self.tmp_folder, self.out_log)
126 instructions_file_path = instructions_file
128 # create cpptraj.in file
129 # trajin randomizeIons.crd
130 # randomizeions :K+,Cl-,Na+ around :DA,DC,DG,DT,D?3,D?5 by 5.0 overlap 3.5
131 # trajout solv_randion.crd restart
132 # trajout solv_randion.pdb pdb
133 # go
135 with open(instructions_file, 'w') as cpptrajin:
136 cpptrajin.write("trajin " + self.stage_io_dict['in']['input_crd_path'] + " \n")
137 cpptrajin.write("randomizeions " + self.ion_mask + " around " + self.solute_mask + " by " + str(self.distance) + " overlap " + str(self.overlap) + " \n")
138 cpptrajin.write("trajout " + self.stage_io_dict['out']['output_crd_path'] + " restart \n")
139 cpptrajin.write("trajout " + self.stage_io_dict['out']['output_pdb_path'] + " pdb \n")
140 cpptrajin.write("go\n")
142 # Command line
143 self.cmd = [self.binary_path,
144 self.stage_io_dict['in']['input_top_path'],
145 '-i', instructions_file_path
146 ]
148 # Run Biobb block
149 self.run_biobb()
151 # Copy files to host
152 self.copy_to_host()
154 # Remove temporary file(s)
155 self.tmp_files.extend([self.tmp_folder, "cpptraj.log"])
156 self.remove_tmp_files()
158 self.check_arguments(output_files_created=True, raise_exception=False)
160 return self.return_code
163def cpptraj_randomize_ions(input_top_path: str, input_crd_path: str,
164 output_pdb_path: str, output_crd_path: str,
165 properties: Optional[dict] = None, **kwargs) -> int:
166 """Create the :class:`CpptrajRandomizeIons <cpptraj.cpptraj_randomize_ions.CpptrajRandomizeIons>` class and
167 execute the :meth:`launch() <cpptraj.cpptraj_randomize_ions.CpptrajRandomizeIons.launch>` method."""
168 return CpptrajRandomizeIons(**dict(locals())).launch()
171cpptraj_randomize_ions.__doc__ = CpptrajRandomizeIons.__doc__
172main = CpptrajRandomizeIons.get_main(cpptraj_randomize_ions, "Swap specified ions with randomly selected solvent molecules using cpptraj tool from the AmberTools MD package.")
174if __name__ == '__main__':
175 main()