コード例 #1
0
ファイル: Meta.py プロジェクト: izadorapimenta/e-linguistics
    def new(uri, bases=(OWLThing, )):
        """
        'new' creates a new class in memory
        """

        #has to be string
        uri = quote(URIRef(uri))

        name = getLocalName(uri)

        #private list of instances
        _instances = []

        cls = OWLClass(name, bases, {
            'uri': uri,
            'name': name,
            '_instances': _instances,
            'bases': bases
        })

        #add the appropriate class methods
        cls.getURI = instancemethod(getURI, cls)
        cls.getInstances = instancemethod(getInstances, cls)

        return cls
コード例 #2
0
ファイル: Meta.py プロジェクト: Uduse/e-linguistics
    def new(uri):
        """
        constructor
        """
        uri=quote(URIRef(uri))
        name=getLocalName(uri)
        
        cls=OWLDatatypeProperty(name,(),{'uri':uri,'name':name})
        
        #add the appropriate class method
        cls.getURI = instancemethod(getURI,cls)

        return cls
コード例 #3
0
ファイル: Meta.py プロジェクト: izadorapimenta/e-linguistics
    def new(uri):
        """
        constructor
        """
        uri = quote(URIRef(uri))
        name = getLocalName(uri)

        cls = OWLDatatypeProperty(name, (), {'uri': uri, 'name': name})

        #add the appropriate class method
        cls.getURI = instancemethod(getURI, cls)

        return cls
コード例 #4
0
ファイル: Meta.py プロジェクト: Uduse/e-linguistics
    def new(uri):
        """
        Constructor to create class in memory
        """
        
        uri=quote(URIRef(uri))

        name=getLocalName(uri)
        
        cls=RDFProperty(name,(),{'uri':uri,'name':name})
    
        #add the appropriate class method
        cls.getURI = instancemethod(getURI,cls)

        return cls    
コード例 #5
0
ファイル: Meta.py プロジェクト: izadorapimenta/e-linguistics
    def new(uri):
        """
        Constructor to create class in memory
        """

        uri = quote(URIRef(uri))

        name = getLocalName(uri)

        cls = RDFProperty(name, (), {'uri': uri, 'name': name})

        #add the appropriate class method
        cls.getURI = instancemethod(getURI, cls)

        return cls
コード例 #6
0
ファイル: Meta.py プロジェクト: Uduse/e-linguistics
    def __call__(cls, *lstArgs, **dictArgs):
        """
        Creates an instance (OWL individual)
        """
        
        #create the instance of cls in memory
        instance = cls.__new__(cls)
        
        #doesn't seem to be necessary
        #instance.__init__()
        
        #set attributes

        #gives the illusion of instantiating multiple classes 
        #this is a dirty hack, but perhaps all that's possible given
        #Python's semantics
        #print type(instance)
       
        instance._types=[]
        
        if len(lstArgs)==2:
            instance._types=lstArgs[1]
        
        instance._types.append(__builtin__.type(instance))
        
        #store the type name for use in Ontology.py
        if len(lstArgs)==2:
            instance._type_names=[]
            for t in lstArgs[1]:
                instance._type_names.append(t.name)
       
        #quote is not strictly needed here, but it's added to be
        #consistent with the uri of 'cls' in 'new'
        instance.uri=quote(URIRef(lstArgs[0]))
        
        instance.name=getLocalName(instance.uri)

        #instance.uri=instance.uri.replace('#','/')
        

        #instance.getTypeNames=instancemethod(getTypeNames,instance,cls)

        instance.getURI = instancemethod(getURI,instance,cls)

        #print 'created a '+cls.name
        cls._instances.append(instance)

        return instance
