orange-bioinformatics / _bioinformatics / obiKEGG / databases.py

  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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
"""
DBGET Database Interface
========================

"""
from __future__ import absolute_import

import re
from contextlib import closing

from . import entry
from .entry import fields
from . import api


def iter_take(source_iter, n):
    """
    Return a list of the first `n` items in `source_iter`.
    """
    source_iter = iter(source_iter)
    return [item for _, item in zip(range(n), source_iter)]


def batch_iter(source_iter, n):
    """
    Split the `source_iter` into batches of size `n`.
    """
    source_iter = iter(source_iter)
    while True:
        batch = iter_take(source_iter, n)
        if batch:
            yield batch
        else:
            break


def chain_iter(chains_iter):
    for iter in chains_iter:
        for element in iter:
            yield element


# TODO: DBDataBase should be able to be constructed from a flat text
# entry file. The precache etc. should be moved in caching api, that creates
# simple file system hierarchy where the flat database is saved (with db
# release string), e.g.
# genes/hsa.dbget
# genes/hsa.release
# genes/sce.dbget
# path.dbget
# module.dbget
# ligand/compound.dbget


class DBDataBase(object):
    """
    Base class for a DBGET database interface.

    """
    #: ENTRY_TYPE constructor (a :class:`~.entry.DBEntry` subclass). This
    #: should be redefined in subclasses.
    ENTRY_TYPE = entry.DBEntry

    #: A database name/abbreviation (e.g. 'pathway'). Needs to be set in a
    #: subclass or object instance's constructor before calling the base.
    #: __init__
    DB = None

    def __init__(self, **kwargs):
        if not self.DB:
            raise TypeError("Cannot make an instance of abstract base "
                            "class %r." % type(self).__name__)

        self.api = api.CachedKeggApi()
        self.info = self.api.info(self.DB)
        release = self.info.release
        self.api.set_default_release(release)
        self._keys = []

    def keys(self):
        """
        Return a list of database keys. These are unique KEGG identifiers
        that can be used to query the database.

        """
        return list(self._keys)

    def iterkeys(self):
        """
        Return an iterator over the `keys`.
        """
        return iter(self._keys)

    def items(self):
        """
        Return a list of all (key, :obj:`DBDataBase.ENTRY_TYPE` instance)
        tuples.

        """
        return list(zip(self.keys(), self.batch_get(self.keys())))

    def iteritems(self):
        """
        Return an iterator over the `items`.
        """
        batch_size = 100
        iterkeys = self.iterkeys()
        return chain_iter(zip(batch, self.batch_get(batch))
                          for batch in batch_iter(iterkeys, batch_size))

    def values(self):
        """
        Return a list of all :obj:`DBDataBase.ENTRY_TYPE` instances.
        """
        return self.batch_get(self.keys())

    def itervalues(self):
        """
        Return an iterator over all :obj:`DBDataBase.ENTRY_TYPE` instances.
        """
        batch_size = 100
        iterkeys = self.iterkeys()
        return chain_iter(self.batch_get(batch)
                          for batch in batch_iter(iterkeys, batch_size))

    def get(self, key, default=None):
        """
        Return an :obj:`DBDataBase.ENTRY_TYPE` instance for the `key`.
        Raises :class:`KeyError` if not found.

        """
        try:
            return self.__getitem__(key)
        except KeyError:
            return default

    def has_key(self, key):
        return self.__contains__(key)

    def __getitem__(self, key):
        e = self.get_entry(key)
        if e is None:
            raise KeyError(key)
        else:
            return e

    def __contains__(self, key):
        return key in set(self.keys())

    def __len__(self):
        return len(self.keys())

    def __iter__(self):
        return iter(self.keys())

    def get_text(self, key):
        """
        Return the database entry for `key` as plain text.
        """
        key = self._add_db(key)
        return self.api.get([key])

    def get_entry(self, key):
        """
        Return the database entry for `key` as an instance of `ENTRY_TYPE`.
        """
        text = self.get_text(key)
        if not text or text == "None":
            return None
        else:
            return self.ENTRY_TYPE(text)

    def find(self, name):
        """
        Find `name` using kegg `find` api.
        """
        res = self.api.find(self.DB, name).splitlines()
        return [r.split(" ", 1)[0] for r in res]

    def pre_cache(self, keys=None, batch_size=10, progress_callback=None):
        """
        Retrieve all the entries for `keys` and cache them locally for faster
        subsequent retrieval. If `keys` is ``None`` then all entries will be
        retrieved.

        """
        if not isinstance(self.api, api.CachedKeggApi):
            raise TypeError("Not an instance of api.CachedKeggApi")

        if batch_size > 10 or batch_size < 1:
            raise ValueError("Invalid batch_size")

        if keys is None:
            keys = self.keys()

        keys = map(self._add_db, keys)

        get = self.api.get

        # drop all keys with a valid cache entry to minimize the number
        # of 'get' requests.
        with closing(get.cache_store()) as store:
            def is_uncached(key):
                return not get.key_has_valid_cache(get.key_from_args((key,)),
                                                   store)
            keys = filter(is_uncached, keys)

        start = 0

        while start < len(keys):
            batch = keys[start: start + batch_size]
            self.api.get(batch)

            if progress_callback:
                progress_callback(100.0 * start / len(keys))

            start += batch_size

    def batch_get(self, keys):
        """
        Batch retrieve all entries for keys. This can be significantly
        faster then getting each entry separately especially if entries
        are not yet cached.

        """
        entries = []
        batch_size = 10
        keys = map(self._add_db, keys)

        # Precache the entries first
        self.pre_cache(keys)

        start = 0
        while start < len(keys):
            batch = keys[start: start + batch_size]
            batch_entries = self.api.get(batch)
            if batch_entries is not None:
                batch_entries = batch_entries.split("///\n")
                # Remove possible empty last line
                batch_entries = [e for e in batch_entries if e.strip()]
                entries.extend(map(self.ENTRY_TYPE, batch_entries))
            start += batch_size

        return entries

    def _add_db(self, key):
        """
        Prefix the key with '%(DB)s:' string if not already prefixed.
        """
        if not key.startswith(self.DB + ":"):
            return self.DB + ":" + key
        else:
            return key


