예제 #1
0
파일: apps.py 프로젝트: ychalier/flont
 def ready(self):
     global world
     global ontology
     global graph
     if world is None:
         world = owlready2.World(filename=settings.FLONT_DB)
     if ontology is None:
         ontology = world.get_ontology(
             "https://ontology.chalier.fr/flont").load()
     if graph is None:
         graph = world.as_rdflib_graph()
예제 #2
0
def rereason(G, filename):
    world = owlready2.World()
    with open(filename, 'wb') as f:
        f.write(G.serialize(format='ntriples'))
    on = world.get_ontology(f"file://./{filename}").load()
    owlready2.sync_reasoner(world, infer_property_values=True)
    G = world.as_rdflib_graph()
    G.bind('rdf', RDF)
    G.bind('owl', OWL)
    G.bind('rdfs', RDFS)
    G.bind('skos', SKOS)
    G.bind('brick', BRICK)
    G.bind('tag', TAG)
    G.bind('bldg', BLDG)
    return G
예제 #3
0
    def __init__(self,
                 subfolder_id="000",
                 folder="IIMB_LARGE",
                 filename="onto.owl"):
        """ Load an ontology from a given folder.

        By extracting the default folder IIMB_LARGE, subfolders are of the
        form 000, 001, 002, ..., 080. Each contains a file onto.owl with an
        ontology in XML format.

        This method intializes a Ontology object by loading the content of a
        given folder.

        """

        self.iri = os.path.join("file://", sys.path[0], folder, subfolder_id,
                                filename)
        print("Loading ontology at", self.iri)
        owl.Ontology.__init__(self, owl.World(), base_iri=self.iri + "#")
        self.load()
import owlready2 as owl
import pathlib
# import rdflib

tpoPath = pathlib.Path('../TissuePhenomics.owl')
importsPath = pathlib.Path('..\imports')
clPath = importsPath / 'cl_import.owl'
# TPO

tpoWorld = owl.World()
if tpoPath.exists():
    owl.onto_path.append(str(tpoPath.parent.resolve()))
    owl.onto_path.append(str(importsPath.resolve()))
    try:
        tpo = tpoWorld.get_ontology(str(
            tpoPath.resolve())).load(only_local=True)
    except:
        pass
else:
    raise FileNotFoundError

# CL Imports
clWorld = owl.World()
if clPath.exists():
    owl.onto_path.append(str(clPath.parent.resolve()))
    owl.onto_path.append(str(importsPath.resolve()))
    try:
        cl = clWorld.get_ontology(str(clPath.resolve())).load(only_local=True)
    except:
        pass
else:
    def GetOntology(cls, iri, doReasoner=False, cachePath=None):
        iri_hash = cls.IRI_HASH.get(iri)

        if iri_hash is None:
            cls.IRI_HASH[iri] = iri_hash = hashlib.sha1(
                iri.encode('utf-8')).hexdigest()

        onto = cls.ONTO_CACHE.get(iri_hash)
        if onto is None:
            worldDB = cls.TermWorlds.get(iri_hash)

            if worldDB is None:
                worldDBPath = cls.GetWorldDBPath(iri_hash, cachePath)

                # Activate this only if you want to save a copy of the ontologies
                #ontologiesPath = os.path.join(cachePath,'ontologies')
                #os.makedirs(ontologiesPath,exist_ok=True)
                #owlready2.onto_path.append(ontologiesPath)
                worldDB = owlready2.World(filename=worldDBPath,
                                          exclusive=False)
                cls.TermWorlds[iri_hash] = worldDB

            # Trying to get the metadata useful for an optimal ontology download
            metadataPath = cls.GetMetadataPath(iri_hash, cachePath)
            if os.path.exists(metadataPath):
                try:
                    with open(metadataPath, mode='r',
                              encoding='utf-8') as metadata_fh:
                        metadata = json.load(metadata_fh)
                except:
                    # A corrupted cache should not disturb
                    metadata = {}
            else:
                metadata = {}

            ontologyPath = cls.GetOntologyPath(iri_hash, cachePath)
            gotPath, gotMetadata = download_file(iri, ontologyPath, metadata)
            if gotPath:
                gotMetadata['orig_url'] = iri
                # Reading the ontology
                with open(ontologyPath, mode="rb") as onto_fh:
                    onto = worldDB.get_ontology(iri).load(fileobj=onto_fh,
                                                          reload=True)

                # Save the metadata
                with open(metadataPath, mode="w",
                          encoding="utf-8") as metadata_fh:
                    json.dump(gotMetadata, metadata_fh)

                # Re-save once the reasoner has run
                if doReasoner:
                    worldDB.save()
                    owlready2.sync_reasoner(onto)
            else:
                onto = worldDB.get_ontology(iri).load()
            worldDB.save()

            # And now unlink the ontology (if exists)
            if os.path.exists(ontologyPath):
                os.unlink(ontologyPath)

            cls.ONTO_CACHE[iri_hash] = onto

        return onto
