Esempio n. 1
0
    def __getTopProps(self, classPredicate='', includeImplicit=False):
        """ 
		Finds the topclass in an ontology (works also with multiple inheritance)

		"""
        returnlist = []
        searchspace = []

        if classPredicate not in [
                "", 'rdf.property', 'owl.objectproperty',
                'owl.datatypeproperty', 'owl.annotationproperty'
        ]:
            raise exceptions.Error(
                "ClassPredicate must be blank or either 'rdf.property' or 'owl.objectproperty' or 'owl.datatypeproperty' or 'owl.annotationproperty'"
            )

        if classPredicate == "rdf.property" or classPredicate == "":
            searchspace += self.allrdfproperties
        if classPredicate == "owl.objectproperty" or classPredicate == "":
            searchspace += self.allobjproperties
        if classPredicate == "owl.datatypeproperty" or classPredicate == "":
            searchspace += self.alldataproperties
        if classPredicate == "owl.annotationproperty" or classPredicate == "":
            searchspace += self.allannotationproperties

        if includeImplicit:
            searchspace += self.allinferredproperties

        for eachprop in searchspace:
            x = self.propertyDirectSupers(eachprop)
            if not x:
                returnlist.append(eachprop)

        return sort_uri_list_by_name(returnlist)
Esempio n. 2
0
	def propertyFind(self, name, exact = False, classPredicate = "", includeImplicit=False):
		"""
		Find a property from its name (string representation of URI or part of it) within an ontology graph.

		Returns a list that in the 'exact' case will have one element only

		classPredicate: one of "rdf.property", "owl.objectproperty", "owl.datatypeproperty"
		
		EG:
		> onto.propertyFind("purl.org", classPredicate="owl.objectproperty")
		"""
		temp = []
		searchspace = []
				
		if classPredicate not in ["", 'rdf.property', 'owl.objectproperty','owl.datatypeproperty']:
			raise exceptions.Error("ClassPredicate must be blank or either 'rdf.property' or 'owl.objectproperty' or 'owl.datatypeproperty'")

		if classPredicate == "rdf.property" or classPredicate == "":
			searchspace += self.allrdfproperties
		if classPredicate == "owl.objectproperty" or classPredicate == "":
			searchspace += self.allobjproperties
		if classPredicate == "owl.datatypeproperty" or classPredicate == "": 
			searchspace += self.alldataproperties
		if includeImplicit:
			searchspace += self.allinferredproperties				   
		
		if name:
			for x in searchspace:
				if exact:
					if x.__str__().lower() == str(name).lower():
						return [x]
				else:
					if x.__str__().lower().find(str(name).lower()) >= 0:
						temp.append(x)
		return temp
Esempio n. 3
0
	def instanceAddForClass(self, aClass, anInstance, ns = None):
		""" 
		2011-07-26: 
		Adds or creates a class-instance to the session-graph (and returns the instance).
		If a URIRef object is passed, that's ok. Also, if a string is passed, we create a URI using the 
		
		default namespace for the Session graph.
		p.s. No need to check for duplicates: rdflib does that already!
		"""
		if aClass in self.allclasses:
			if type(anInstance) == URIRef:
				self.sessionGraph.add((anInstance, RDF.type, aClass))
				return anInstance
			elif type(anInstance) == type("string") or type(anInstance) == type(u"unicode"):
				ns = ns or self.sessionNS  # needed?
				self.sessionGraph.add((ns[anInstance], RDF.type, aClass))
				return ns[anInstance]
			else:
				raise exceptions.Error("Instance must be a URIRef object or a String")
		else:
			raise exceptions.Error("Class is not available in current ontology")
