Source

orange-bioinformatics / _bioinformatics / obiKEGG / api.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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
"""
KEGG api interface.

"""
from __future__ import absolute_import

from datetime import datetime
from contextlib import closing
from operator import itemgetter
import warnings

from .service import web_service
from .types import OrganismSummary, Definition, BInfo, Link


# A list of all databases with names, abbreviations
DATABASES = [
    ("KEGG Pathway", "pathway", "path", None),
    ("KEGG Brite", "brite", "br", None),
    ("KEGG Module", "module", "md", "M"),
    ("KEGG Disease", "disease", "ds", "H"),
    ("KEGG Drug", "drug", "dr", "D"),
    ("KEGG Orthology", "orthology", "ko", "K"),
    ("KEGG Genome", "genome", "genome", "T"),
    ("KEGG Genomes", "genomes", "gn", "T"),
    ("KEGG Genes", "genes", None, None),
    ("KEGG Ligand", "ligand", "ligand", None),
    ("KEGG Compound", "compound", "cpd", "C"),
    ("KEGG Glycan", "glycan", "gl", "G"),
    ("KEGG Reaction", "reaction", "rn", "R"),
    ("KEGG RPair", "rpair", "rp", "RP"),
    ("KEGG RClass", "rclass", "rc", "RC"),
    ("KEGG Enzyme", "enzyme", "ec", "E")
]


def _link_targets(links):
    return sorted(set(map(itemgetter(1), links)))


