import_igc_data.py 6.83 KB
Newer Older
1
#!/usr/bin/env python
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
2
3
import argparse
import logging
4
import os
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
5
6
7
import sys
from itertools import islice

8
from bioapi import MetageneDBCatalogGeneAPI, MetageneDBCatalogTaxonomyAPI
9
from requests.exceptions import HTTPError
10
from slugify import slugify
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
11

12
13
from metagenedb.common.utils.parsers import IGCLineParser

14
logging.basicConfig(format='[%(asctime)s] %(levelname)s:%(name)s:%(message)s')
15
logger = logging.getLogger()
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
16

17

18
19
class ImportIGCGenes(object):
    METAGENEDB_GENE_API = MetageneDBCatalogGeneAPI
20
21
22
23
24
    METAGENEDB_TAXONOMY_API = MetageneDBCatalogTaxonomyAPI

    PHYLUM_COL = 'taxo_phylum'
    GENUS_COL = 'taxo_genus'
    SELECTED_KEYS = ['gene_id', 'length', 'kegg_ko', PHYLUM_COL, GENUS_COL]
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
25

26
27
28
29
    def __init__(self, annotation_file, url, skip_tax=False, skip_functions=False):
        self.annotation_file = annotation_file
        self.url = url
        self.metagenedb_gene_api = self.METAGENEDB_GENE_API(base_url=self.url)
30
        self.metagenedb_taxonomy_api = self.METAGENEDB_TAXONOMY_API(base_url=self.url)
31
32
        self.total_genes = self._get_number_genes()
        self._reset_counters()
33
34
35
        # Skip some insertion if specified in script options
        self.skip_tax = skip_tax
        self.skip_functions = skip_functions
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
36

37
38
    def _build_taxo_mapping(self, rank, page_size=1000):
        logger.info("Building local mapping for %s level...", rank)
39
40
41
42
        counter = 1
        next_page = None
        mapping = {}
        while counter == 1 or next_page is not None:
43
44
45
46
47
48
            params = {
                'page': counter,
                'page_size': page_size,
                'rank': rank,
            }
            current_page = self.metagenedb_taxonomy_api.get_all(params=params)
49
50
51
52
53
54
55
            next_page = current_page['next']
            mapping.update({
                value['name']: value['tax_id'] for value in current_page['results']
            })
            counter += 1
        return mapping

56
57
58
    def build_mapping(self, page_size=1000):
        self.phylum_mapping = self._build_taxo_mapping("phylum", page_size=page_size)
        self.genus_mapping = self._build_taxo_mapping("genus", page_size=page_size)
59

60
61
62
63
64
    def _reset_counters(self):
        self.processed_genes = 0
        self.created_genes = 0
        self.updated_genes = 0
        self.skipped_genes = 0
65

66
67
68
69
70
71
72
73
74
    def _get_number_genes(self):
        if not os.path.isfile(self.annotation_file):
            return 0
        with open(self.annotation_file) as f:
            for i, l in enumerate(f):
                pass
        return i + 1

    def _select_taxonomy(self, gene_dict, unknown_val='unknown'):
75
76
77
78
        """
        Select the taxonomy to be assigned for the gene.
        genus has priority on phylum. If both unknow, remove the taxonomy key
        """
79
80
        phylum = gene_dict.pop(self.PHYLUM_COL)
        genus = gene_dict.pop(self.GENUS_COL)
81
82
        if self.skip_tax:
            return gene_dict
83
        taxonomy_id = None
84
        if genus != unknown_val:
85
86
87
            taxonomy_id = self.genus_mapping.get(genus, None)
            if taxonomy_id is None:
                logger.warning("No tax_id found for genus %s" % genus)
88
        elif phylum != unknown_val:
89
90
91
92
93
            taxonomy_id = self.phylum_mapping.get(phylum, None)
            if taxonomy_id is None:
                logger.warning("No tax_id found for phylum %s" % genus)
        if taxonomy_id is not None:
            gene_dict.update({'taxonomy': taxonomy_id})
