Coverage for biobb_structure_utils / utils / extract_model.py: 87%

63 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2025-12-16 14:59 +0000

1#!/usr/bin/env python3 

2 

3"""Module containing the ExtractModel class and the command line interface.""" 

4import shutil 

5from typing import Optional 

6from biobb_common.generic.biobb_object import BiobbObject 

7from biobb_common.tools import file_utils as fu 

8from biobb_common.tools.file_utils import launchlogger 

9 

10from biobb_structure_utils.utils.common import check_input_path, check_output_path 

11 

12 

13class ExtractModel(BiobbObject): 

14 """ 

15 | biobb_structure_utils ExtractModel 

16 | This class is a wrapper of the Structure Checking tool to extract a model from a 3D structure. 

17 | Wrapper for the `Structure Checking <https://github.com/bioexcel/biobb_structure_checking>`_ tool to extract a model from a 3D structure. 

18 

19 Args: 

20 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/extract_model.pdb>`_. Accepted formats: pdb (edam:format_1476), pdbqt (edam:format_1476). 

21 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/ref_extract_model.pdb>`_. Accepted formats: pdb (edam:format_1476), pdbqt (edam:format_1476). 

22 properties (dic - Python dictionary object containing the tool parameters, not input/output files): 

23 * **models** (*list*) - (None) List of models to be extracted from the input_structure_path file. If empty, all the models of the structure will be returned. 

24 * **binary_path** (*string*) - ("check_structure") path to the check_structure application 

25 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files. 

26 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist. 

27 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

28 

29 Examples: 

30 This is a use example of how to use the building block from Python:: 

31 

32 from biobb_structure_utils.utils.extract_model import extract_model 

33 prop = { 

34 'models': [ 1, 2, 3 ] 

35 } 

36 extract_model(input_structure_path='/path/to/myStructure.pdb', 

37 output_structure_path='/path/to/newStructure.pdb', 

38 properties=prop) 

39 

40 Info: 

41 * wrapped_software: 

42 * name: Structure Checking from MDWeb 

43 * version: >=3.0.3 

44 * license: Apache-2.0 

45 * ontology: 

46 * name: EDAM 

47 * schema: http://edamontology.org/EDAM.owl 

48 

49 """ 

50 

51 def __init__( 

52 self, input_structure_path, output_structure_path, properties=None, **kwargs 

53 ) -> None: 

54 properties = properties or {} 

55 

56 # Call parent class constructor 

57 super().__init__(properties) 

58 self.locals_var_dict = locals().copy() 

59 

60 # Input/Output files 

61 self.io_dict = { 

62 "in": {"input_structure_path": input_structure_path}, 

63 "out": {"output_structure_path": output_structure_path}, 

64 } 

65 

66 # Properties specific for BB 

67 self.binary_path = properties.get("binary_path", "check_structure") 

68 self.models = properties.get("models", []) 

69 self.properties = properties 

70 

71 # Check the properties 

72 self.check_properties(properties) 

73 self.check_arguments() 

74 

75 @launchlogger 

76 def launch(self) -> int: 

77 """Execute the :class:`ExtractModel <utils.extract_model.ExtractModel>` utils.extract_model.ExtractModel object.""" 

78 

79 self.io_dict["in"]["input_structure_path"] = check_input_path( 

80 self.io_dict["in"]["input_structure_path"], 

81 self.out_log, 

82 self.__class__.__name__, 

83 ) 

84 self.io_dict["out"]["output_structure_path"] = check_output_path( 

85 self.io_dict["out"]["output_structure_path"], 

86 self.out_log, 

87 self.__class__.__name__, 

88 ) 

89 

90 # Setup Biobb 

91 if self.check_restart(): 

92 return 0 

93 self.stage_files() 

94 

95 # check if user has passed models properly 

96 models = check_format_models(self.models, self.out_log) 

97 

98 if models == "All": 

99 shutil.copyfile( 

100 self.io_dict["in"]["input_structure_path"], 

101 self.io_dict["out"]["output_structure_path"], 

102 ) 

103 

104 return 0 

105 else: 

106 # create temporary folder 

107 tmp_folder = fu.create_unique_dir() 

108 fu.log("Creating %s temporary folder" % tmp_folder, self.out_log) 

109 

110 filenames = [] 

111 

112 for model in models: 

113 tmp_file = tmp_folder + "/model" + str(model) + ".pdb" 

114 

115 self.cmd = [ 

116 self.binary_path, 

117 "-i", 

118 self.stage_io_dict["in"]["input_structure_path"], 

119 "-o", 

120 tmp_file, 

121 "--force_save", 

122 "models", 

123 "--select", 

124 str(model), 

125 ] 

126 

127 # Run Biobb block 

128 self.run_biobb() 

129 

130 filenames.append(tmp_file) 

131 

132 # concat tmp_file and save them into output file 

133 with open(self.io_dict["out"]["output_structure_path"], "w") as outfile: 

134 for i, fname in enumerate(filenames): 

135 with open(fname) as infile: 

136 outfile.write("MODEL " + "{:>4}".format(str(i + 1)) + "\n") 

137 for line in infile: 

138 if not line.startswith("END"): 

139 outfile.write(line) 

140 else: 

141 outfile.write("ENDMDL\n") 

142 

143 # Copy files to host 

144 self.copy_to_host() 

145 

146 # Remove temporal files 

147 self.tmp_files.extend([ 

148 tmp_folder 

149 ]) 

150 self.remove_tmp_files() 

151 

152 self.check_arguments(output_files_created=True, raise_exception=False) 

153 

154 return self.return_code 

155 

156 

157def check_format_models(models, out_log): 

158 """Check format of models list""" 

159 if not models: 

160 fu.log("Empty models parameter, all models will be returned.", out_log) 

161 return "All" 

162 

163 if not isinstance(models, list): 

164 fu.log( 

165 "Incorrect format of models parameter, all models will be returned.", 

166 out_log, 

167 ) 

168 return "All" 

169 

170 return models 

171 

172 

173def extract_model( 

174 input_structure_path: str, 

175 output_structure_path: str, 

176 properties: Optional[dict] = None, 

177 **kwargs, 

178) -> int: 

179 """Create the :class:`ExtractModel <utils.extract_model.ExtractModel>` class and 

180 execute the :meth:`launch() <utils.extract_model.ExtractModel.launch>` method.""" 

181 return ExtractModel(**dict(locals())).launch() 

182 

183 

184extract_model.__doc__ = ExtractModel.__doc__ 

185main = ExtractModel.get_main(extract_model, "Extract a model from a 3D structure.") 

186 

187if __name__ == "__main__": 

188 main()