Coverage for biobb_structure_utils/utils/renumber_structure.py: 86%
87 statements
« prev ^ index » next coverage.py v7.5.3, created at 2024-06-14 19:03 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2024-06-14 19:03 +0000
1#!/usr/bin/env python3
3"""Module containing the RenumberStructure class and the command line interface."""
4import json
5import argparse
6from pathlib import Path
7from biobb_common.configuration import settings
8from biobb_common.generic.biobb_object import BiobbObject
9from biobb_common.tools import file_utils as fu
10from biobb_common.tools.file_utils import launchlogger
11from biobb_structure_utils.gro_lib.gro import Gro
12from biobb_structure_utils.utils.common import PDB_SERIAL_RECORDS
15class RenumberStructure(BiobbObject):
16 """
17 | biobb_structure_utils RenumberStructure
18 | Class to renumber atomic indexes from a 3D structure.
19 | Renumber atomic indexes from a 3D structure.
21 Args:
22 input_structure_path (str): Input structure file path. File type: input. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/data/utils/cl3.noH.pdb>`_. Accepted formats: pdb (edam:format_1476), gro (edam:format_2033).
23 output_structure_path (str): Output structure file path. File type: output. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/reference/utils/renum_cl3_noH.pdb>`_. Accepted formats: pdb (edam:format_1476), gro (edam:format_2033).
24 output_mapping_json_path (str): Output mapping json file path. File type: output. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/reference/utils/cl3_output_mapping_json_path.json>`_. Accepted formats: json (edam:format_3464).
25 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
26 * **renumber_residues** (*bool*) - (True) Residue code of the ligand to be removed.
27 * **renumber_residues_per_chain** (*bool*) - (True) Restart residue enumeration every time a new chain is detected.
28 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
29 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
30 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
32 Examples:
33 This is a use example of how to use the building block from Python::
35 from biobb_structure_utils.utils.renumber_structure import renumber_structure
36 prop = {
37 'renumber_residues': True,
38 'renumber_residues_per_chain': True
39 }
40 renumber_structure(input_structure_path='/path/to/myInputStr.pdb',
41 output_structure_path='/path/to/newStructure.pdb',
42 output_mapping_json_path='/path/to/newMapping.json',
43 properties=prop)
45 Info:
46 * wrapped_software:
47 * name: In house
48 * license: Apache-2.0
49 * ontology:
50 * name: EDAM
51 * schema: http://edamontology.org/EDAM.owl
53 """
55 def __init__(self, input_structure_path, output_structure_path, output_mapping_json_path, properties=None, **kwargs) -> None:
56 properties = properties or {}
58 # Call parent class constructor
59 super().__init__(properties)
60 self.locals_var_dict = locals().copy()
62 # Input/Output files
63 self.io_dict = {
64 "in": {"input_structure_path": input_structure_path},
65 "out": {"output_structure_path": output_structure_path,
66 "output_mapping_json_path": output_mapping_json_path}
67 }
69 # Properties specific for BB
70 self.renumber_residues = properties.get('renumber_residues', True)
71 self.renumber_residues_per_chain = properties.get('renumber_residues_per_chain', True)
73 # Common in all BB
74 self.can_write_console_log = properties.get('can_write_console_log', True)
75 self.global_log = properties.get('global_log', None)
76 self.prefix = properties.get('prefix', None)
77 self.step = properties.get('step', None)
78 self.path = properties.get('path', '')
79 self.remove_tmp = properties.get('remove_tmp', True)
80 self.restart = properties.get('restart', False)
82 # Check the properties
83 self.check_properties(properties)
84 self.check_arguments()
86 @launchlogger
87 def launch(self) -> int:
88 """Execute the :class:`RenumberStructure <utils.renumber_structure.RenumberStructure>` utils.renumber_structure.RenumberStructure object."""
90 # Setup Biobb
91 if self.check_restart():
92 return 0
93 self.stage_files()
95 # Business code
96 extension = Path(self.stage_io_dict['in']['input_structure_path']).suffix.lower()
97 if extension.lower() == '.gro':
98 fu.log('GRO format detected, reenumerating atoms', self.out_log)
99 gro_st = Gro()
100 gro_st.read_gro_file(self.stage_io_dict['in']['input_structure_path'])
101 residue_mapping, atom_mapping = gro_st.renumber_atoms(renumber_residues=self.renumber_residues, renumber_residues_per_chain=self.renumber_residues_per_chain)
102 gro_st.write_gro_file(self.stage_io_dict['out']['output_structure_path'])
104 else:
105 fu.log('PDB format detected, reenumerating atoms', self.out_log)
106 atom_mapping = {}
107 atom_count = 0
108 residue_mapping = {}
109 residue_count = 0
110 with open(self.stage_io_dict['in']['input_structure_path'], "r") as input_pdb, open(self.stage_io_dict['out']['output_structure_path'], "w") as output_pdb:
111 for line in input_pdb:
112 record = line[:6].upper().strip()
113 if len(line) > 10 and record in PDB_SERIAL_RECORDS: # Avoid MODEL, ENDMDL records and empty lines
114 # Renumbering atoms
115 pdb_atom_number = line[6:11].strip()
116 if not atom_mapping.get(pdb_atom_number): # ANISOU records should have the same numeration as ATOM records
117 atom_count += 1
118 atom_mapping[pdb_atom_number] = str(atom_count)
119 line = line[:6]+'{: >5d}'.format(atom_count)+line[11:]
120 # Renumbering residues
121 if self.renumber_residues:
122 chain = line[21]
123 pdb_residue_number = line[22:26].strip()
124 if not residue_mapping.get(chain):
125 residue_mapping[chain] = {}
126 if self.renumber_residues_per_chain:
127 residue_count = 0
128 if not residue_mapping[chain].get(pdb_residue_number):
129 residue_count += 1
130 residue_mapping[chain][pdb_residue_number] = str(residue_count)
131 line = line[:22] + '{: >4d}'.format(residue_count) + line[26:]
132 output_pdb.write(line)
134 with open(self.stage_io_dict['out']['output_mapping_json_path'], "w") as output_json:
135 output_json.write(json.dumps({'residues': residue_mapping, 'atoms': atom_mapping}))
137 self.return_code = 0
138 ##########
140 # Copy files to host
141 self.copy_to_host()
143 # Remove temporal files
144 self.tmp_files.append(self.stage_io_dict.get("unique_dir"))
145 self.remove_tmp_files()
147 self.check_arguments(output_files_created=True, raise_exception=False)
149 return self.return_code
152def renumber_structure(input_structure_path: str, output_structure_path: str, output_mapping_json_path: str, properties: dict = None, **kwargs) -> int:
153 """Execute the :class:`RenumberStructure <utils.renumber_structure.RenumberStructure>` class and
154 execute the :meth:`launch() <utils.renumber_structure.RenumberStructure.launch>` method."""
156 return RenumberStructure(input_structure_path=input_structure_path,
157 output_structure_path=output_structure_path,
158 output_mapping_json_path=output_mapping_json_path,
159 properties=properties, **kwargs).launch()
162def main():
163 """Command line execution of this building block. Please check the command line documentation."""
164 parser = argparse.ArgumentParser(description="Renumber atoms and residues from a 3D structure.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
165 parser.add_argument('-c', '--config', required=False, help="This file can be a YAML file, JSON file or JSON string")
167 # Specific args of each building block
168 required_args = parser.add_argument_group('required arguments')
169 required_args.add_argument('-i', '--input_structure_path', required=True, help="Input structure file name")
170 required_args.add_argument('-o', '--output_structure_path', required=True, help="Output structure file name")
171 required_args.add_argument('-j', '--output_mapping_json_path', required=True, help="Output mapping json file name")
173 args = parser.parse_args()
174 config = args.config if args.config else None
175 properties = settings.ConfReader(config=config).get_prop_dic()
177 # Specific call of each building block
178 renumber_structure(input_structure_path=args.input_structure_path,
179 output_structure_path=args.output_structure_path,
180 output_mapping_json_path=args.output_mapping_json_path,
181 properties=properties)
184if __name__ == '__main__':
185 main()