source: orange-bioinformatics/obiKEGG2/__init__.py @ 1532:14a377419a09

Revision 1532:14a377419a09, 10.1 KB checked in by ales_erjavec, 2 years ago (diff)

Added KEGG interface using web services

Line 
1"""\
2==============================================
3KEGG - Kyoto Encyclopedia of Genes and Genomes
4==============================================
5
6This is a python module for access to `KEGG`_ using its web services. To use this module you need to have
7`SUDS`_ python library installed (other backends are planed).
8
9.. _`KEGG`: http://www.genome.jp/kegg/
10
11"""
12from __future__ import absolute_import
13
14import urllib2
15
16import os, sys
17from functools import wraps, partial
18from collections import defaultdict
19
20import re
21from datetime import datetime
22
23from Orange.misc import lru_cache, serverfiles
24
25from . import databases
26from . import entry
27
28from .brite import BriteEntry, Brite
29
30from . import api
31from . import conf
32from . import pathway
33
34KEGGGenome = databases.Genome
35KEGGGenes = databases.Genes
36KEGGEnzymes = databases.Enzymes
37KEGGReaction = databases.Reactions
38KEGGPathways = databases.Pathways
39
40KEGGBrite = Brite
41KEGGBriteEntry = BriteEntry
42
43KEGGPathway = pathway.Pathway
44
45DEFAULT_CACHE_DIR = conf.params["cache.path"]
46
47
48import obiProb
49from Orange.misc import deprecated_keywords, deprecated_attribute
50
51class Organism(object):
52    def __init__(self, org, genematcher=None):
53        self.org_code = self.organism_name_search(org)
54        self.genematcher = genematcher
55        self.api = api.CachedKeggApi()
56       
57    @property
58    def org(self):
59        return self.org_code
60   
61    @property
62    def genes(self):
63        if not hasattr(self, "_genes"):
64            genes = KEGGGenes(self.org_code)
65            self._genes = genes
66        return self._genes
67   
68    def gene_aliases(self):
69        return self.genes().gene_aliases()
70   
71    def pathways(self, with_ids=None):
72        if with_ids is not None:
73            return self.api.get_pathways_by_genes(with_ids)
74        else:
75            return [p.entry_id for p in self.api.list_pathways(self.org_code)]
76   
77    def list_pathways(self):
78        return self.pathways()
79   
80    def get_linked_pathways(self, pathway_id):
81        self.api.get_linked_pathways(pathway_id)
82       
83    def enzymes(self, genes=None):
84        raise NotImplementedError()
85   
86    def get_enriched_pathways(self, genes, reference=None, prob=obiProb.Binomial(), callback=None):
87        """Return a dictionary with enriched pathways ids as keys and (list_of_genes, p_value, num_of_reference_genes) tuples as items."""
88        allPathways = defaultdict(lambda :[[], 1.0, []])
89        import orngMisc
90        milestones = orngMisc.progressBarMilestones(len(genes), 100)
91        pathways_db = KEGGPathways()
92       
93        for i, gene in enumerate(genes):
94            pathways = self.pathways([gene])
95            pathways_db.pre_cache(pathways)
96            for pathway in pathways:
97                if pathways_db.get_entry(pathway).gene: 
98                    allPathways[pathway][0].append(gene)
99            if callback and i in milestones:
100                callback(i*50.0/len(genes))
101        reference = set(reference if reference is not None else self.genes.keys())
102       
103        pItems = allPathways.items()
104       
105        for i, (p_id, entry) in enumerate(pItems):
106            pathway = pathways_db.get_entry(p_id)
107            entry[2].extend(reference.intersection(pathway.gene or []))
108            entry[1] = prob.p_value(len(entry[0]), len(reference), len(entry[2]), len(genes))
109        return dict([(pid, (genes, p, len(ref))) for pid, (genes, p, ref) in allPathways.items()])
110       
111    def get_genes_by_enzyme(self, enzyme):
112        enzyme = Enzymes().get_entry(enzyme)
113        return enzyme.genes.get(self.org_code, []) if enzyme.genes else []
114   
115    def get_genes_by_pathway(self, pathway_id):
116        return Pathway(pathway_id).genes()
117   
118    def get_enzymes_by_pathway(self, pathway_id):
119        return Pathway(pathway_id).enzymes()
120   
121    def get_compounds_by_pathway(self, pathway_id):
122        return Pathway(pathway_id).compounds()
123   
124    def get_pathways_by_genes(self, gene_ids):
125        return self.api.get_pathways_by_genes(gene_ids)
126        gene_ids = set(gene_ids)
127        pathways = [self.genes[id].pathway for id in gene_ids if self.genes[id].pathway]
128        pathways = reduce(set.union, pathways, set())
129        return [id for id in pathways if gene_ids.issubset(KEGGPathway(id).genes())] 
130   
131    def get_pathways_by_enzymes(self, enzyme_ids):
132        enzyme_ids = set(enzyme_ids)
133        pathways = [KEGGEnzymes()[id].pathway for id in enzyme_ids]
134        pathwats = reduce(set.union, pathways, set())
135        return [id for id in pathways if enzyme_ids.issubset(KEGGPathway(id).enzymes())]
136   
137    def get_pathways_by_compounds(self, compound_ids):
138        compound_ids = set(compound_ids)
139        pathways = [KEGGCompounds()[id].pathway for id in compound_ids]
140        pathwats = reduce(set.union, pathways, set())
141        return [id for id in pathways if compound_ids.issubset(KEGGPathway(id).compounds())]
142   
143    def get_enzymes_by_compound(self, compound_id):
144        return KEGGCompound()[compound_id].enzyme
145   
146    def get_enzymes_by_gene(self, gene_id):
147        return self.genes[gene_id].enzymes
148   
149    def get_compounds_by_enzyme(self, enzyme_id):
150        return self._enzymes_to_compounds.get(enzyme_id)
151   
152    @deprecated_keywords({"caseSensitive": "case_sensitive"})
153    def get_unique_gene_ids(self, genes, case_sensitive=True):
154        """Return a tuple with three elements. The first is a dictionary mapping from unique gene
155        ids to gene names in genes, the second is a list of conflicting gene names and the third is a list
156        of unknown genes.
157        """
158        unique, conflicting, unknown = {}, [], []
159        for gene in genes:
160            names = self.genematcher.match(gene)
161            if len(names) == 1:
162                unique[names[0]] = gene
163            elif len(names) == 0:
164                unknown.append(gene)
165            else:
166                conflicting.append(gene)
167        return unique, conflicting, unknown
168   
169    def get_genes(self):
170        return self.genes
171   
172    @classmethod
173    def organism_name_search(cls, name):
174        genome = KEGGGenome()
175        if name not in genome:
176            ids = genome.search(name)
177            if not ids:
178                import obiTaxonomy
179                ids = obiTaxonomy.search(name)
180                ids = [id for id in ids if genome.search(id)]
181            name = ids.pop(0) if ids else name
182           
183        try:
184            return genome[name].entry_key
185        except KeyError:
186            raise ValueError("Organism with name='%s' not found in KEGG." % name)
187       
188    @classmethod
189    def organism_version(cls, name):
190        name = cls.organism_name_search(name)
191        genome = KEGGGenome()
192        info = genome.api.binfo(name)
193        return info.release
194#        orngServerFiles.localpath_download("KEGG", "kegg_genes_%s.tar.gz" % name)
195#        return orngServerFiles.info("KEGG", "kegg_genes_%s.tar.gz" % name)["datetime"]
196   
197    def _set_genematcher(self, genematcher):
198        setattr(self, "_genematcher", genematcher)
199       
200    def _get_genematcher(self):
201        if getattr(self, "_genematcher", None) == None:
202            import obiGene
203            if self.org_code == "ddi":
204                self._genematcher = obiGene.matcher([obiGene.GMKEGG(self.org_code), obiGene.GMDicty(),
205                                                     [obiGene.GMKEGG(self.org_code), obiGene.GMDicty()]])
206            else:
207                self._genematcher = obiGene.matcher([obiGene.GMKEGG(self.org_code)])
208            self._genematcher.set_targets(self.genes.keys())
209        return self._genematcher
210   
211    genematcher = property(_get_genematcher, _set_genematcher)
212   
213KEGGOrganism = Organism
214   
215def organism_name_search(name):
216    return KEGGOrganism.organism_name_search(name)
217
218def pathways(org):
219    return KEGGPathway.list(org)
220
221def organisms():
222    return KEGGOrganism.organisms()
223
224def from_taxid(taxid):
225    genome = KEGGGenome()
226    res = genome.search(taxid)
227    for r in res:
228        e = genome[r]
229        if e.taxid == taxid:
230            return e.org_code()
231       
232    return None
233
234def to_taxid(name):
235    genome = KEGGGenome()
236    keys = genome.search(name)
237    if keys:
238        return genome[keys[0]].taxid
239    else:
240        return None
241
242def create_gene_sets():
243    pass
244
245import obiGene
246from Orange.misc import serverfiles
247from Orange.misc import ConsoleProgressBar
248
249class MatcherAliasesKEGG(obiGene.MatcherAliasesPickled):
250    DOMAIN = "KEGG"
251    def create_aliases(self):
252        files = set(serverfiles.listfiles(self.DOMAIN))
253        ids_filename = "gene_matcher_kegg_ids_" + self.organism + ".pickle"
254        if ids_filename in files:
255            filename = serverfiles.localpath_download(self.DOMAIN, ids_filename)
256            import cPickle
257            aliases = cPickle.load(open(filename, "rb"))
258        else:
259            pb = ConsoleProgressBar("Retriving KEGG ids:")
260            kegg_org = KEGGOrganism(self.organism)
261            genes = kegg_org.genes
262            genes.pre_cache(progress_callback=pb.set_state)
263            aliases = []
264            for key, entry in genes.iteritems():
265                aliases.append(set([key]) | set(entry.alt_names))
266        return aliases
267   
268    def filename(self):
269        return "kegg3_" + self.organism
270   
271    def create_aliases_version(self):
272        files = set(serverfiles.listfiles(self.DOMAIN))
273        ids_filename = "gene_matcher_kegg_ids_" + self.organism + ".pickle"
274        if ids_filename in files:
275            version = serverfiles.info(self.DOMAIN, ids_filename)
276        else:
277            kegg_org = KEGGOrganism(self.organism)
278            genes = kegg_org.genes
279            version = genes.info.release
280        return version
281       
282    def __init__(self, organism, **kwargs):
283        self.organism = organism
284        sf = serverfiles.ServerFiles()
285        files = set(sf.listfiles(self.DOMAIN))
286        ids_filename = "gene_matcher_kegg_ids_" + self.organism + ".pickle"
287        if ids_filename in files:
288            serverfiles.update(self.DOMAIN, ids_filename)
289           
290        obiGene.MatcherAliasesPickled.__init__(self, **kwargs)
291
292def main():
293    KEGGGenome()
294    import doctest
295    extraglobs = {"api": KeggApi()}
296    doctest.testmod(optionflags=doctest.ELLIPSIS, extraglobs=extraglobs)
297
298if __name__ == "__main__":
299    sys.exit(main())
Note: See TracBrowser for help on using the repository browser.