コード例 #1
0
    def __init__(self, ident=None, key=None, **kwargs):
        try:
            super(DataObject, self).__init__(**kwargs)
        except BadConf:
            raise Exception(
                "You may need to connect to a database before continuing.")

        self.properties = []
        self.owner_properties = []
        self.po_cache = None
        """ A cache of property URIs and values. Used by RealSimpleProperty """

        if ident is not None:
            self._id = R.URIRef(ident)
        else:
            # Randomly generate an identifier if the derived class can't
            # come up with one from the start. Ensures we always have something
            # that functions as an identifier
            self._id = None

        if key is not None:
            self.setKey(key)

        self._variable = R.Variable("V" + str(RND.random()))
        DataObject.attach_property(self, RDFTypeProperty)
        self.rdf_type_property.set(self.rdf_type)
コード例 #2
0
ファイル: plugin.py プロジェクト: octadocs/octadocs
    def on_page_context(
        self,
        context: TemplateContext,
        page: Page,
        config: Config,
        nav: Page,
    ) -> TemplateContext:
        """Attach the views to certain pages."""
        page_iri = rdflib.URIRef(
            f'{LOCAL}{page.file.src_path}',
        )

        this_choices = list(map(
            operator.itemgetter(rdflib.Variable('this')),
            self.octiron.graph.query(
                'SELECT * WHERE { ?this octa:subjectOf ?page_iri }',
                initBindings={
                    'page_iri': page_iri,
                },
            ).bindings,
        ))

        if this_choices:
            context['this'] = this_choices[0]
        else:
            context['this'] = page_iri

        context['graph'] = self.octiron.graph
        context['iri'] = page_iri

        # noinspection PyTypedDict
        context['query'] = partial(
            query,
            instance=self.octiron.graph,
        )
        context['queries'] = self.stored_query

        context['local'] = LOCAL
        context['LOCAL'] = LOCAL
        context.update(self.octiron.namespaces)

        context['render'] = partial(
            render,
            octiron=self.octiron,
        )

        # Provide all the support namespaces into template context
        context['octiron'] = self.octiron
        context['link'] = partial(
            link,
            octiron=self.octiron,
        )

        # Page attributes
        page.iri = page_iri

        return context
コード例 #3
0
ファイル: dataObject.py プロジェクト: travs/PyOpenWorm
    def _graph_variable_to_var(cls, uri):

        from urlparse import urlparse
        u = urlparse(uri)
        x = u.path.split('/')
        #print uri
        if x[2] == 'variable':
            #print 'fragment = ', u.fragment
            return R.Variable(u.fragment)
        else:
            return uri
コード例 #4
0
ファイル: macros.py プロジェクト: octadocs/octadocs
def label(
    resource: rdflib.URIRef,
    graph: rdflib.ConjunctiveGraph
) -> Optional[str]:
    """Convert a URIRef to a clickable URL."""
    bindings = graph.query(
        'SELECT ?label WHERE { ?resource rdfs:label ?label . } ',
        initBindings={
            'resource': resource,
        }
    ).bindings

    if not bindings:
        return None

    return bindings[0][rdflib.Variable('label')].value
コード例 #5
0
ファイル: macros.py プロジェクト: octadocs/octadocs
def url(
    resource: rdflib.URIRef,
    graph: rdflib.ConjunctiveGraph
) -> Optional[str]:
    """Convert a URIRef to a clickable URL."""
    bindings = graph.query(
        'SELECT ?url WHERE { ?resource octa:subjectOf/octa:url ?url . } ',
        initBindings={
            'resource': resource,
        }
    ).bindings

    if not bindings:
        return None

    return '/' + bindings[0][rdflib.Variable('url')].value
コード例 #6
0
ファイル: simpleProperty.py プロジェクト: hytsang/PyOpenWorm
    def __init__(self, owner, resolver, **kwargs):
        super(SimpleProperty, self).__init__(**kwargs)
        self.owner = owner
        self._id = None
        self._variable = R.Variable("V" + str(RND.random()))
        if self.property_type == "ObjectProperty":
            self._pp = _ObjectValueProperty(conf=self.conf,
                                            owner_property=self,
                                            resolver=resolver)
        else:
            self._pp = _DatatypeValueProperty(conf=self.conf,
                                              owner_property=self,
                                              resolver=resolver)

        self.properties.append(self._pp)
        self._defined_values_cache = None
        self._defined_values_string_cache = None