예제 #6
0
#!/usr/bin/env python3

import os, shutil
import owlready2

CachePath = '/tmp/onto'

shutil.rmtree(CachePath, ignore_errors=True)
os.makedirs(CachePath, exist_ok=True)
owlready2.onto_path.append(CachePath)

import time

w = owlready2.World(filename=os.path.join(CachePath, 'firstDirect.sqlite3'),
                    exclusive=False)
print("FirstDirect")
onto1 = w.get_ontology(
    'https://raw.githubusercontent.com/inab/OEB-ontologies/master/oebDataFormats.owl'
).load()
w.save()
onto1.save()
res1 = onto1.search(label="participant")
import pprint
pprint.pprint(res1)

theRes = res1[0]
print("{0} => {1}".format(theRes.label, theRes.iri))

w = owlready2.World(filename=os.path.join(CachePath, 'firstIndirect1.sqlite3'),
                    exclusive=False)
print("FirstIndirect1")
예제 #7
0
#!/usr/bin/env python3

import os , shutil
import owlready2

CachePath = '/tmp/onto'

shutil.rmtree(CachePath,ignore_errors=True)
os.makedirs(CachePath,exist_ok=True)
owlready2.onto_path.append(CachePath)

import time

w = owlready2.World(filename='/tmp/onto/firstDirect.sqlite3', exclusive=False)
print("FirstDirect")
onto1 = w.get_ontology('https://raw.githubusercontent.com/inab/OEB-ontologies/master/oebDatasets.owl').load()
w.save()
onto1.save()
res1 = onto1.search(label = "participant")
import pprint
pprint.pprint(res1)

theRes = res1[0]
print("{0} => {1}".format(theRes.label,theRes.iri))

w = owlready2.World(filename='/tmp/onto/firstIndirect1.sqlite3', exclusive=False)
print("FirstIndirect1")
onto1 = w.get_ontology('https://w3id.org/oebDatasets/').load()
w.save()
onto1.save()
res1 = onto1.search(label = "participant")
예제 #8
0
    'owlready2': {},
    'reasonable': {},
}

# owlready2
import owlready2
for data_file in data_files:
    print(f"Benching owlready2 on {data_file}")
    all_samples['owlready2'][data_file] = []
    for i in range(N):
        g = rdflib.Graph()
        load_file(g, data_file)
        for ont_file in ontology_files:
            load_file(g, ont_file)
        g.serialize("_owlready2_input.ttl", format="ttl")
        world = owlready2.World()
        onto = world.get_ontology(f"file://./_owlready2_input.ttl").load()
        t0 = time.time()
        owlready2.sync_reasoner(world, infer_property_values=True)
        G = world.as_rdflib_graph()
        t1 = time.time()
        print(f"    owlready2: {data_file} took {t1-t0}")
        all_samples['owlready2'][data_file].append({
            'duration': t1 - t0,
            'triples': len(G)
        })

# OWLRL
import owlrl
for data_file in data_files:
    print(f"Benching owlrl on {data_file}")
예제 #9
0
파일: populate.py 프로젝트: ychalier/flont
 def load(self):
     """Load the ontology schema.
     """
     uri = "file://" + os.path.join(os.getcwd(), self.folder, "schema.owl")
     self.world = owlready2.World()
     self.ontology = self.world.get_ontology(uri).load()