@entry.entry_decorate
class GenomeEntry(entry.DBEntry):
    """
    Entry for a KEGG Genome database.
    """
    FIELDS = [
        ("ENTRY", fields.DBEntryField),
        ("NAME", fields.DBNameField),
        ("DEFINITION", fields.DBDefinitionField),
        ("ANNOTATION", fields.DBSimpleField),
        ("TAXONOMY", fields.DBTaxonomyField),
        ("DATA_SOURCE", fields.DBSimpleField),
        ("ORIGINAL_DB", fields.DBSimpleField),
        ("KEYWORDS", fields.DBSimpleField),
        ("DISEASE", fields.DBSimpleField),
        ("COMMENT", fields.DBSimpleField),
        ("CHROMOSOME", fields.DBFieldWithSubsections),
        ("PLASMID", fields.DBSimpleField),
        ("STATISTICS", fields.DBSimpleField),
        ("REFERENCE", fields.DBReference)
    ]

    MULTIPLE_FIELDS = ["REFERENCE"]

    def __init__(self, text):
        entry.DBEntry.__init__(self, text)

    @property
    def organism_code(self):
        """
        A three or four letter KEGG organism code (e.g. 'hsa', 'sce', ...)
        """
        return self.name.split(",", 1)[0]

    @property
    def taxid(self):
        """
        Organism NCBI taxonomy id.
        """
        return self.TAXONOMY.taxid

    def org_code(self):
        # for backwards compatibility; return the `organism_code`
        return self.organism_code


