Coverage for biobb_io/api/pdb_variants.py: 82%

67 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-07 10:41 +0000

1#!/usr/bin/env python 

2 

3"""PdbVariants Module""" 

4import re 

5import argparse 

6import requests 

7from biobb_common.generic.biobb_object import BiobbObject 

8from biobb_common.configuration import settings 

9from biobb_common.tools import file_utils as fu 

10from biobb_common.tools.file_utils import launchlogger 

11from biobb_io.api.common import check_mandatory_property, check_output_path, get_uniprot, get_variants 

12 

13 

14class PdbVariants(BiobbObject): 

15 """ 

16 | biobb_io PdbVariants 

17 | This class creates a text file containing a list of all the variants mapped to a PDB code from the corresponding UNIPROT entries. 

18 | Wrapper for the `UNIPROT <http://www.uniprot.org/>`_ mirror of the `MMB group REST API <http://mmb.irbbarcelona.org/api/>`_ for creating a list of all the variants mapped to a PDB code from the corresponding UNIPROT entries. 

19 

20 Args: 

21 output_mutations_list_txt (str): Path to the TXT file containing an ASCII comma separated values of the mutations. File type: output. `Sample file <https://github.com/bioexcel/biobb_io/raw/master/biobb_io/test/reference/api/output_pdb_variants.txt>`_. Accepted formats: txt (edam:format_2330). 

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

23 * **pdb_code** (*str*) - (None) RSCB PDB four letter code. 

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

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

26 

27 Examples: 

28 This is a use example of how to use the PdbVariants module from Python 

29 

30 from biobb_io.api.pdb_variants import pdb_variants 

31 prop = { 

32 'pdb_code': '2VGB' 

33 } 

34 pdb_variants(output_mutations_list_txt='/path/to/newMutationsList.txt', 

35 properties=prop) 

36 

37 Info: 

38 * wrapped_software: 

39 * name: UNIPROT 

40 * license: Creative Commons 

41 * ontology: 

42 * name: EDAM 

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

44 

45 """ 

46 

47 def __init__(self, output_mutations_list_txt, 

48 properties=None, **kwargs) -> None: 

49 properties = properties or {} 

50 

51 # Call parent class constructor 

52 super().__init__(properties) 

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

54 

55 # Input/Output files 

56 self.io_dict = { 

57 "out": {"output_mutations_list_txt": output_mutations_list_txt} 

58 } 

59 

60 # Properties specific for BB 

61 self.pdb_code = properties.get('pdb_code', None) 

62 self.properties = properties 

63 

64 # Check the properties 

65 self.check_properties(properties) 

66 self.check_arguments() 

67 

68 def check_data_params(self, out_log, err_log): 

69 """ Checks all the input/output paths and parameters """ 

70 self.output_mutations_list_txt = check_output_path(self.io_dict["out"]["output_mutations_list_txt"], "output_mutations_list_txt", False, out_log, self.__class__.__name__) 

71 

72 @launchlogger 

73 def launch(self) -> int: 

74 """Execute the :class:`PdbVariants <api.pdb_variants.PdbVariants>` api.pdb_variants.PdbVariants object.""" 

75 

76 # check input/output paths and parameters 

77 self.check_data_params(self.out_log, self.err_log) 

78 

79 # Setup Biobb 

80 if self.check_restart(): 

81 return 0 

82 

83 check_mandatory_property(self.pdb_code, 'pdb_code', self.out_log, self.__class__.__name__) 

84 

85 self.pdb_code = self.pdb_code.strip().lower() 

86 

87 url = 'http://mmb.irbbarcelona.org/api' 

88 uniprot_id = get_uniprot(self.pdb_code, url, self.out_log, self.global_log) 

89 url_mapPDBRes = (url+"/uniprot/"+uniprot_id+"/mapPDBRes?pdbId="+self.pdb_code) 

90 pattern = re.compile((r"p.(?P<wt>[a-zA-Z]{3})(?P<resnum>\d+)(?P<mt>[a-zA-Z]{3})")) 

91 

92 fu.log('Fetching variants for uniprot_id: %s and pdb_code: %s' % (uniprot_id, self.pdb_code), self.out_log, self.global_log) 

93 unfiltered_dic = requests.get(url_mapPDBRes, verify=False).json() 

94 if not unfiltered_dic: 

95 fu.log("No mutation found", self.out_log, self.global_log) 

96 return None 

97 

98 mapdic = requests.get(url_mapPDBRes, verify=False).json() 

99 mutations = [] 

100 uniprot_var_list = get_variants(uniprot_id, url, self.out_log, self.global_log) 

101 for var in uniprot_var_list: 

102 uni_mut = pattern.match(var).groupdict() 

103 for k in mapdic.keys(): 

104 for fragment in mapdic[k]: 

105 if int(fragment['unp_start']) <= int(uni_mut['resnum']) <= int(fragment['unp_end']): 

106 resnum = int(uni_mut['resnum']) + int(fragment['pdb_start']) - int(fragment['unp_start']) 

107 mutations.append(k[-1]+'.'+uni_mut['wt']+str(resnum)+uni_mut['mt']) 

108 

109 fu.log('Found %d mutations mapped to PDB: %s' % (len(mutations), self.pdb_code), self.out_log, self.global_log) 

110 fu.log('Writting mutations to: %s' % self.output_mutations_list_txt, self.out_log, self.global_log) 

111 

112 with open(self.output_mutations_list_txt, 'w') as mut_file: 

113 mutations.sort() 

114 mut_file.write(",".join(mutations)) 

115 

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

117 

118 return 0 

119 

120 

121def pdb_variants(output_mutations_list_txt: str, properties: dict = None, **kwargs) -> int: 

122 """Execute the :class:`PdbVariants <api.pdb_variants.PdbVariants>` class and 

123 execute the :meth:`launch() <api.pdb_variants.PdbVariants.launch>` method.""" 

124 

125 return PdbVariants(output_mutations_list_txt=output_mutations_list_txt, 

126 properties=properties, **kwargs).launch() 

127 

128 

129def main(): 

130 """Command line execution of this building block. Please check the command line documentation.""" 

131 parser = argparse.ArgumentParser(description="Wrapper for the UNIPROT (http://www.uniprot.org/) mirror of the MMB group REST API (http://mmb.irbbarcelona.org/api/) for creating a list of all the variants mapped to a PDB code from the corresponding UNIPROT entries.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

132 parser.add_argument('-c', '--config', required=False, help="This file can be a YAML file, JSON file or JSON string") 

133 

134 # Specific args of each building block 

135 required_args = parser.add_argument_group('required arguments') 

136 required_args.add_argument('-o', '--output_mutations_list_txt', required=True, help="Path to the TXT file containing an ASCII comma separated values of the mutations. Accepted formats: txt.") 

137 

138 args = parser.parse_args() 

139 config = args.config if args.config else None 

140 properties = settings.ConfReader(config=config).get_prop_dic() 

141 

142 # Specific call of each building block 

143 pdb_variants(output_mutations_list_txt=args.output_mutations_list_txt, 

144 properties=properties) 

145 

146 

147if __name__ == '__main__': 

148 main()