aboutsummaryrefslogtreecommitdiff
path: root/workflows/pull-data/genbank/genbank.py
blob: 314f50d0160799dcfdcd4d67ffcfc73e75c325c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# Genbank XML parser

from collections import namedtuple
import dateutil
from dateutil.parser import parse as dateparse
from dateutil.tz import gettz
import os
import re
import sys
import types
import xml.etree.ElementTree as ET

class GBError(Exception):
    pass

"""
Example of an output JSON:

{
  "id": "placeholder",
  "host": {
    "host_species": "http://purl.obolibrary.org/obo/NCBITaxon_9606"
  },
  "sample": {
    "sample_id": "MT890462.1",
    "source_database_accession": [
      "http://identifiers.org/insdc/MT890462.1#sequence"
    ],
    "collection_location": "http://www.wikidata.org/entity/Q649",
    "collection_date": "2020-04-17",
    "collecting_institution": "N.A.Kovtun Clinical Hospital 1 of Departament of President Affairs"
  },
  "virus": {
    "virus_strain": "SARS-CoV-2/human/RUS/20200417_10/2020",
    "virus_species": "http://purl.obolibrary.org/obo/NCBITaxon_2697049"
  },
  "technology": {
    "assembly_method": "http://purl.obolibrary.org/obo/GENEPIO_0001628",
    "alignment_protocol": "bowtie2 v. 2.3.4",
    "sample_sequencing_technology": [
      "http://purl.obolibrary.org/obo/OBI_0000759"
    ]
  },
  "submitter": {
    "authors": [
      "Blagodatskikh,K.A."
    ],
    "submitter_name": [
      "R&D"
    ],
    "submitter_address": "Pirogov Russian National Research Medical University, Ostrovityanova 1, Moscow 117997, Russia"
  }
}

Note: missing data should be None! Do not fill in other data by
'guessing'.

When data is malformed an warning should be issued.

"""

def get_metadata(id, gbseq):
    host = types.SimpleNamespace()
    sample = types.SimpleNamespace()
    submitter = types.SimpleNamespace()
    technology = types.SimpleNamespace()
    warnings = []

    def warn(msg):
        print(f"WARNING: {msg}",file=sys.stderr)
        warnings.append(msg)

    host.host_species = "http://purl.obolibrary.org/obo/NCBITaxon_9606"
    sample.sample_id = id
    sample.database = "https://www.ncbi.nlm.nih.gov/genbank/"
    sample.source_database_accession = f"http://identifiers.org/insdc/{id}#sequence"
    # <GBQualifier>
    #   <GBQualifier_name>country</GBQualifier_name>
    #   <GBQualifier_value>USA: Cruise_Ship_1, California</GBQualifier_value>
    # </GBQualifier>
    sample.collection_location = "FIXME"

    submitter.authors = [n.text for n in gbseq.findall(".//GBAuthor")]
    # <GBReference_journal>Submitted (28-OCT-2020) MDU-PHL, The Peter
    #   Doherty Institute for Infection and Immunity, 792 Elizabeth
    #   Street, Melbourne, Vic 3000, Australia
    # </GBReference_journal>
    try:
        n = gbseq.find(".//GBReference_journal").text
        # print(n,file=sys.stderr)
        if n != 'Unpublished':
            institute,address = n.split(',',1)
            submitter.submitter_name = institute.split(') ')[1]
            submitter.submitter_address = address.strip()
    except AttributeError:
        pass
    except ValueError:
        submitter.additional_submitter_information = n
        pass

    try:
        n = gbseq.find("./GBSeq_comment").text
    except AttributeError:
        pass
    if 'Assembly-Data' in n:
        # print(n,file=sys.stderr)
        # the following is wrong (de novo by default)
        # technology.assembly_method = 'http://purl.obolibrary.org/obo/GENEPIO_0001628'
        p = re.compile(r'.*Assembly Method :: ([^;]+).*')
        m = p.match(n)
        if m: technology.alignment_protocol = m.group(1)
        p = re.compile(r'.*Coverage :: ([^;]+).*')
        m = p.match(n)
        if m: technology.sequencing_coverage = m.group(1)
        p = re.compile(r'.*Sequencing Technology :: ([^;]+).*')
        m = p.match(n)
        if m: technology.sample_sequencing_technology = m.group(1).strip()

    # --- Dates
    n = gbseq.find("./GBSeq_create-date")
    creation_date = dateparse(n.text).date()
    n = gbseq.find("./GBSeq_update-date")
    update_date = dateparse(n.text).date()
    n = gbseq.find(".//GBQualifier/GBQualifier_name/[.='collection_date']/../GBQualifier_value")
    try:
        date = dateparse(n.text).date()
        sample.collection_date = str(date)
    except dateutil.parser._parser.ParserError as e:
        warn("No collection_date: ",str(e))
        sample.collection_date = None
    except AttributeError:
        warn("Missing collection_date")
        sample.collection_date = None

    info = {
        'id': 'placeholder',
        'update_date': str(update_date),
        'host': host,
        'sample': sample,
        #'virus': virus,
        'technology': technology,
        'submitter': submitter,
        'warnings': warnings,
        }
    print(info)
    return True,info

def get_sequence(id, gbseq):
    seq = None
    count = 0
    for gbseq_sequence in gbseq.findall('./GBSeq_sequence'):
        count += 1
        if count > 1:
            raise GBError(f"Expected one sequence for {id}")
        seq = gbseq_sequence.text.upper()
        print(f"SEQ: size={len(seq)}",seq[0:30])
        if len(seq) < 20_000:
            raise GBError(f"Sequence too short")
        return seq