class Genome(DBDataBase):
    """
    An interface to the A KEGG GENOME database.
    """
    DB = "genome"
    ENTRY_TYPE = GenomeEntry

    # For obiTaxonomy.common_taxids mapping
    TAXID_MAP = {
        "562": "511145",   # Escherichia coli K-12 MG1655
        "2104": "272634",  # Mycoplasma pneumoniae M129
        "4530": "39947",   # Oryza sativa ssp. japonica cultivar Nipponbare (Japanese rice)
        "4932": "559292",  # Saccharomyces cerevisiae S288C
        "4896": "284812",  # Schizosaccharomyces pombe 972h-
    }

    def __init__(self):
        DBDataBase.__init__(self)
        self._org_list = self.api.list_organisms()
        self._keys = [org.entry_id for org in self._org_list]

    def _key_to_gn_entry_id(self, key):
        res = self.find(key)
        if len(res) == 0:
            raise KeyError("Unknown key")
        elif len(res) > 1:
            raise ValueError("Not a unique key")
        else:
            return res[0]

    @classmethod
    def common_organisms(cls):
        return ['ath', 'bta', 'cel', 'cre', 'dre', 'ddi',
                'dme', 'eco', 'hsa', 'mmu', 'mpn', 'osa',
                'pfa', 'rno', 'sce', 'spo', 'zma', 'xla']

    @classmethod
    def essential_organisms(cls):
        return ['ddi', 'dme', 'hsa', 'mmu', 'sce']

    def org_code_to_entry_key(self, code):
        """
        Map an organism code ('hsa', 'sce', ...) to the corresponding kegg
        identifier (T + 5 digit number).

        """
        for org in self._org_list:
            if org.org_code == code:
                return org.entry_id
        else:
            raise ValueError("Unknown organism code '%s'" % code)

    def search(self, string, relevance=False):
        """
        Search the genome database for string using ``bfind``.
        """
        if relevance:
            raise NotImplementedError("relevance is no longer supported")

        if string in self.TAXID_MAP:
            string = self.TAXID_MAP[string]

        res = self.api.find(self.DB, string).strip()
        if not res:
            return []

        res = res.splitlines()
        res = [r.split(",", 1)[0] for r in res]
        res = [r.split(None, 1)[1] for r in res]
        return res


@entry.entry_decorate
class GeneEntry(entry.DBEntry):
    FIELDS = [
        ("ENTRY", fields.DBEntryField),
        ("NAME", fields.DBNameField),
        ("DEFINITION", fields.DBDefinitionField),
        ("ORTHOLOGY", fields.DBSimpleField),
        ("ORGANISM", fields.DBSimpleField),
        ("PATHWAY", fields.DBPathway),
        ("MODULE", fields.DBSimpleField),
        ("DISEASE", fields.DBSimpleField),
        ("DRUG_TARGET", fields.DBSimpleField),
        ("CLASS", fields.DBSimpleField),
        ("MOTIF", fields.DBSimpleField),
        ("DBLINKS", fields.DBDBLinks),
        ("STRUCTURE", fields.DBSimpleField),
        ("POSITION", fields.DBSimpleField),
        ("AASEQ", fields.DBAASeq),
        ("NTSEQ", fields.DBNTSeq)
    ]

    def aliases(self):
        return [self.entry_key] + \
               (self.name.split(",") if self.name else []) + \
               ([link[1][0] for link in self.dblinks.items()]
                if self.dblinks else [])

    @property
    def alt_names(self):
        """
        For backwards compatibility.
        """
        return self.aliases()


class Genes(DBDataBase):
    """
    Interface to the KEGG Genes database.

    :param str org_code: KEGG organism code (e.g. 'hsa').

    """
    DB = None  # Needs to be set in __init__
    ENTRY_TYPE = GeneEntry

    def __init__(self, org_code):
        # TODO: Map to org code from kegg id (T + 5 digits)
        self.DB = org_code
        self.org_code = org_code
        DBDataBase.__init__(self)
        self._keys = self.api.get_genes_by_organism(org_code)

    def gene_aliases(self):
        aliases = {}
        for entry in self.itervalues():
            aliases.update(
                dict.fromkeys(entry.aliases(),
                              self.org_code + ":" + entry.entry_key)
            )

        return aliases


@entry.entry_decorate
class CompoundEntry(entry.DBEntry):
    FIELDS = [
        ("ENTRY", fields.DBEntryField),
        ("NAME", fields.DBNameField),
        ("FORMULA", fields.DBSimpleField),
        ("EXACT_MASS", fields.DBSimpleField),
        ("MOL_WEIGHT", fields.DBSimpleField),
        ("REMARK", fields.DBSimpleField),
        ("COMMENT", fields.DBSimpleField),
        ("REACTION", fields.DBSimpleField),
        ("PATHWAY", fields.DBPathway),
        ("ENZYME", fields.DBSimpleField),
        ("BRITE", fields.DBSimpleField),
        ("REFERENCE", fields.DBSimpleField),
        ("DBLINKS", fields.DBDBLinks),
        ("ATOM", fields.DBSimpleField),
        ("BOND", fields.DBSimpleField)
    ]


class Compound(DBDataBase):
    DB = "cpd"
    ENTRY_TYPE = CompoundEntry

    def __init__(self):
        DBDataBase.__init__(self)
        self._keys = [d.entry_id for d in self.api.list("cpd")]


