Depends on RDF::Queryable, SemanticAccessors and SubjectMethods
504926
def each(opts={}, &block)
      attribute_definitions.map{|name, attribute| attribute.to_rdf(self, opts)}.each(&block)
    end
1115086
def run_sparql_on(q, ontology):
    
    logging.info("Connecting to " + ontology.value + " SPARQL endpoint...")
    sparql = SPARQLWrapper(ontology.value)
    logging.info("Made wrapper: {}".format(sparql))
    sparql.setQuery(q)
    sparql.setReturnFormat(JSON)
    logging.info("Query: {}".format(q))
    results = sparql.query().convert()
    bindings = results['results']['bindings']
    logging.info("Rows: {}".format(len(bindings)))
    for r in bindings:
        curiefy(r)
    return bindings
82968
def predicate_to_IRI(self, predicate: ShExDocParser.PredicateContext) -> ShExJ.IRIREF:
        
        if predicate.iri():
            return self.iri_to_iriref(predicate.iri())
        else:
            return RDF_TYPE
451702
def url_from_rdf(rdf, prop):
    '''
    
    '''
    value = rdf.value(prop)
    if isinstance(value, (URIRef, Literal)):
        return value.toPython()
    elif isinstance(value, RdfResource):
        return value.identifier.toPython()
604352
def entityTriples(rdfGraph, anEntity, excludeProps=False, excludeBNodes=False,
                  orderProps=[RDF, RDFS, OWL.OWLNS, DC.DCNS]):
    
    temp = []
    if not excludeProps:
        excludeProps = []

    # extract predicate/object
    for x, y, z in rdfGraph.triples((anEntity, None, None)):
        if excludeBNodes and isBlankNode(z):
            continue
        if y not in excludeProps:
            temp += [(y, z)]

    # sorting
    if type(orderProps) == type([]):
        orderedUris = sortByNamespacePrefix([y for y, z in temp], orderProps)  # order props only
        orderedUris = [(n + 1, x) for n, x in
                       enumerate(orderedUris)]  # create form: [(1, 'something'),(2,'bobby'),(3,'suzy'),(4,'crab')]
        rank = dict((key, rank) for (rank, key) in orderedUris)  # create dict to pass to sorted procedure
        temp = sorted(temp, key=lambda tup: rank.get(tup[0]))
    elif orderProps:  # default to alpha sorting unless False
        temp = sorted(temp, key=lambda tup: tup[0])

    # if niceURI:
    #	temp = [(uri2niceString(ontology, y), z) for y,z in temp]

    return temp
462263
def transform_literals(rdf, literalmap):
    """"""

    affected_types = (SKOS.Concept, SKOS.Collection,
                      SKOSEXT.DeprecatedConcept)

    props = set()
    for t in affected_types:
        for conc in rdf.subjects(RDF.type, t):
            for p, o in rdf.predicate_objects(conc):
                if isinstance(o, Literal) \
                   and (p in literalmap or not in_general_ns(p)):
                    props.add(p)

    for p in props:
        if mapping_match(p, literalmap):
            newval = mapping_get(p, literalmap)
            newuris = [v[0] for v in newval]
            logging.debug("transform literal %s -> %s", p, str(newuris))
            replace_predicate(
                rdf, p, newuris, subjecttypes=affected_types)
        else:
            logging.info("Don't know what to do with literal %s", p)
1236613
def skos_transitive(rdf, narrower=True):
    """"""
    for conc in rdf.subjects(RDF.type, SKOS.Concept):
        for bt in rdf.transitive_objects(conc, SKOS.broader):
            if bt == conc:
                continue
            rdf.add((conc, SKOS.broaderTransitive, bt))
            if narrower:
                rdf.add((bt, SKOS.narrowerTransitive, conc))
1062129
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'text' in _dict:
            args['text'] = _dict.get('text')
        if 'entities' in _dict:
            args['entities'] = [
                SemanticRolesEntity._from_dict(x)
                for x in (_dict.get('entities'))
            ]
        if 'keywords' in _dict:
            args['keywords'] = [
                SemanticRolesKeyword._from_dict(x)
                for x in (_dict.get('keywords'))
            ]
        return cls(**args)
