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

import django
9
from rest_framework.exceptions import ValidationError
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
10

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

Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
13
14
15
16
# Before model import, we need to called django.setup() to Load apps
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "metagenedb.settings")
django.setup()

Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
17
from metagenedb.apps.catalog.models import Gene, Function  # noqa
18
from metagenedb.apps.catalog.serializers import GeneSerializer  # noqa
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
19
20
21
22

logging.basicConfig(level=logging.INFO)
_LOGGER = logging.getLogger(__name__)

23
24
SELECTED_KEYS = ['gene_id', 'gene_length', 'kegg_ko']

Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
25

26
def parse_gene(raw_line, selected_keys=SELECTED_KEYS):
27
    """
28
    Use IGCLineParser and return selected keys
29
    """
30
31
32
33
    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
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
34
35


36
37
38
39
40
41
42
43
44
45
def upsert_gene(gene_dict):
    try:
        gene_obj = Gene.objects.get(gene_id=gene_dict.get('gene_id'))
        serializer = GeneSerializer(gene_obj, data=gene_dict)
    except Gene.DoesNotExist:
        serializer = GeneSerializer(data=gene_dict)
    serializer.is_valid(raise_exception=True)
    serializer.save()


Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
46
def insert_gene_list(chunk_genes):
47
    for gene_line in chunk_genes:
48
        gene_dict = parse_gene(gene_line)
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
49
        try:
50
            upsert_gene(gene_dict)
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
51
        except ValidationError as e:
52
            _LOGGER.warning(f"{e.__dict__} for gene_id: {gene_dict.get('gene_id')}. Insertion skipped.")
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
53
54
55


def load_annotation_file_to_db_in_chunks(annotation_file, chunk_size=100000):
56
    processed_genes = 0
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
57
58
59
60
61
    with open(annotation_file, 'r') as file:
        while True:
            chunk_genes = list(islice(file, chunk_size))
            if not chunk_genes:
                break
62
            processed_genes += len(chunk_genes)
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
63
            insert_gene_list(chunk_genes)
64
65
            _LOGGER.info(f"{processed_genes} genes processed so far...")
    _LOGGER.info(f"[DONE] {processed_genes} genes processed.")
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


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')
    parser.add_argument('--delete_all', action='store_true', help='Empty database before insertion.')

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


def run():
    args = parse_arguments()
    if args.delete_all:
        Gene.objects.all().delete()
    load_annotation_file_to_db_in_chunks(args.annotation)


if __name__ == "__main__":
    run()