Source

orange-bioinformatics / _bioinformatics / obiKEGG / __init__.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
"""
==============================================
KEGG - Kyoto Encyclopedia of Genes and Genomes
==============================================

:mod:`obiKEGG` is a python module for accessing `KEGG (Kyoto Encyclopedia
of Genes and Genomes) <http://www.genome.jp/kegg/>`_ using its web services.

.. note:: To use this module you need to have `slumber`_ and `requests`_
          package installed.

.. _`slumber`: https://pypi.python.org/pypi/slumber/

.. _`requests`: https://pypi.python.org/pypi/requests


>>> # Create a KEGG Genes database interface
>>> genome = KEGGGenome()
>>> # List all available entry ids
>>> keys = genome.keys()
>>> print keys[0]
T01001
>>> # Retrieve the entry for the key.
>>> entry = genome[keys[0]]
>>> print entry.entry_key
T01001
>>> print entry.definition
Homo sapiens (human)
>>> print str(entry)
ENTRY       T01001            Complete  Genome
NAME        hsa, HUMAN, 9606
DEFINITION  Homo sapiens (human)
...

The :class:`Organism` class can be used as a convenient starting point
for organism specific databases.

>>> organism = Organism("Homo sapiens")  # searches for the organism by name
>>> print organism.org_code  # prints the KEGG organism code
hsa
>>> genes = organism.genes  # get the genes database for the organism
>>> gene_ids = genes.keys() # KEGG gene identifiers
>>> entry = genes["hsa:672"]
>>> print entry.definition
breast cancer 1, early onset
>>> print entry  # print the entry in DBGET database format.
ENTRY       672               CDS       T01001
NAME        BRCA1, BRCAI, BRCC1, BROVCA1, IRIS, PNCA4, PPP1R53, PSCP, RNF53
DEFINITION  breast cancer 1, early onset
...

"""
from __future__ import absolute_import

import os
import sys
import urllib2
import threading

from collections import defaultdict
from itertools import chain
from datetime import datetime
from contextlib import contextmanager

from Orange.utils import lru_cache
from Orange.utils import progress_bar_milestones
from Orange.utils import (
    deprecated_keywords, deprecated_attribute, deprecated_function_name
)

from .. import obiProb, obiTaxonomy

from . import databases
from . import entry

from .brite import BriteEntry, Brite

from . import api
from . import conf
from . import pathway

KEGGGenome = databases.Genome
KEGGGenes = databases.Genes
KEGGEnzyme = databases.Enzyme
KEGGReaction = databases.Reaction
KEGGPathways = databases.Pathway
KEGGCompound = databases.Compound

KEGGBrite = Brite
KEGGBriteEntry = BriteEntry

KEGGPathway = pathway.Pathway

DEFAULT_CACHE_DIR = conf.params["cache.path"]