551038
def process(source, target, rdfsonly, base=None, logger=logging):
    '''
    

    '''
    for link in source.match():
        s, p, o = link[:3]
        #SKip docheader statements
        if s == (base or '') + '@docheader': continue
        if p in RESOURCE_MAPPING: p = RESOURCE_MAPPING[p]
        if o in RESOURCE_MAPPING: o = RESOURCE_MAPPING[o]
        if p == VERSA_BASEIRI + 'refines':
            tlinks = list(source.match(s, TYPE_REL))
            if tlinks:
                if tlinks[0][TARGET] == VERSA_BASEIRI + 'Resource':
                    p = I(RDFS_NAMESPACE + 'subClassOf')
                elif tlinks[0][TARGET] == VERSA_BASEIRI + 'Property':
                    p = I(RDFS_NAMESPACE + 'subPropertyOf')
        if p == VERSA_BASEIRI + 'properties':
            suri = I(iri.absolutize(s, base)) if base else s
            target.add((URIRef(o), URIRef(RDFS_NAMESPACE + 'domain'), URIRef(suri)))
            continue
        if p == VERSA_BASEIRI + 'value':
            if o not in ['Literal', 'IRI']:
                ouri = I(iri.absolutize(o, base)) if base else o
                target.add((URIRef(s), URIRef(RDFS_NAMESPACE + 'range'), URIRef(ouri)))
                continue
        s = URIRef(s)
        #Translate v:type to rdf:type
        p = RDF.type if p == TYPE_REL else URIRef(p)
        o = URIRef(o) if isinstance(o, I) else Literal(o)
        if not rdfsonly or p.startswith(RDF_NAMESPACE) or p.startswith(RDFS_NAMESPACE):
            target.add((s, p, o))
    return
593366
def skos_hierarchical_mappings(rdf, narrower=True):
    
    for s, o in rdf.subject_objects(SKOS.broadMatch):
        rdf.add((s, SKOS.broader, o))
        if narrower:
            rdf.add((o, SKOS.narrowMatch, s))
            rdf.add((o, SKOS.narrower, s))

    for s, o in rdf.subject_objects(SKOS.narrowMatch):
        rdf.add((o, SKOS.broadMatch, s))
        rdf.add((o, SKOS.broader, s))
        if narrower:
            rdf.add((s, SKOS.narrower, o))
        else:
            rdf.remove((s, SKOS.narrowMatch, o))
1338488
def _rdf_graph_from_ntriples_string(ntriples_string, graph=nil)
      graph ||= RDF::Graph.new
      RDF::Reader.for(:ntriples).new(ntriples_string) do |reader|
        reader.each_statement do |statement|
          graph << statement
        end
      end
      graph
    end
719324
def parse_owl_rdf(iri):
    
    g = nx.DiGraph(IRI=iri)
    o = Ontospy(iri)

    for cls in o.classes:
        g.add_node(cls.locale, type='Class')

        for parent in cls.parents():
            g.add_edge(cls.locale, parent.locale, type='SubClassOf')

        for instance in cls.instances():
            _, frag = urldefrag(instance)
            g.add_edge(frag, cls.locale, type='ClassAssertion')

    return g
960078
def rdf_type(new_rdf_type)
      self._RDF_TYPE = RDF::URI.new(new_rdf_type.to_s)
      field :rdf_type, RDF.type, :multivalued => true, :is_uri => true # things can have more than 1 type and often do
    end
1031563
def Validate(self, type_names):
    """"""
    errs = [n for n in self._RDFTypes(type_names) if not self._GetClass(n)]
    if errs:
      raise DefinitionError("Undefined RDF Types: %s" % ",".join(errs))
284043
def process_rdfgraph(self, rg, ont=None):
        
        # TODO: ontology metadata
        if ont is None:
            ont = Ontology()
            subjs = list(rg.subjects(RDF.type, SKOS.ConceptScheme))
            if len(subjs) == 0:
                logging.warning("No ConceptScheme")
            else:
                ont.id = self._uri2id(subjs[0])
            
        subset_map = {}
        for concept in rg.subjects(RDF.type, SKOS.Concept):
            for s in self._get_schemes(rg, concept):
                subset_map[self._uri2id(s)] = s
                
        for concept in sorted(list(rg.subjects(RDF.type, SKOS.Concept))):
            concept_uri = str(concept)
            id=self._uri2id(concept)
            logging.info("ADDING: {}".format(id))
            ont.add_node(id, self._get_label(rg,concept))
                    
            for defn in rg.objects(concept, SKOS.definition):
                if (defn.language == self.lang):
                    td = TextDefinition(id, escape_value(defn.value))
                    ont.add_text_definition(td)
                    
            for s in rg.objects(concept, SKOS.broader):
                ont.add_parent(id, self._uri2id(s))
                
            for s in rg.objects(concept, SKOS.related):
                ont.add_parent(id, self._uri2id(s), self._uri2id(SKOS.related))
                
            for m in rg.objects(concept, SKOS.exactMatch):
                ont.add_xref(id, self._uri2id(m))
                
            for m in rg.objects(concept, SKOS.altLabel):
                syn = Synonym(id, val=self._uri2id(m))
                ont.add_synonym(syn)
                
            for s in self._get_schemes(rg,concept):
                ont.add_to_subset(id, self._uri2id(s))
                
        return ont
599033
def get_objects(self, subject=None, predicate=None):
        """"""

        for triple in self.triples:

            # Filter out non-matches
            if ((subject and triple['subject'] != subject) or
                (predicate and triple['predicate'] != predicate)):
                continue

            yield triple['object']
1212433
def replace_uri(rdf, fromuri, touri):
    
    replace_subject(rdf, fromuri, touri)
    replace_predicate(rdf, fromuri, touri)
    replace_object(rdf, fromuri, touri)