94
95
96
97
98
99
100
101
102
103
        return gene_dict

    def _parse_gene(self, raw_line, selected_keys=SELECTED_KEYS):
        """
        Use IGCLineParser and return selected keys
        """
        gene_parser = IGCLineParser()
        all_dict = gene_parser.gene(raw_line)
        selected_dict = {k: v for k, v in all_dict.items() if k in selected_keys}
        return selected_dict
104

105
    def _clean_gene(self, gene_dict):
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
106
        gene_dict['gene_name'] = gene_dict['gene_id']
107
        gene_dict['gene_id'] = slugify(gene_dict['gene_id'])
108
        gene_dict['functions'] = gene_dict.pop('kegg_ko')
109
        gene_dict = self._select_taxonomy(gene_dict)
110
        if self.skip_functions or 'unknown' in gene_dict['functions']:
111
112
113
            gene_dict.pop('functions')
        return gene_dict

114
    def load_annotation_file_to_db_in_chunks(self, chunk_size=1000, test=False):
115
        # Build mapping for different phylum and genus
116
117
        if not self.skip_tax:
            self.build_mapping()
118
119
120
121
122
        with open(self.annotation_file, 'r') as file:
            while True:
                chunk_genes = list(islice(file, chunk_size))
                if not chunk_genes:
                    break
123
                genes = [self._clean_gene(self._parse_gene(i)) for i in chunk_genes]
124
125
126
127
128
129
                try:
                    response = self.metagenedb_gene_api.put(genes)
                    self.created_genes += response.get('created').get('count')
                    self.updated_genes += response.get('updated').get('count')
                except HTTPError as http_error:
                    logging.warning("%s: %s; %s", http_error, http_error.response.json(), genes)
130
                    self.skipped_genes += len(genes)
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
131
                self.processed_genes += len(chunk_genes)
132
                logger.info("%s Genes processed so far...", self.processed_genes)
133
134
                if test is True:
                    break
135
136
137
        logger.info("[DONE] %s/%s Genes created.", self.created_genes, self.total_genes)
        logger.info("[DONE] %s/%s Genes updated.", self.updated_genes, self.total_genes)
        logger.info("[DONE] %s/%s Genes skipped.", self.skipped_genes, self.total_genes)
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
138
139
140
141
142
143
144
145
146


def parse_arguments():
    """
    Defines parser.
    """
    parser = argparse.ArgumentParser(description='Populate database from a given IGC annotation file.')
    # Common arguments for analysis and annotations
    parser.add_argument('annotation', help='IGC annotation file')
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
147
    parser.add_argument('--url', help='base URL of the instance.', default='http://localhost/')
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
148
149
    parser.add_argument('--chunk_size', type=int, default=1000,
                        help='How many genes to handle and create in the same time.')
150
151
    parser.add_argument('--skip_taxonomy', action='store_true', help='Skip taxonomy information from genes.')
    parser.add_argument('--skip_functions', action='store_true', help='Skip functions information from genes.')
152
    parser.add_argument('--test', action='store_true', help='Run only on first chunk.')
153
    parser.add_argument('-v', '--verbose', action='store_true')
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
154
155
156
157
158
159
160
161
162

    try:
        return parser.parse_args()
    except SystemExit:
        sys.exit(1)


def run():
    args = parse_arguments()
163
164
    if args.verbose:
        logger.setLevel(logging.INFO)
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
165
166
    import_igc_genes = ImportIGCGenes(args.annotation, args.url,
                                      skip_tax=args.skip_taxonomy, skip_functions=args.skip_functions)
167
    import_igc_genes.load_annotation_file_to_db_in_chunks(chunk_size=args.chunk_size, test=args.test)
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
168
169
170
171


if __name__ == "__main__":
    run()