Beispiel #1
0
 def ID_to_label_lookup(self, ID):
     result = []
     onto_result = []
     mesh_result = []
     hgnc_result = []
     if ID.startswith('MESH'):
         try:
             ID_split = ID.split(':')
             ID_split[0] = ID_split[0].lower()
             mesh_ID_formatted = ID_split[0]+':'+ID_split[1]
             url = "http://id.nlm.nih.gov/mesh/sparql"
             mesh_response = MeshKS(ServiceContext.create_context(), url).get_label_by_id(mesh_ID_formatted)
             mesh_result = result + [{ "id" : ID, "label" : mesh_response[0]['label']} ]
         except:
             traceback.print_exc ()
     elif ID.lower().startswith('hgnc'):
         try:
             hgnc_service = HGNC('hgnc',ServiceContext.create_context())
             result = {'id': ID}
             result.update(hgnc_service.get_label(ID))
             hgnc_result.append(result)
             logger.debug(hgnc_result)
         except:
             traceback.print_exc ()
     else:
         try:
             onto_result = result + [ { "id" : ID, "label" : self.context.core.onto.get_label (ID) }]
         except:
             traceback.print_exc ()
     all_results = onto_result + mesh_result + hgnc_result
     return all_results
Beispiel #2
0
def test_one(infname, outfname, fieldnum):
    from greent.servicecontext import ServiceContext
    m = Mondo(ServiceContext.create_context())
    n_good = 0
    n_bad = 0
    diseases = set()
    with open(infname, 'r') as inf, open(outfname, 'w') as outf:
        h = inf.readline()
        for line in inf:
            if line.startswith('#'):
                continue
            x = line.strip().split('\t')[fieldnum]
            if x in diseases:
                continue
            diseases.add(x)
            result = m.search(x)
            if len(result) == 0:
                mondos = ''
                names = ''
                doids = ''
                umlss = ''
                efos = ''
                n_bad += 1
            else:
                n_good += 1
                mondos = ';'.join(result)
                names = ';'.join([m.get_label(r) for r in result])
                doids = ';'.join(sum([m.mondo_get_doid(r) for r in result],
                                     []))
                umlss = ';'.join(sum([m.mondo_get_umls(r) for r in result],
                                     []))
                efos = ';'.join(sum([m.mondo_get_efo(r) for r in result], []))
            outf.write('{}\t{}\t{}\t{}\t{}\n'.format(x, mondos, doids, umlss,
                                                     efos))
            print('Good: {}   Bad: {}'.format(n_good, n_bad))
def test_parts(uberon):
    uk = UberonGraphKS(ServiceContext.create_context())
    results = uberon.get_anatomy_parts('UBERON:0004535')
    #What are the parts of the cardiovascular system?
    #Note that we don't use this atm, it's just here as an example
    curies = [x['curie'] for x in results]
    assert 'UBERON:0000948' in curies  #heart
    assert 'UBERON:0001981' in curies  #blood vessel
def test_chebi_input(unichem):
    q = UniChem(ServiceContext.create_context())
    synonyms = unichem.get_synonyms("CHEBI:49575")
    assert len(synonyms) == 4
    assert 'CHEMBL:CHEMBL12' in synonyms
    assert 'DRUGBANK:DB00829' in synonyms
    assert 'CHEBI:49575' in synonyms
    assert 'PUBCHEM:3016' in synonyms