class Organism(object):
    """
    A convenience class for retrieving information regarding an
    organism in the KEGG Genes database.

    :param org: KEGG organism code (e.g. "hsa", "sce"). Can also be a
        descriptive name (e.g. 'yeast', "homo sapiens") in which case the
        organism code will be searched for by using KEGG `find` api.
    :type org: str

    .. seealso::

        :func:`organism_name_search`
            Search KEGG for an organism code

    """
    def __init__(self, org, genematcher=None):
        self.org_code = self.organism_name_search(org)
        self.genematcher = genematcher
        self.api = api.CachedKeggApi()

    @property
    def org(self):
        """
        KEGG organism code.
        """
        return self.org_code

    @property
    def genes(self):
        """
        An :class:`~.databases.Genes` database instance for this organism.
        """
        # TODO: This should not be a property but a method.
        # I think it was only put here as back compatibility with old obiKEGG.
        if not hasattr(self, "_genes"):
            genes = KEGGGenes(self.org_code)
            self._genes = genes
        return self._genes

    def gene_aliases(self):
        """
        Return a list of sets of equal genes (synonyms) in KEGG for
        this organism.

        .. note::

            This only includes 'ncbi-geneid' and 'ncbi-gi' records
            from the KEGG Genes DBLINKS entries.

        """
        definitions = self.api.list(self.org_code)
        ncbi_geneid = self.api.conv(self.org_code, "ncbi-geneid")
        ncbi_gi = self.api.conv(self.org_code, "ncbi-gi")

        aliases = defaultdict(set)

        for entry_id, definition in definitions:
            # genes entry id without the organism code
            aliases[entry_id].add(entry_id.split(":", 1)[1])
            # all names in the NAME field (KEGG API list returns
            # 'NAME; DEFINITION') fields for genes
            names = definition.split(";")[0].split(",")
            aliases[entry_id].update([name.strip() for name in names])

        for source_id, target_id in chain(ncbi_geneid, ncbi_gi):
            aliases[target_id].add(source_id.split(":", 1)[1])

        return [set([entry_id]).union(names)
                for entry_id, names in aliases.iteritems()]

    def pathways(self, with_ids=None):
        """
        Return a list of all pathways for this organism.
        """
        if with_ids is not None:
            return self.api.get_pathways_by_genes(with_ids)
        else:
            return [p.entry_id for p in self.api.list_pathways(self.org_code)]

    def list_pathways(self):
        """
        List all pathways for this organism.

        .. deprecated: 2.5
            Use :func:`pathways` instead.

        """
        # NOTE: remove/deprecate and use pathways()
        return self.pathways()

    def get_linked_pathways(self, pathway_id):
        self.api.get_linked_pathways(pathway_id)

    def enzymes(self, genes=None):
        raise NotImplementedError()

    def get_enriched_pathways(self, genes, reference=None,
                              prob=obiProb.Binomial(), callback=None):
        """
        Return a dictionary with enriched pathways ids as keys
        and (list_of_genes, p_value, num_of_reference_genes) tuples
        as items.

        """
        if reference is None:
            reference = self.genes.keys()
        reference = set(reference)

        allPathways = defaultdict(lambda: [[], 1.0, []])
        milestones = progress_bar_milestones(len(genes), 100)
        pathways_db = KEGGPathways()

        pathways_for_gene = []
        for i, gene in enumerate(genes):
            pathways_for_gene.append(self.pathways([gene]))
            if callback and i in milestones:
                callback(i * 50.0 / len(genes))

        # pre-cache for speed
        pathways_db.pre_cache([pid for pfg in pathways_for_gene
                               for pid in pfg])
        for i, (gene, pathways) in enumerate(zip(genes, pathways_for_gene)):
            for pathway in pathways:
                if pathways_db.get_entry(pathway).gene:
                    allPathways[pathway][0].append(gene)
            if callback and i in milestones:
                callback(50.0 + i * 50.0 / len(genes))

        pItems = allPathways.items()

        for i, (p_id, entry) in enumerate(pItems):
            pathway = pathways_db.get_entry(p_id)
            entry[2].extend(reference.intersection(pathway.gene or []))
            entry[1] = prob.p_value(len(entry[0]), len(reference),
                                    len(entry[2]), len(genes))
        return dict([(pid, (genes, p, len(ref)))
                     for pid, (genes, p, ref) in allPathways.items()])

    def get_genes_by_enzyme(self, enzyme):
        enzyme = KEGGEnzyme().get_entry(enzyme)
        return enzyme.genes.get(self.org_code, []) if enzyme.genes else []

    def get_genes_by_pathway(self, pathway_id):
        return KEGGPathway(pathway_id).genes()

    def get_enzymes_by_pathway(self, pathway_id):
        return KEGGPathway(pathway_id).enzymes()

    def get_compounds_by_pathway(self, pathway_id):
        return KEGGPathway(pathway_id).compounds()

    def get_pathways_by_genes(self, gene_ids):
        return self.api.get_pathways_by_genes(gene_ids)
        gene_ids = set(gene_ids)
        pathways = [self.genes[id].pathway for id in gene_ids
                    if self.genes[id].pathway]
        pathways = reduce(set.union, pathways, set())
        return [id for id in pathways
                if gene_ids.issubset(KEGGPathway(id).genes())]

    def get_pathways_by_enzymes(self, enzyme_ids):
        enzyme_ids = set(enzyme_ids)
        pathways = [KEGGEnzyme()[id].pathway for id in enzyme_ids]
        pathways = reduce(set.union, pathways, set())
        return [id for id in pathways
                if enzyme_ids.issubset(KEGGPathway(id).enzymes())]

    def get_pathways_by_compounds(self, compound_ids):
        compound_ids = set(compound_ids)
        pathways = [KEGGCompound()[id].pathway for id in compound_ids]
        pathways = reduce(set.union, pathways, set())
        return [id for id in pathways
                if compound_ids.issubset(KEGGPathway(id).compounds())]

    def get_enzymes_by_compound(self, compound_id):
        return KEGGCompound()[compound_id].enzyme

    def get_enzymes_by_gene(self, gene_id):
        return self.genes[gene_id].enzymes

    def get_compounds_by_enzyme(self, enzyme_id):
        return self._enzymes_to_compounds.get(enzyme_id)

    @deprecated_keywords({"caseSensitive": "case_sensitive"})
    def get_unique_gene_ids(self, genes, case_sensitive=True):
        """
        Return a tuple with three elements. The first is a dictionary
        mapping from unique geneids to gene names in genes, the second
        is a list of conflicting gene names and the third is a list of
        unknown genes.

        """
        unique, conflicting, unknown = {}, [], []
        for gene in genes:
            names = self.genematcher.match(gene)
            if len(names) == 1:
                unique[names[0]] = gene
            elif len(names) == 0:
                unknown.append(gene)
            else:
                conflicting.append(gene)
        return unique, conflicting, unknown

    @deprecated_function_name
    def get_genes(self):
        return self.genes

    @classmethod
    def organism_name_search(cls, name):
        return organism_name_search(name)

    @classmethod
    def organism_version(cls, name):
        name = cls.organism_name_search(name)
        with _global_genome_instance() as genome:
            info = genome.api.info(name)
            return info.release

    def _set_genematcher(self, genematcher):
        setattr(self, "_genematcher", genematcher)

    def _get_genematcher(self):
        if getattr(self, "_genematcher", None) is None:
            from .. import obiGene
            if self.org_code == "ddi":
                self._genematcher = obiGene.matcher(
                    [obiGene.GMKEGG(self.org_code), obiGene.GMDicty(),
                     [obiGene.GMKEGG(self.org_code), obiGene.GMDicty()]]
                )
            else:
                self._genematcher = obiGene.matcher(
                    [obiGene.GMKEGG(self.org_code)])

            self._genematcher.set_targets(self.genes.keys())
        return self._genematcher

    genematcher = property(_get_genematcher, _set_genematcher)