@entry.entry_decorate
class ReactionEntry(entry.DBEntry):
    FIELDS = [
        ("ENTRY", fields.DBEntryField),
        ("NAME", fields.DBNameField),
        ("DEFINITION", fields.DBDefinitionField),
        ("EQUATION", fields.DBSimpleField),
        ("ENZYME", fields.DBSimpleField)
    ]


class Reaction(DBDataBase):
    DB = "rn"
    ENTRY_TYPE = ReactionEntry

    def __init__(self):
        DBDataBase.__init__(self)
        self._keys = [d.entry_id for d in self.api.list("rn")]


class Brite(DBDataBase):
    DB = "br"


class Disease(DBDataBase):
    DB = "ds"


class Drug(DBDataBase):
    DB = "dr"


@entry.entry_decorate
class EnzymeEntry(entry.DBEntry):
    FIELDS = [
        ("ENTRY", fields.DBEntryField),
        ("NAME", fields.DBNameField),
        ("CLASS", fields.DBSimpleField),
        ("SYSNAME", fields.DBSimpleField),
        ("REACTION", fields.DBSimpleField),
        ("ALL_REAC", fields.DBSimpleField),
        ("SUBSTRATE", fields.DBSimpleField),
        ("PRODUCT", fields.DBSimpleField),
        ("COMMENT", fields.DBSimpleField),
        ("REFERENCE", fields.DBReference),
        ("PATHWAY", fields.DBPathway),
        ("ORTHOLOGY", fields.DBSimpleField),
        ("GENES", fields.DBSimpleField),
        ("DBLINKS", fields.DBDBLinks)
    ]

    MULTIPLE_FIELDS = ["REFERENCE"]


class Enzyme(DBDataBase):
    DB = "ec"
    ENTRY_TYPE = EnzymeEntry

    def __init__(self):
        DBDataBase.__init__(self)
        self._keys = [d.entry_id for d in self.api.list("ec")]


@entry.entry_decorate
class OrthologyEntry(entry.DBEntry):
    FIELDS = [
        ("ENTRY", fields.DBEntryField),
        ("NAME", fields.DBNameField),
        ("CLASS", fields.DBSimpleField),
        ("DBLINKS", fields.DBDBLinks),
        ("GENES", fields.DBSimpleField),
    ]


class Orthology(DBDataBase):
    DB = "ko"
    ENTRY_TYPE = OrthologyEntry

    def __init__(self):
        DBDataBase.__init__(self)
        self._keys = [d.entry_id for d in self.api.list("ko")]


@entry.entry_decorate
class PathwayEntry(entry.DBEntry):
    FIELDS = [
        ("ENTRY", fields.DBEntryField),
        ("NAME", fields.DBNameField),
        ("DESCRIPTION", fields.DBSimpleField),
        ("CLASS", fields.DBSimpleField),
        ("PATHWAY_MAP", fields.DBPathwayMapField),
        ("MODULE", fields.DBSimpleField),
        ("DISEASE", fields.DBSimpleField),
        ("DRUG", fields.DBSimpleField),
        ("DBLINKS", fields.DBDBLinks),
        ("ORGANISM", fields.DBSimpleField),
        ("GENE", fields.DBGeneField),
        ("ENZYME", fields.DBEnzymeField),
        ("COMPOUND", fields.DBCompoundField),
        ("REFERENCE", fields.DBReference),
        ("REL_PATHWAY", fields.DBSimpleField),
        ("KO_PATHWAY", fields.DBSimpleField),
    ]

    MULTIPLE_FIELDS = ["REFERENCE"]

    @property
    def gene(self):
        if hasattr(self, "GENE"):
            genes = self.GENE._convert()
        else:
            return None

        org = self.organism
        org_prefix = ""
        if org:
            match = re.findall(r"\[GN:([a-z]+)\]", org)
            if match:
                org_prefix = match[0] + ":"
        genes = [org_prefix + g for g in genes]
        return genes


class Pathway(DBDataBase):
    """
    KEGG Pathway database

    :param str prefix:
        KEGG Organism code ('hsa', ...) or 'map', 'ko', 'ec' or 'rn'

    """
    DB = "path"
    ENTRY_TYPE = PathwayEntry

    def __init__(self, prefix="map"):
        DBDataBase.__init__(self)
        self.prefix = prefix
        valid = [d.org_code for d in self.api.list_organisms()] + \
                ["map", "ko", "ec", "rn"]

        if prefix not in valid:
            raise ValueError("Invalid prefix %r" % prefix)

        self._keys = [d.entry_id for d in self.api.list("pathway/" + prefix)]
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.