Beispiel #5
0
def ontology():
    url = "http://purl.obolibrary.org/obo/mondo.obo"
    ontology_file = "mondo.obo"
    if not os.path.exists(ontology_file):
        r = requests.get(url, stream=True)
        with open(ontology_file, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:  # filter out keep-alive new chunks
                    f.write(chunk)
    return GenericOntology(ServiceContext.create_context(), ontology_file)
Beispiel #6
0
    def __init__(self,
                 greentConf=None,
                 config_file=os.path.join(os.path.dirname(__file__),
                                          "rosetta.yml"),
                 delete_type_graph=False,
                 init_db=False,
                 build_indexes=False,
                 debug=False):
        """ The constructor loads the config file an prepares the type graph.
        If delete_type_graph flag is true, the graph is deleted entirely. 
        If the init_db flag is true, the type_graph will be loaded from the config file. """

        self.debug = False

        logger.debug("-- rosetta init.")
        self.service_context = ServiceContext(greentConf)
        self.core = self.service_context.core
        """ Load configuration. """
        with open(config_file, 'r') as stream:
            self.config = yaml.load(stream)
        self.operators = self.config["@operators"]
        self.type_checks = self.config["@type_checks"]

        # Abbreviation
        self.cache = self.service_context.cache  # core.service_context.cache
        """ Initialize type graph. """
        self.type_graph = TypeGraph(self.service_context, debug=debug)
        self.synonymizer = Synonymizer(self.type_graph.concept_model, self)
        """ Merge identifiers.org vocabulary into Rosetta vocab. """
        self.identifiers = Identifiers()

        if delete_type_graph:
            logger.debug("--Deleting type graph")
            self.type_graph.delete_all()

        if init_db:
            """ Initialize type graph metadata. """
            '''
            for k, v in self.identifiers.vocab.items():
                if isinstance(v, str):
                    self.type_graph.find_or_create(k, v)
            '''
            self.type_graph.find_or_create_list(self.identifiers.vocab.items())
            # self.configure_local_operators ()
            self.type_graph.configure_operators(self.operators.items())
            # self.configure_translator_registry ()
            self.type_graph.cast_edges(self.type_checks)

        if build_indexes:
            """Create neo4j indices for identifier on different labels"""
            self.type_graph.create_constraints()
Beispiel #7
0
def ontology():
    """
    Creates and returns a GenericOntology instance.
    For cases relying on .obo files, this ontology
    relies on the mondo.obo file.
    """
    url = "http://purl.obolibrary.org/obo/mondo.obo"
    ontology_file = "mondo.obo"
    if not os.path.exists (ontology_file):
        r = requests.get(url, stream=True)
        with open(ontology_file, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk: # filter out keep-alive new chunks
                    f.write(chunk)

    return GenericOntology(ServiceContext.create_context(),
                           ontology_file)
Beispiel #8
0
def hgnc():
    return HGNC("hgnc", ServiceContext.create_context())
Beispiel #9
0
def hpo():
    hpo = HPO(ServiceContext.create_context())
    return hpo
Beispiel #10
0
def mesh():
    url = "http://id.nlm.nih.gov/mesh/sparql"
    return MeshKS(ServiceContext.create_context(), url)
Beispiel #11
0
def bionames():
    """
    Create a bionames instance for passing in to the test functions.
    """
    return BioNames(ServiceContext.create_context())
def mondo2():
    return Mondo2(ServiceContext.create_context())
Beispiel #13
0
def hpo2():
    return HPO2(ServiceContext.create_context())
Beispiel #14
0
def omnicorpus():
    uberon = OmniCorp(ServiceContext.create_context())
    return uberon
Beispiel #15
0
def hgnc():
    hgnc = HGNC(ServiceContext.create_context())
    return hgnc
Beispiel #16
0
def go():
    go = GO(ServiceContext.create_context())
    return go
Beispiel #17
0
 def __init__(self):
     self.context = service_context = ServiceContext(
         config=os.environ.get('greent.conf'))
     self.generic_ont = GenericOntology(self.context, '')
def unichem():
    unichem = UniChem(ServiceContext.create_context())
    return unichem
Beispiel #19
0
        "Bionames is a generic facility which aggregates bio-ontology lookup services to retrieve names from IDs or IDs based on Natural Language names.",
        "contact": {
            "responsibleOrganization": "renci.org",
            "responsibleDeveloper": "*****@*****.**",
            "email": "*****@*****.**",
            "url": "www.renci.org",
        },
        "termsOfService": "http://renci.org/terms",
        "version": "0.0.2"
    },
    "schemes": ["https", "http"]
}
app.config['SWAGGER'] = {'title': 'BioNames Service'}

swagger = Swagger(app, template=template)
core = BioNames(ServiceContext.create_context())
cache = LRU(1000)


@app.route('/lookup/<q>/<concept>/')
def lookup(q, concept):
    """ Find ids by various methods.
   ---
   parameters:
     - name: q
       in: path
       type: string
       required: true
       default: asthma
       description: "A text string of interest. If 'include_similar' is set to true, fragments may be used. 'include_similar' also makes the search NOT case sensitive. "
       x-valueType:
Beispiel #20
0
def oxo():
    oxo = OXO(ServiceContext.create_context())
    return oxo
Beispiel #21
0
def mondo():
    mondo = Mondo(ServiceContext.create_context())
    return mondo
Beispiel #22
0
def pubchem():
    return PubChem("pubchem", ServiceContext.create_context())
def test_unknown_curie(unichem):
    q = UniChem(ServiceContext.create_context())
    synonyms = unichem.get_synonyms("DruggyDrug:49575")
    assert len(synonyms) == 0
def uniprot():
    uniprot = UniProt(ServiceContext.create_context())
    return uniprot
def go2():
    return GO2(ServiceContext.create_context())
def type_graph(conf):
    return TypeGraph(
        ServiceContext.create_context(config=conf.get('config', None)))
Beispiel #27
0
def chembl():
    return CHEMBL("chembl", ServiceContext.create_context())