Esempio n. 4
0
    def __getAllProperties(self, classPredicate="", includeImplicit=False):
        """
		Extracts all the properties declared in a model.
		
		Args:
		> classPredicate: a mapping to one of the allowed OWL props
		
		> includeImplicit: gets all predicates from triples and infers that they are all RDF properties (even if not explicitly declared)
		
		Corresponding RDF predicates: 
		OWL.ObjectProperty, OWL.DatatypeProperty, OWL.AnnotationProperty, RDF.Property 

		"""
        rdfGraph = self.rdfGraph
        exit = {}

        if classPredicate not in [
                "", 'rdf.property', 'owl.objectproperty',
                'owl.datatypeproperty', 'owl.annotationproperty'
        ]:
            raise exceptions.Error(
                "ClassPredicate must be either 'rdf.property' or 'owl.objectproperty' or 'owl.datatypeproperty' or 'owl.annotationproperty' "
            )

        def addIfYouCan(x, mydict):
            if x not in mydict:
                mydict[x] = None
            return mydict

        if classPredicate == "rdf.property" or "":
            for s in rdfGraph.subjects(RDF.type, RDF.Property):
                exit = addIfYouCan(s, exit)
            if includeImplicit:
                # includes everything that appears as a predicate;
                # below we add also owl properties due to inheritance: they are instances of of rdf:property subclasses
                for s in rdfGraph.predicates(None, None):
                    exit = addIfYouCan(s, exit)

        if classPredicate == "owl.objectproperty" or classPredicate == "" or includeImplicit:
            for s in rdfGraph.subjects(RDF.type, OWL.ObjectProperty):
                exit = addIfYouCan(s, exit)
        if classPredicate == "owl.datatypeproperty" or classPredicate == "" or includeImplicit:
            for s in rdfGraph.subjects(RDF.type, OWL.DatatypeProperty):
                exit = addIfYouCan(s, exit)

        if classPredicate == "owl.annotationproperty" or classPredicate == "" or includeImplicit:
            for s in rdfGraph.subjects(RDF.type, OWL.AnnotationProperty):
                exit = addIfYouCan(s, exit)

        # get a list
        exit = exit.keys()
        return sort_uri_list_by_name(exit)
 def __init__(self, uri, language=""):
     super(Inspector, self).__init__()
     self.rdfGraph = ConjunctiveGraph()
     try:
         self.rdfGraph.parse(uri, format="application/rdf+xml")
     except:
         try:
             self.rdfGraph.parse(uri, format="n3")
         except:
             raise exceptions.Error("Could not parse the file! Is it a valid RDF/OWL ontology?")
     finally:
         self.baseURI = self.get_OntologyURI() or uri
         self.allclasses = self.__getAllClasses(includeDomainRange=True, includeImplicit=True, removeBlankNodes=False, excludeRDF_OWL=False)
Esempio n. 6
0
	def classInstances(self, aClass, onlydirect = True):
		""" 
		Gets all the (direct by default) instances of a class
		"""
		if aClass in self.allclasses:
			returnlist = []
			for s, v, o in self.rdfGraph.triples((None , RDF.type , aClass)):
				returnlist.append(s)
			if not onlydirect:
				for sub in self.classAllSubs(aClass):
					for s, v, o in self.rdfGraph.triples((None , RDF.type , sub)):
						returnlist.append(s)
			return sort_uri_list_by_name(remove_duplicates(returnlist))
		else:
			raise exceptions.Error("Class is not available in current ontology")
Esempio n. 7
0
    def __getAllClasses(self, classPredicate = "", removeBlankNodes = True):
        """
        Extracts all the classes from a model
        We use the RDFS and OWL predicate by default; also, we extract non explicitly declared classes
        """

        rdfGraph = self.rdfGraph
        exit = []

        if not classPredicate:
            for s, v, o in rdfGraph.triples((None, RDF.type , OWL.Class)):
                exit.append(s)
            for s, v, o in rdfGraph.triples((None, RDF.type , RDFS.Class)):
                exit.append(s)

            # this extra routine makes sure we include classes not declared explicitly
            # eg when importing another onto and subclassing one of its classes...
            for s, v, o in rdfGraph.triples((None, RDFS.subClassOf , None)):
                if s not in exit:
                    exit.append(s)
                if o not in exit:
                    exit.append(o)

            # this extra routine includes classes found only in rdfs:domain and rdfs:range definitions
            for s, v, o in rdfGraph.triples((None, RDFS.domain , None)):
                if o not in exit:
                    exit.append(o)
            for s, v, o in rdfGraph.triples((None, RDFS.range , None)):
                if o not in exit:
                    exit.append(o)

        else:
            if classPredicate == "rdfs" or classPredicate == "rdf":
                for s, v, o in rdfGraph.triples((None, RDF.type , RDFS.Class)):
                    exit.append(s)
            elif classPredicate == "owl":
                for s, v, o in rdfGraph.triples((None, RDF.type , OWL.Class)):
                    exit.append(s)
            else:
                raise exceptions.Error("ClassPredicate must be either rdf, rdfs or owl")

        exit = remove_duplicates(exit)

        if removeBlankNodes:
            exit = [x for x in exit if not self.__isBlankNode(x)]

        return sort_uri_list_by_name(exit)
Esempio n. 8
0
    def __init__(self, uri, language=""):
        super(OntoInspector, self).__init__()

        self.rdfGraph = ConjunctiveGraph()
        try:
            self.rdfGraph.parse(uri, format="xml")
        except:
            try:
                self.rdfGraph.parse(uri, format="n3")
            except:
                raise exceptions.Error("Could not parse the file! Is it a valid RDF/OWL ontology?")

        finally:
            # let's cache some useful info for faster access
            self.baseURI = self.get_OntologyURI() or uri
            self.allclasses = self.__getAllClasses(classPredicate)
            self.toplayer = self.__getTopclasses()
            self.tree = self.__getTree()
Esempio n. 9
0
 def setSessionGraphNamespace(self, ns):
     if ns.startswith("http://"):
         self.sessionNS = ns
     else:
         raise exceptions.Error(
             "Please provide a URI starting with 'http://'..")