Coverage for biobb_mem/ambertools/cpptraj_density.py: 85%
33 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 14:15 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 14:15 +0000
1#!/usr/bin/env python3
3"""Module containing the Cpptraj Density class and the command line interface."""
4from pathlib import Path, PurePath
5from biobb_common.generic.biobb_object import BiobbObject, launcher
8class CpptrajDensity(BiobbObject):
9 """
10 | biobb_mem CpptrajDensity
11 | Wrapper of the Ambertools Cpptraj module for calculating density profile along an axis of a given cpptraj compatible trajectory.
12 | 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>`_.
14 Args:
15 input_top_path (str): Path to the input structure or topology file. File type: input. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/data/ambertools/topology.pdb>`_. Accepted formats: top (edam:format_3881), pdb (edam:format_1476), prmtop (edam:format_3881), parmtop (edam:format_3881), zip (edam:format_3987).
16 input_traj_path (str): Path to the input trajectory to be processed. File type: input. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/data/ambertools/trajectory.xtc>`_. 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).
17 output_cpptraj_path (str): Path to the output processed density analysis. File type: output. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/reference/ambertools/density_default.dat>`_. Accepted formats: dat (edam:format_1637), agr (edam:format_2033), xmgr (edam:format_2033), gnu (edam:format_2033).
18 output_traj_path (str) (Optional): Path to the output processed trajectory. File type: output. `Sample file <https://github.com/bioexcel/biobb_mem/raw/main/biobb_mem/test/reference/ambertools/trajectory_out.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).
19 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
20 * **start** (*int*) - (1) [1~100000|1] Starting frame for slicing
21 * **end** (*int*) - (-1) [-1~100000|1] Ending frame for slicing
22 * **steps** (*int*) - (1) [1~100000|1] Step for slicing
23 * **density_type** (*str*) - ("number") Number, mass, partial charge (q) or electron (Ne - q) density. Electron density will be converted to e-/Å3 by dividing the average area spanned by the other two dimensions.
24 * **mask** (*str*) - ("*") Arbitrary number of masks for atom selection; a dataset is created and the output will contain entries for each mask.. Default: all atoms.
25 * **delta** (*float*) - (0.25) Resolution, i.e. determines number of slices (i.e. histogram bins).
26 * **axis** (*str*) - ("z") Coordinate (axis) for density calculation. Vales: x, y, z.
27 * **bintype** (*str*) - ("bincenter") Determine whether histogram bin coordinates will be based on bin center (default) or bin edges. Values: bicenter, binedge.
28 * **restrict** (*str*) - (None) If specified, only calculate the density within a cylinder or square shape from the specified axis as defined by a distance cutoff. Values: cylinder, square.
29 * **cutoff** (*float*) - (None) The distance cutoff for 'restrict'. Required if 'restrict' is specified.
30 * **binary_path** (*str*) - ("cpptraj") Path to the cpptraj executable binary.
31 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
32 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
33 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
34 * **container_path** (*str*) - (None) Container path definition.
35 * **container_image** (*str*) - ('afandiadib/ambertools:serial') Container image definition.
36 * **container_volume_path** (*str*) - ('/tmp') Container volume path 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_mem.ambertools.cpptraj_density import cpptraj_density
44 prop = {
45 'density_type': 'number'
46 }
47 cpptraj_density(input_top_path='/path/to/myTopology.top',
48 input_traj_path='/path/to/myTrajectory.xtc',
49 output_cpptraj_path='/path/to/newAnalysis.dat',
50 properties=prop)
52 Info:
53 * wrapped_software:
54 * name: Ambertools Cpptraj
55 * version: >=22.5
56 * license: GNU
57 * ontology:
58 * name: EDAM
59 * schema: http://edamontology.org/EDAM.owl
61 """
63 def __init__(self, input_top_path: str, input_traj_path: str, output_cpptraj_path: str,
64 output_traj_path: str | None = None, properties: dict | None = None, **kwargs) -> None:
65 super().__init__(**locals())
67 # Properties specific for BB
68 self.instructions_file = 'instructions.in'
69 self.slice = f' {self.start} {self.end} {self.steps}'
71 def create_instructions_file(self, stage_io_dict, out_log, err_log):
72 """Creates an input file using the properties file settings."""
73 instructions_list = []
74 instructions_file_name = PurePath(self.instructions_file).name
75 # The instructions file in the sandbox, where cpptraj runs
76 unique_dir = stage_io_dict.get("unique_dir", "")
77 self.instructions_file = str(Path(unique_dir).joinpath(instructions_file_name))
79 instructions_list.append('parm ' + stage_io_dict["in"]["input_top_path"])
80 instructions_list.append('trajin ' + stage_io_dict["in"]["input_traj_path"] + self.slice)
81 density_command = f'density {self.density_type} out {stage_io_dict["out"]["output_cpptraj_path"]} {self.mask} delta {self.delta} {self.axis} {self.bintype}'
82 if self.restrict:
83 density_command += f' restrict {self.restrict}'
84 if self.cutoff:
85 density_command += f' cutoff {self.cutoff}'
86 instructions_list.append(density_command)
88 # trajout
89 if stage_io_dict["out"].get("output_traj_path"):
90 instructions_list.append('trajout ' + stage_io_dict["out"]["output_traj_path"])
92 # Create .in file
93 with open(self.instructions_file, 'w') as mdp:
94 for line in instructions_list:
95 mdp.write(line.strip() + '\n')
97 return self.instructions_file
99 def run(self) -> None:
100 """Execute the :class:`CpptrajDensity <ambertools.cpptraj_density.CpptrajDensity>` object."""
102 # create instructions file
103 self.create_instructions_file(self.stage_io_dict, self.out_log, self.err_log)
104 # create cmd and launch execution
105 self.cmd = [self.binary_path, '-i', self.staged_path(self.instructions_file)]
106 # Run Biobb block
107 self.run_biobb()
110cpptraj_density = launcher(CpptrajDensity)
112if __name__ == '__main__':
113 CpptrajDensity.main()