コード例 #7
0
ファイル: dataObject.py プロジェクト: travs/PyOpenWorm
    def get(self):
        """ If the ``Property`` has had ``load`` or ``set`` called previously, returns
        the resulting values. Otherwise, queries the configured rdf graph for values
        which are set for the ``Property``'s owner.
        """
        import random as RND
        if self.id_is_variable():
            try:
                self._var = R.Variable("V" + str(int(RND.random() * 1E10)))
                gp = self.owner.graph_pattern(query=True)
                if self.property_type == 'DatatypeProperty':
                    q = u"SELECT DISTINCT {0} where {{ {1} . }}".format(
                        self._var.n3(), gp)
                elif self.property_type == 'ObjectProperty':
                    q = "SELECT DISTINCT {0} {0}_type where {{ {{ {1} }} . {0} rdf:type {0}_type }} ORDER BY {0}".format(
                        self._var.n3(), gp)
                else:
                    raise Exception("Inappropriate property type " +
                                    self.property_type +
                                    " in SimpleProperty::get")
            finally:
                self._var = None
            qres = self.rdf.query(q)
            if self.property_type == 'DatatypeProperty':
                for x in qres:
                    if x[0] is not None and not DataObject._is_variable(x[0]):
                        yield _rdf_literal_to_python(x[0])
            elif self.property_type == 'ObjectProperty':
                for x in _QueryResultsTypeResolver(self, qres)():
                    yield x
        else:
            for value in self.rdf.objects(self.identifier(query=False),
                                          self.value_property):
                if self.property_type == 'DatatypeProperty':
                    if value is not None and not DataObject._is_variable(
                            value):
                        yield _rdf_literal_to_python(value)
                elif self.property_type == 'ObjectProperty':
                    constructed_qres = set()
                    for rdf_type in self.rdf.objects(value, R.RDF['type']):
                        constructed_qres.add((value, rdf_type))

                    for ob in _QueryResultsTypeResolver(
                            self, constructed_qres)():
                        yield ob
コード例 #8
0
 def next_variable(cls):
     cls._next_variable_int += 1
     return R.Variable('a' + cls.__name__ + '_' + str(cls._next_variable_int))
コード例 #9
0
 def fixup2(o):
     if type(o) == rdflib.BNode:
         return rdflib.Variable(str(o.lower()))
     return o