class KeggApi(object):
    """
    An abstraction of a rest KEGG API.
    """

    def __init__(self):
        self.service = web_service()

    def list_organisms(self):
        """
        Return a list of all available organisms

        >>> api.list_organisms()
        [OrganismSummary(entry_id=T0..

        """
        return map(OrganismSummary.from_str,
                   self.service.list.organism.get().splitlines())

    def list_pathways(self, organism):
        """
        Return a list of all available pathways for `organism`

        >>> api.list_pathways("hsa")
        [Definition(entry_id=',...

        """
        return map(Definition.from_str,
                   self.service.list.pathway(organism).get().splitlines())

    def list(self, db):
        """
        Return a list of all available entries in database `db`.
        """
        return map(Definition.from_str,
                   self.service.list(db).get().splitlines())

    #######
    # DBGET
    #######

    def info(self, db):
        """
        Return info for database `db`

        >>> print api.info("pathway")
        BInfo(entry_id='path', definition='KEGG Pathway Database', ...

        """
        result = self.service.info(db).get()
        return BInfo.from_text(str(result))

    def find(self, db, keywords):
        """
        Search database 'db' for keywords.
        """
        if isinstance(keywords, basestring):
            keywords = [keywords]

        return self.service.find(db)("+".join(keywords)).get()

    def get(self, ids):
        """
        Retrieve database entries for `ids` list.
        """
        if not isinstance(ids, basestring):
            # Sequence of ids
            ids = "+".join(ids)

        return self.service.get(ids).get()

    def conv(self, target_db, source):
        """
        Return a mapping from source to target_db ids as a list of two
        tuples [(source_id, target_id), ...].

        """
        if not isinstance(source, basestring):
            source = "+".join(source)

        res = self.service.conv(target_db)(source).get()
        return [tuple(line.split("\t")) for line in res.splitlines()]

    def link(self, target_db, source_db=None, ids=None):
        if not (source_db or ids):
            raise ValueError("One of 'source_db' or 'ids' must be supplied")
        if source_db and ids:
            raise ValueError("Only one 'source_db' or 'ids' must be supplied")

        if source_db:
            result = self.service.link(target_db)(source_db).get()
        else:
            result = self.service.link(target_db)("+".join(ids)).get()

        return map(Link._make, map(str.split, result.splitlines()))

    def get_genes_by_enzyme(self, enzyme_id, org):
        return _link_targets(self.link(org, ids=[enzyme_id]))

    def get_enzymes_by_gene(self, gene_id):
        return _link_targets(self.link("ec", ids=[gene_id]))

    def get_enzymes_by_compound(self, compound_id):
        return _link_targets(self.link("ec", ids=[compound_id]))

    def get_enzymes_by_glycan(self, glycan_id):
        return _link_targets(self.link("ec", ids=[glycan_id]))

    def get_enzymes_by_reaction(self, reaction_id):
        return _link_targets(self.link("ec", ids=[reaction_id]))

    def get_compounds_by_enzyme(self, enzyme_id):
        return _link_targets(self.link("compound", ids=[enzyme_id]))

    def get_compounds_by_reaction(self, reaction_id):
        return _link_targets(self.link("compound", ids=[reaction_id]))

    def get_glycans_by_enzyme(self, enzyme_id):
        return _link_targets(self.link("gl", ids=[enzyme_id]))

    def get_glycans_by_reaction(self, reaction_id):
        return _link_targets(self.link("gl", ids=[reaction_id]))

    def get_reactions_by_enzyme(self, enzyme_id):
        return _link_targets(self.link("rn", ids=[enzyme_id]))

    def get_reactions_by_compound(self, compound_id):
        return _link_targets(self.link("rn", ids=[compound_id]))

    def get_reactions_by_glycan(self, glycan_id):
        return _link_targets(self.link("rn", ids=[glycan_id]))

    ######
    # SSDB
    ######

    # No replacement api in the KEGG REST api.
    def get_best_best_neighbors_by_gene(self, genes_id, offset, limit):
        raise NotImplementedError

    def get_best_neighbors_by_gene(self, genes_id, offset, limit):
        raise NotImplementedError

    def get_reverse_best_neighbors_by_gene(self, genes_id, offset, limit):
        raise NotImplementedError

    def get_paralogs_by_gene(self, genes_id, offset, limit):
        raise NotImplementedError

    #######
    # Motif
    #######

    # No replacement api in KEGG REST api
    def get_motifs_by_gene(self, genes_id, db):
        raise NotImplementedError

    def get_genes_by_motifs(self, motif_id_list, offset, limit):
        raise NotImplementedError

    ####
    # KO
    ####

    def get_ko_by_gene(self, genes_id):
        raise NotImplementedError

    def get_ko_by_ko_class(self, ko_class_id):
        raise NotImplementedError

    def get_genes_by_ko_class(self, ko_class_id, org, offset, limit):
        raise NotImplementedError

    def get_genes_by_ko(self, ko_id, org):
        raise NotImplementedError

    #########
    # Pathway
    #########

    def mark_pathway_by_objects(self, pathway_id, object_id_list):
        raise NotImplementedError

    def color_pathway_by_objects(self, pathway_id, object_id_list,
                                 fg_color_list, bg_color_list):
        raise NotImplementedError

    def color_pathway_by_elements(self, pathway_id, element_id_list,
                                  fg_color_list, bg_color_list):
        raise NotImplementedError

    def get_html_of_marked_pathway_by_objects(self, pathway_id,
                                              object_id_list):
        raise NotImplementedError

    def get_html_of_colored_pathway_by_objects(self, pathway_id,
                                               object_id_list, fg_color_list,
                                               bg_color_list):
        raise NotImplementedError

    def get_html_of_colored_pathway_by_elements(self, pathway_id,
                                                element_id_list, fg_color_list,
                                                bg_color_list):
        raise NotImplementedError

    def get_references_by_pathway(self, pathway_id):
        return self.service.get_references_by_pathway(pathway_id)

    def get_element_relations_by_pathway(self, pathway_id):
        return self.service.get_element_relations_by_pathway(pathway_id)

    def get_genes_by_organism(self, organism, offset=None, limit=None):
        if offset is not None:
            raise NotImplementedError("offset is no longer supported")
        if limit is not None:
            raise NotImplementedError("limit is no longer supported.")

        res = self.service.list(organism).get().splitlines()
        return [r.split(None, 1)[0] for r in res]

    def get_number_of_genes_by_organism(self, organism):
        raise NotImplementedError

    ####################
    # Objects by pathway
    ####################

    def get_elements_by_pathway(self, pathway_id):
        raise NotImplementedError

    def get_genes_by_pathway(self, pathway_id):
        return _link_targets(self.link("genes", ids=[pathway_id]))

    def get_enzymes_by_pathway(self, pathway_id):
        return _link_targets(self.link("ec", ids=[pathway_id]))

    def get_compounds_by_pathway(self, pathway_id):
        return _link_targets(self.link("compound", ids=[pathway_id]))

    def get_drugs_by_pathway(self, pathway_id):
        return _link_targets(self.link("drug", ids=[pathway_id]))

    def get_glycans_by_pathway(self, pathway_id):
        return _link_targets(self.link("gl", ids=[pathway_id]))

    def get_reactions_by_pathway(self, pathway_id):
        return _link_targets(self.link("rn", ids=[pathway_id]))

    def get_kos_by_pathway(self, pathway_id):
        return _link_targets(self.link("ko", ids=[pathway_id]))

    #####################
    # Pathways by objects
    #####################

    # These functions returned results intersections.
    def get_pathways_by_genes(self, gene_list):
        raise NotImplementedError

    def get_pathways_by_enzymes(self, enzyme_list):
        raise NotImplementedError

    def get_pathways_by_compounds(self, compound_list):
        raise NotImplementedError

    def get_pathways_by_drugs(self, drug_list):
        raise NotImplementedError

    def get_pathways_by_glycans(self, glycan_list):
        raise NotImplementedError

    def get_pathways_by_reactions(self, reaction_list):
        raise NotImplementedError

    def get_pathways_by_kos(self, ko_list):
        raise NotImplementedError

    ##########################
    # Relations among pathways
    ##########################

    def get_linked_pathways(self, pathway_id):
        if not pathway_id.startswith("path:"):
            pathway_id = "path:" + pathway_id
        return _link_targets(self.link("pathway", ids=[pathway_id]))