コード例 #7
0
ファイル: Meta.py プロジェクト: izadorapimenta/e-linguistics
    def __call__(cls, *lstArgs, **dictArgs):
        """
        Creates an instance (OWL individual)
        """

        #create the instance of cls in memory
        instance = cls.__new__(cls)

        #doesn't seem to be necessary
        #instance.__init__()

        #set attributes

        #gives the illusion of instantiating multiple classes
        #this is a dirty hack, but perhaps all that's possible given
        #Python's semantics
        #print type(instance)

        instance._types = []

        if len(lstArgs) == 2:
            instance._types = lstArgs[1]

        instance._types.append(__builtin__.type(instance))

        #store the type name for use in Ontology.py
        if len(lstArgs) == 2:
            instance._type_names = []
            for t in lstArgs[1]:
                instance._type_names.append(t.name)

        #quote is not strictly needed here, but it's added to be
        #consistent with the uri of 'cls' in 'new'
        instance.uri = quote(URIRef(lstArgs[0]))

        instance.name = getLocalName(instance.uri)

        #instance.uri=instance.uri.replace('#','/')

        #instance.getTypeNames=instancemethod(getTypeNames,instance,cls)

        instance.getURI = instancemethod(getURI, instance, cls)

        #print 'created a '+cls.name
        cls._instances.append(instance)

        return instance
コード例 #8
0
ファイル: Meta.py プロジェクト: Uduse/e-linguistics
    def new(uri,bases=(OWLThing,)):
        """
        'new' creates a new class in memory
        """
        
        #has to be string
        uri=quote(URIRef(uri))
        
        name=getLocalName(uri)
        
        #private list of instances
        _instances=[]

        

        cls=OWLClass(name,bases,{'uri':uri,'name':name, '_instances':_instances, 'bases':bases})
    
        #add the appropriate class methods
        cls.getURI = instancemethod(getURI,cls)
        cls.getInstances = instancemethod(getInstances,cls)
       


        return cls    
コード例 #9
0
    def addAttr(self):
        """
        addAttr adds attributes to individuals. If the RDF graph contains:
            myindiv --pred--> obj
        then  add 'obj' as the attribute called 'pred'. Thus:
        
        >>> myindiv.pred
        >>> obj

        addAttr also adds triples to self.kb.
        
        
        :rtype: None
        """
        
        #iterate over all attributes 
        for attribute in self.kb.__dict__.iteritems():
            
            #print self.kb.__dict__

            predicate_objects = {} 
            
            #print attribute

            #only pick attributes that are instances of classes
            # (trick: since by def. all Py's types are type object, not lists)
            # 
            #if type(type(attribute[1])) is list: <--works too    

            if type(type(attribute[1])) in [OWLClass,RDFSResource]:
                
                
                #iterate over (predicate, object) pairs (see rdflib.Graph)
                for po in self.graph.predicate_objects(attribute[1].getURI()):
                    
                    #filter:
                    #   RDF:type <--- maybe more???
            
                    if po[0]!=URIRef(RDFtype.uri):
                        
                        if po[0] in predicate_objects.keys():
                            predicate_objects[po[0]].append(po[1])
                        else:
                            predicate_objects[po[0]] = [po[1]]
                
               
                for pred in predicate_objects.keys():
                    
                    #objects to assign to attribute
                    obj_list=[]

                    for obj in predicate_objects[pred]:
                        
                        if hasattr(self.graph,quote(getLocalName(obj))):
                            
                            #print getLocalName(obj)

                            obj_list.append(getattr(self.graph,quote(getLocalName(obj))))
                            
                        #there is no such class in the current ontology
                        #the object is of a type not in the current domain
                        else:
                            pass
                    
                    #assign the attribute its value
                    setattr(attribute[1],quote(getLocalName(pred)),obj_list)