KEGGOrganism = Organism


def organism_name_search(name):
    """
    Search for a organism by `name` and return it's KEGG organism code.
    """
    with _global_genome_instance() as genome:
        try:
            name = genome.org_code_to_entry_key(name)
        except ValueError:
            pass

        if name not in genome:
            ids = genome.search(name)
            if ids:
                name = ids.pop(0) if ids else name
            else:
                raise obiTaxonomy.UnknownSpeciesIdentifier(name)

        try:
            return genome[name].organism_code
        except KeyError:
            raise obiTaxonomy.UnknownSpeciesIdentifier(name)


def pathways(org):
    """
    Return a list of all KEGG pathways for an KEGG organism code `org`.
    """
    return KEGGPathway.list(org)


def from_taxid(taxid):
    """
    Return a KEGG organism code for a an NCBI Taxonomy id string `taxid`.
    """
    with _global_genome_instance() as genome:
        res = genome.search(taxid)
        for r in res:
            e = genome[r]

            if e.taxid in [taxid, genome.TAXID_MAP.get(taxid, taxid)]:
                return e.org_code()

        return None


def to_taxid(name):
    """
    Return a NCBI Taxonomy id for a given KEGG Organism name
    """
    with _global_genome_instance() as genome:
        if name in genome:
            return genome[name].taxid

        keys = genome.search(name)
        if keys:
            return genome[keys[0]].taxid
        else:
            return None


def _global_genome_instance():
    genome = getattr(_global_genome_instance, "_genome", None)
    if genome is None:
        genome = KEGGGenome()
        genome._lock = threading.RLock()
        _global_genome_instance._genome = genome

    @contextmanager
    def instance_locked(instance, lock):
        lock.acquire()
        try:
            yield instance
        finally:
            lock.release()

    return instance_locked(genome, genome._lock)


def main():
    KEGGGenome()
    import doctest
    extraglobs = {"api": KeggApi()}
    doctest.testmod(optionflags=doctest.ELLIPSIS, extraglobs=extraglobs)


if __name__ == "__main__":
    sys.exit(main())