source: orange-bioinformatics/Orange/bioinformatics/obiOMIM.py @ 1632:9cf919d0f343

Revision 1632:9cf919d0f343, 3.5 KB checked in by mitar, 2 years ago (diff)

Fixing imports.

Line 
1import sys, os
2import urllib2
3import shutil
4import re
5
6from collections import defaultdict
7
8from Orange.orng import orngServerFiles
9
10class disease(object):
11    """ A class representing a disease in the OMIM database
12    """
13    regex = re.compile(r'(?P<name>.*?),? (?P<id>[0-9]{3,6} )?(?P<m1>\([123?]\) )?(?P<m2>\([123?]\) )? *$')
14    __slots__ = ["name", "id", "mapping"]
15    def __init__(self, morbidmap_line):
16        string = morbidmap_line.split("|", 1)[0]
17        match = self.regex.match(string)
18#        print string
19#        print match.groups()
20        self.name, self.id, self.mapping = [s.strip() if s else s for s in match.groups()[:3]]
21        if match.group("m2"):
22            self.mapping += " " + match.group("m2").strip()
23       
24class OMIM(object):
25    VERSION = 1
26    DEFAULT_DATABASE_PATH = orngServerFiles.localpath("OMIM")
27    def __init__(self, local_database_path=None):
28        self.local_database_path = local_database_path if local_database_path is not None else self.DEFAULT_DATABASE_PATH
29       
30        if not os.path.exists(self.local_database_path):
31            os.makedirs(self.local_database_path)
32           
33        filename = os.path.join(self.local_database_path, "morbidmap")
34        if not os.path.exists(filename):
35            stream = urllib2.urlopen("ftp://ftp.ncbi.nih.gov/repository/OMIM/ARCHIVE/morbidmap")
36            with open(filename, "wb") as file:
37                shutil.copyfileobj(stream, file, length=10)
38           
39           
40        self.load(filename)
41   
42    @classmethod
43    def download_from_NCBI(cls, file=None):
44        data = urllib2.urlopen("ftp://ftp.ncbi.nih.gov/repository/OMIM/ARCHIVE/morbidmap").read()
45        if file is None:
46            if not os.path.exists(cls.DEFAULT_DATABASE_PATH):
47                os.mkdir(cls.DEFAULT_DATABASE_PATH)
48            file = open(os.path.join(cls.DEFAULT_DATABASE_PATH, "morbidmap"), "wb")
49        elif type(file) in [str, unicode]:
50            file = open(file, "wb")
51        file.write(data)
52       
53    @classmethod
54    def get_instance(cls):
55        if not hasattr(cls, "_shared_dict"):
56            omim = OMIM()
57            cls._shared_dict = omim.__dict__
58        instance = OMIM.__new__(OMIM)
59        instance.__dict__ = cls._shared_dict
60        return instance
61   
62    def load(self, filename):
63        file = open(filename, "rb")
64        lines = file.read().split("\n")
65        self._disease_dict = dict([(disease(line), line) for line in lines if line])
66       
67    def diseases(self):
68        return self._disease_dict.keys()
69   
70    def genes(self):
71        return sorted(set(reduce(list.__add__, [self.disease_genes(disease) for disease in self.diseases()], [])))
72   
73    def disease_genes(self, disease):
74        return self._disease_dict[disease].split("|")[1].split(", ")
75   
76    def gene_diseases(self):
77        d = defaultdict(set)
78        for disease, genes in [(disease, self.disease_genes(disease)) for disease in self.diseases()]:
79            for gene in genes:
80                d[gene].add(disease)
81        return d
82   
83def diseases():
84    """ Return all disease objects
85    """
86    return OMIM.get_instance().diseases()
87       
88def genes():
89    """ Return a set of all genes referenced in OMIM
90    """
91    return OMIM.get_instance().genes()
92
93def disease_genes(disease):
94    """ Return a set of all genes referenced by disease in OMIM
95    """
96    return OMIM.get_instance().disease_genes(disease)
97
98def gene_diseases():
99    """ Return a dictionary {gene: set(disease_objects for gene), ...}
100    """
101    return OMIM.get_instance().gene_diseases()
Note: See TracBrowser for help on using the repository browser.