コード例 #10
0
    def buildPyModel(self):
        """
        buildPyModel iterates over all triples in Graph and converts to Python's OOP model.

        :rtype: eltk.kb.KBComponent.KBComponent
        """


        #main loop to add OWL classes and object/data properties to KBComponent as attributes
        #
        #loop over subjects in triples (same as looping over triples) 
        #
        #This could be done using sparql queries, but that's less efficient
        
        self.kb.uri = self.graph.identifier

        for s in self.graph.subjects():
            
            #don't attempt to reassign instance attribute
            #   if it's already there
            #still not 100% sure what the problem is
            #so this is a hack. dc:'identifier' causes the problem
            if not hasattr(self.graph,quote(getLocalName(s))):   
                
                #loop over all predicate_objects 
                for i in self.graph.predicate_objects(s):
                    
                    #if an OWL class is found
                    if i[0]==URIRef(RDFtype.uri) and i[1]==OWLClass.uri:

                        #create the class and add as attribute
                        setattr(self.kb,quote(getLocalName(s)),OWLClass.new(s))
                    
                    #if an OWL ObjectProperty is found
                    elif i[0]==URIRef(RDFtype.uri) and i[1]==OWLObjectProperty.uri:
                        
                        #create ObjectProperties and add as attribute
                        setattr(self.kb,quote(getLocalName(s)),OWLObjectProperty.new(s))

                    #if an OWL DatatypeProperty is found
                    elif i[0]==URIRef(RDFtype.uri) and i[1]==OWLDatatypeProperty.uri:
                        
                        #create DatatypeProperty and add as attribute
                        setattr(self.kb,quote(getLocalName(s)),OWLDatatypeProperty.new(s))
        
        #add individuals to ontology
        #
        #keys: URIRef for the indiv
        #values:  list of types for individuals, that is:
        #   ind_class_pair[k][0] is the URIRef of first class
        #   ind_class_pair[k][1:] are the URIRefs for any other classes
        ind_class_pair=sparql.getIndividuals(self.graph) 
        

        for k in ind_class_pair.keys():    



            #get the local names of first class
            cls_name=getLocalName(ind_class_pair[k][0])
            
            #print cls_name 
            #
            #don't instantiate when cls_name is an OWL metatype
            #used when reading an OWL file
            #
            if cls_name not in ['Class','AnnotationProperty','ObjectProperty','DatatypeProperty','FunctionalProperty','InverseFunctionalProperty','TransitiveProperty','SymmetricProperty','Ontology']:
                
                #print cls_name

                #if an indiv. has only one type
                if len(ind_class_pair[k])==1:

                    #use quote for unicode symbols in local URI name
                    #
                    #instantiate a class 
                    
                    indiv = ''
                    
                    #this conditional added if concept isn't in resource, but is up a
                    #level, ie in GOLD or some other COPE 
                    #
                    #maybe 'import eltk' and use eltk.GOLD here???
                    #
                    if quote(cls_name) in dir(self.kb):
                        
                        indiv=getattr(self.kb,quote(cls_name)).__call__(k,[])
                
                    else:
                        
                        getattr(eltk.GOLD,quote(cls_name)).__call__(k,[])
                        
                    #assign the indiv to the ontology using the local
                    #name of the indiv
                    setattr(self.kb,quote(getLocalName(k)),indiv)
                    

                #if an indiv. has multiple types
                else:
                
                    #the list to hold multiple types
                    other_classes=[]
                    
                    #build list of classes
                    for c in ind_class_pair[k][1:]:
                        
                        #hack1, I don't know what wrong so I added this if
                        if c !=URIRef('http://www.w3.org/2002/07/owl#Class'):
                            other_classes.append(getattr(self.kb,getLocalName(c)))
                    
                    #get the class
                    
                    #hack2: the try statement is another hack related to OWLThing
                    #maybe related to problem above in hack1
                    try: 
                        indiv=getattr(self.kb,cls_name).__call__(k,other_classes)
                    except:
                        pass
                    #assign the indiv with more than one type 
                    #to the ontology using the local
                    #name of the indiv              
                    setattr(self.kb,quote(getLocalName(k)),indiv)

        #######LOOP to add base classes#######
        for attr_name in dir(self.kb):
            
            attr = getattr(self.kb,attr_name)

            if type(attr) is OWLClass:

                #start w. list
                bases = []
                
                
                list_base_urirefs = sparql.getBaseClasses(self.graph,attr.uri)
                
                for base_uriref in list_base_urirefs:
                    
                    bases.append(getattr(self.kb,getLocalName(base_uriref)))

                #print attr.__bases__ 
                #print object 
                
                #if attr.__bases__ != (object,):
                #print tuple(bases,)   
                
                if bases != []:
                    
                    try:
                        attr.__bases__ = tuple(bases,) 
                    except:
                        print 'MRO problem with: ',attr
        
        self.addAttr()
        self.addFunc() 

        return self.kb