"""
KEGG api with caching
"""

import os

from . import caching
from .caching import cached_method, cache_entry, touch_dir

try:
    from functools import lru_cache
except ImportError:
    # TODO: move a copy of lru_cache in .caching if distributing this as a
    # standalone package
    from Orange.utils import lru_cache


class CachedKeggApi(KeggApi):
    def __init__(self, store=None):
        KeggApi.__init__(self)
        if store is None:
            self.store = {}

    # Needed API for cached decorator.
    def cache_store(self):
        from . import conf
        path = conf.params["cache.path"]
        touch_dir(path)
        return caching.Sqlite3Store(os.path.join(path,
                                                 "kegg_api_cache_1.sqlite3"))

    def last_modified(self, args, kwargs=None):
        return getattr(self, "default_release", "")

    def set_default_release(self, release):
        self.default_release = release

    @cached_method
    def list_organisms(self):
        return KeggApi.list_organisms(self)

    @cached_method
    def list_pathways(self, organism):
        return KeggApi.list_pathways(self, organism)

    @cached_method
    def list(self, db):
        return KeggApi.list(self, db)

    @lru_cache()  # not persistently cached
    def info(self, db):
        return KeggApi.info(self, db)

    @cached_method
    def find(self, db, keywords):
        return KeggApi.find(self, db, keywords)

    @cached_method
    def get(self, ids):
        if not isinstance(ids, basestring):
            return self._batch_get(ids)
        else:
            return KeggApi.get(self, ids)

    def _batch_get(self, ids):
        if len(ids) > 10:
            raise ValueError("Can batch at most 10 ids at a time.")

        get = self.get
        uncached = []
        unmatched = set()

        with closing(get.cache_store()) as store:
            # Which ids are already cached
            # TODO: Invalidate entries by release string.
            for id in ids:
                key = get.key_from_args((id,))
                if not get.key_has_valid_cache(key, store):
                    uncached.append(id)

        if uncached:
            # in case there are duplicate ids
            uncached = sorted(set(uncached))

            rval = KeggApi.get(self, uncached)

            if rval is not None:
                entries = rval.split("///\n")
            else:
                entries = []

            if entries and not entries[-1].strip():
                # Delete the last single newline entry if present
                del entries[-1]

            if len(entries) != len(uncached):
                new_uncached, entries = match_by_ids(uncached, entries)
                unmatched = set(uncached) - set(new_uncached)
                uncached = new_uncached
                warnings.warn("Unable to match entries for keys: %s." %
                              ", ".join(map(repr, unmatched)))

            with closing(get.cache_store()) as store:
                for id, entry in zip(uncached, entries):
                    key = get.key_from_args((id,))
                    if entry is not None:
                        entry = entry + "///\n"
                    store[key] = cache_entry(entry, mtime=datetime.now())

        # Finally join all the results, but drop all None objects

        with closing(get.cache_store()):
            keys = [get.key_from_args((id,)) for id in ids]
            entries = [store[key].value for key in keys]

        entries = filter(lambda e: e is not None, entries)

        rval = "".join(entries)
        return rval

    @cached_method
    def conv(self, target_db, source):
        return KeggApi.conv(self, target_db, source)

    ########
    # LinkDB
    ########

    @cached_method
    def get_genes_by_enzyme(self, enzyme_id, org):
        return KeggApi.get_genes_by_enzyme(self, enzyme_id, org)

    @cached_method
    def get_enzymes_by_gene(self, genes_id):
        return KeggApi.get_enzymes_by_gene(self, genes_id)

    @cached_method
    def get_enzymes_by_compound(self, compound_id):
        return KeggApi.get_enzymes_by_compound(self, compound_id)

    @cached_method
    def get_enzymes_by_glycan(self, glycan_id):
        return KeggApi.get_enzymes_by_glycan(self, glycan_id)

    @cached_method
    def get_enzymes_by_reaction(self, reaction_id):
        return KeggApi.get_enzymes_by_reaction(self, reaction_id)

    @cached_method
    def get_compounds_by_enzyme(self, enzyme_id):
        return KeggApi.get_compounds_by_enzyme(self, enzyme_id)

    @cached_method
    def get_compounds_by_reaction(self, reaction_id):
        return KeggApi.get_compounds_by_reaction(self, reaction_id)

    @cached_method
    def get_glycans_by_enzyme(self, enzyme_id):
        return KeggApi.get_glycans_by_enzyme(self, enzyme_id)

    @cached_method
    def get_glycans_by_reaction(self, reaction_id):
        return KeggApi.get_glycans_by_reaction(self, reaction_id)

    @cached_method
    def get_reactions_by_enzyme(self, enzyme_id):
        return KeggApi.get_reactions_by_enzyme(self, enzyme_id)

    @cached_method
    def get_reactions_by_compound(self, compound_id):
        return KeggApi.get_reactions_by_compound(self, compound_id)

    @cached_method
    def get_reactions_by_glycan(self, glycan_id):
        return KeggApi.get_reactions_by_glycan(self, glycan_id)

    ######
    # SSDB
    ######

    @cached_method
    def get_best_best_neighbors_by_gene(self, genes_id, offset, limit):
        return KeggApi.get_best_best_neighbors_by_gene(self, genes_id, offset,
                                                       limit)

    @cached_method
    def get_best_neighbors_by_gene(self, genes_id, offset, limit):
        return KeggApi.get_best_neighbors_by_gene(self, genes_id, offset,
                                                  limit)

    @cached_method
    def get_reverse_best_neighbors_by_gene(self, genes_id, offset, limit):
        return KeggApi.get_reverse_best_neighbors_by_gene(self, genes_id,
                                                          offset, limit)

    @cached_method
    def get_paralogs_by_gene(self, genes_id, offset, limit):
        return KeggApi.get_paralogs_by_gene(self, genes_id, offset, limit)

    #######
    # Motif
    #######

    @cached_method
    def get_motifs_by_gene(self, genes_id, db):
        return KeggApi.get_motifs_by_gene(self, genes_id, db)

    @cached_method
    def get_genes_by_motifs(self, motif_id_list, offset, limit):
        return KeggApi.get_genes_by_motifs(self, motif_id_list, offset, limit)

    ####
    # KO
    ####

    @cached_method
    def get_ko_by_gene(self, genes_id):
        return KeggApi.get_ko_by_gene(self, genes_id)

    @cached_method
    def get_ko_by_ko_class(self, ko_class_id):
        return KeggApi.service.get_ko_by_ko_class(self, ko_class_id)

    @cached_method
    def get_genes_by_ko_class(self, ko_class_id, org, offset, limit):
        return KeggApi.get_genes_by_ko_class(self, ko_class_id, org, offset,
                                             limit)

    @cached_method
    def get_genes_by_ko(self, ko_id, org):
        return KeggApi.get_genes_by_ko(self, ko_id, org)

    #########
    # Pathway
    #########

    @cached_method
    def get_genes_by_organism(self, organism, offset=None, limit=None):
        return KeggApi.get_genes_by_organism(self, organism, offset=offset,
                                             limit=limit)

    @cached_method
    def get_number_of_genes_by_organism(self, organism):
        return KeggApi.get_number_of_genes_by_organism(self, organism)

    @cached_method
    def get_pathways_by_genes(self, gene_list):
        return KeggApi.get_pathways_by_genes(self, gene_list)

    @cached_method
    def get_pathways_by_enzymes(self, enzyme_list):
        return KeggApi.get_pathways_by_enzymes(self, enzyme_list)

    @cached_method
    def get_pathways_by_compounds(self, compound_list):
        return KeggApi.get_pathways_by_compounds(self, compound_list)

    @cached_method
    def get_pathways_by_drugs(self, drug_list):
        return KeggApi.get_pathways_by_drugs(self, drug_list)

    @cached_method
    def get_pathways_by_glycans(self, glycan_list):
        return KeggApi.get_pathways_by_glycans(self, glycan_list)

    @cached_method
    def get_pathways_by_reactions(self, reaction_list):
        return KeggApi.get_pathways_by_reactions(self, reaction_list)

    @cached_method
    def get_pathways_by_kos(self, ko_list):
        return KeggApi.get_pathways_by_kos(self, ko_list)

    @cached_method
    def get_elements_by_pathway(self, pathway_id):
        return KeggApi.get_elements_by_pathway(self, pathway_id)

    @cached_method
    def get_genes_by_pathway(self, pathway_id):
        return KeggApi.get_genes_by_pathway(self, pathway_id)

    @cached_method
    def get_enzymes_by_pathway(self, pathway_id):
        return KeggApi.get_enzymes_by_pathway(self, pathway_id)

    @cached_method
    def get_compounds_by_pathway(self, pathway_id):
        return KeggApi.get_compounds_by_pathway(self, pathway_id)

    @cached_method
    def get_drugs_by_pathway(self, pathway_id):
        return KeggApi.get_drugs_by_pathway(self, pathway_id)

    @cached_method
    def get_glycans_by_pathway(self, pathway_id):
        return KeggApi.get_glycans_by_pathway(self, pathway_id)

    @cached_method
    def get_reactions_by_pathway(self, pathway_id):
        return KeggApi.get_reactions_by_pathway(self, pathway_id)

    @cached_method
    def get_kos_by_pathway(self, pathway_id):
        return KeggApi.get_kos_by_pathway(self, pathway_id)


def match_by_ids(ids, entries):
    """

    """

    unmatched_ids = set(ids)
    unmatched_entries = set(entries)

    matched_ids = []
    matched_entries = []

    def match_add(search_id, entry):
        """
        Move search_id and entry to the matched lists.
        """
        matched_ids.append(search_id)
        matched_entries.append(entry)

        # Remove from the unmatched set
        unmatched_ids.remove(search_id)
        unmatched_entries.remove(entry)

    def entry_split(entry_text):
        line, _ = entry_text.split("\n", 1)
        return line.split(None, 2)

    entries_by_id = {}

    for entry in entries:
        _, eid, _ = entry_split(entry)
        entries_by_id[eid] = entry

    # First match full search ids
    for search_id in list(unmatched_ids):
        if search_id in entries_by_id:
            entry = entries_by_id.pop(search_id)
            match_add(search_id, entry)

    # Second pass, split the search ids by ':' to db and identifier part,
    # match by identifier
    for search_id in list(unmatched_ids):
        if ":" in search_id:
            db_id, rest = search_id.split(":", 1)
            if rest in entries_by_id:
                entry = entries_by_id.pop(rest)
                match_add(search_id, entry)

    return matched_ids, matched_entries
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.