コード例 #10
0
def load(kb, goal, identification, base):

    kb_stream, goal_stream = kb, goal
    implies = rdflib.URIRef("http://www.w3.org/2000/10/swap/log#implies")
    store = OrderedStore()
    kb_graph = rdflib.Graph(store=store, identifier=base)
    kb_conjunctive = rdflib.ConjunctiveGraph(store=store, identifier=base)
    kb_graph.parse(kb_stream, format='n3', publicID=base)
    if not nolog:
        log('---kb:')
        try:
            for l in kb_graph.serialize(format='n3').splitlines():
                log(l.decode('utf8'))
        except Exception as e:
            log(str(e))
        log('---kb quads:')
        for l in kb_conjunctive.serialize(format='nquads').splitlines():
            log(l.decode('utf8'))
        log('---')

    def fixup3(o):
        if isinstance(o, rdflib.Graph):
            #
            r = URIRef('file:///#' + o.identifier.n3().strip('_:'))
            #from IPython import embed; embed();
            return r
        return o

    def fixup2(o):
        if type(o) == rdflib.BNode:
            return rdflib.Variable(str(o.lower()))
        return o

    def fixup(spo):
        s, p, o = spo
        return (fixup2(s), fixup2(p), fixup2(o))

    rules = []
    head_triples_triples_id = 0
    kb_graph_triples = [fixup(x) for x in kb_graph.triples((None, None, None))]
    facts = GraphTuple(
        Triple(un_move_me_ize_pred(fixup3(x[1])),
               [fixup3(x[0]), fixup3(x[2])]) for x in kb_graph_triples)
    facts.id = head_triples_triples_id
    head_triples_triples_id += 1
    for kb_graph_triple_idx, (s, p, o) in enumerate(kb_graph_triples):
        if p == implies:
            body = Graph()
            head_triples = [
                fixup(x) for x in kb_conjunctive.triples((None, None, None, o))
            ]
            head_triples_triples = Graph()
            for triple in [
                    Triple(fixup3(x[1]),
                           [fixup3(x[0]), fixup3(x[2])]) for x in head_triples
            ]:
                move = False
                if triple.pred == URIRef(
                        'http://www.w3.org/1999/02/22-rdf-syntax-ns#move_me_to_body_first'
                ):
                    triple.pred = URIRef(
                        'http://www.w3.org/1999/02/22-rdf-syntax-ns#first')
                    move = True
                if triple.pred == URIRef(
                        'http://www.w3.org/1999/02/22-rdf-syntax-ns#move_me_to_body_rest'
                ):
                    triple.pred = URIRef(
                        'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest')
                    move = True
                if move:
                    body.append(triple)
                else:
                    head_triples_triples.append(triple)
            for body_triple in [
                    fixup(x)
                    for x in kb_conjunctive.triples((None, None, None, s))
            ]:
                body.append(
                    Triple((un_move_me_ize_pred(fixup3(body_triple[1]))),
                           [fixup3(body_triple[0]),
                            fixup3(body_triple[2])]))
            #body.reverse()
            to_expand = []
            for triple in head_triples_triples + body:
                for thing in triple.args:
                    if type(thing) == rdflib.Variable:
                        if str(thing).endswith('_'):
                            to_expand.append(thing)
            for thing in to_expand:
                body.insert(
                    0,
                    Triple(
                        rdflib.RDF.first,
                        [thing, rdflib.Variable(str(thing)[:-1] + 'f')]))
                body.insert(
                    0,
                    Triple(
                        rdflib.RDF.rest,
                        [thing, rdflib.Variable(str(thing)[:-1] + 'r')]))
            body = GraphTuple(body)
            head_triples_triples = GraphTuple(head_triples_triples)
            head_triples_triples.id = head_triples_triples_id
            head_triples_triples_id += 1
            #			if len(head_triples_triples) > 1:
            #				with open(_rules_file_name, 'a') as ru:
            #					ru.write("expanded rules for " + head_triples_triples.str(shorten) + ":\n")
            for head_triple_idx in range(len(head_triples_triples)):
                rules.append(Rule(head_triples_triples, head_triple_idx, body))
            if len(head_triples_triples) > 1:
                with open(_rules_file_name, 'a') as ru:
                    ru.write("\n\n")
        else:
            rules.append(Rule(facts, kb_graph_triple_idx, GraphTuple()))

    goal_rdflib_graph = rdflib.ConjunctiveGraph(store=OrderedStore(),
                                                identifier=base)
    goal_rdflib_graph.parse(goal_stream, format='n3', publicID=base)

    if not nolog:
        log('---goal:')
        try:
            for l in goal_rdflib_graph.serialize(format='n3').splitlines():
                log(l.decode('utf8'))
        except Exception as e:
            log(str(e))
        log('---goal nq:')
        for l in goal_rdflib_graph.serialize(format='nquads').splitlines():
            log(l.decode('utf8'))
        log('---')

    goal = Graph()
    for s, p, o in [
            fixup(x)
            for x in goal_rdflib_graph.triples((None, None, None, None))
    ]:
        goal.append(
            Triple(un_move_me_ize_pred(fixup3(p)),
                   [fixup3(s), fixup3(o)]))
    #goal.reverse()
    goal = GraphTuple(goal)
    query_rule = Rule(GraphTuple(), None, goal)
    return rules, query_rule, goal
コード例 #11
0
ファイル: variable.py プロジェクト: openworm/owmeta-core
 def __init__(self, name, **kwargs):
     super(Variable, self).__init__()
     self.var = rdflib.Variable(name)