summaryrefslogtreecommitdiff
path: root/rdflib/paths.py
blob: ea6a8b38d98c6acc2242308ddcfd5854ea702b0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
from six import PY3


__doc__ = """

This module implements the SPARQL 1.1 Property path operators, as
defined in:

http://www.w3.org/TR/sparql11-query/#propertypaths

In SPARQL the syntax is as follows:

+--------------------+-------------------------------------------------+
|Syntax              | Matches                                         |
+====================+=================================================+
|iri                 | An IRI. A path of length one.                   |
+--------------------+-------------------------------------------------+
|^elt                | Inverse path (object to subject).               |
+--------------------+-------------------------------------------------+
|elt1 / elt2         | A sequence path of elt1 followed by elt2.       |
+--------------------+-------------------------------------------------+
|elt1 | elt2         | A alternative path of elt1 or elt2              |
|                    | (all possibilities are tried).                  |
+--------------------+-------------------------------------------------+
|elt*                | A path that connects the subject and object     |
|                    | of the path by zero or more matches of elt.     |
+--------------------+-------------------------------------------------+
|elt+                | A path that connects the subject and object     |
|                    | of the path by one or more matches of elt.      |
+--------------------+-------------------------------------------------+
|elt?                | A path that connects the subject and object     |
|                    | of the path by zero or one matches of elt.      |
+--------------------+-------------------------------------------------+
|!iri or             | Negated property set. An IRI which is not one of|
|!(iri\ :sub:`1`\ |  | iri\ :sub:`1`...iri\ :sub:`n`.                  |
|... |iri\ :sub:`n`) | !iri is short for !(iri).                       |
+--------------------+-------------------------------------------------+
|!^iri or            | Negated property set where the excluded matches |
|!(^iri\ :sub:`1`\ | | are based on reversed path. That is, not one of |
|... |^iri\ :sub:`n`)| iri\ :sub:`1`...iri\ :sub:`n` as reverse paths. |
|                    | !^iri is short for !(^iri).                     |
+--------------------+-------------------------------------------------+
|!(iri\ :sub:`1`\ |  | A combination of forward and reverse            |
|...|iri\ :sub:`j`\ || properties in a negated property set.           |
|^iri\ :sub:`j+1`\ | |                                                 |
|... |^iri\ :sub:`n`)|                                                 |
+--------------------+-------------------------------------------------+
|(elt)               | A group path elt, brackets control precedence.  |
+--------------------+-------------------------------------------------+

This module is used internally be the SPARQL engine, but they property paths
can also be used to query RDFLib Graphs directly.

Where possible the SPARQL syntax is mapped to python operators, and property
path objects can be constructed from existing URIRefs.

>>> from rdflib import Graph, Namespace

>>> foaf=Namespace('http://xmlns.com/foaf/0.1/')

>>> ~foaf.knows
Path(~http://xmlns.com/foaf/0.1/knows)

>>> foaf.knows/foaf.name
Path(http://xmlns.com/foaf/0.1/knows / http://xmlns.com/foaf/0.1/name)

>>> foaf.name|foaf.firstName
Path(http://xmlns.com/foaf/0.1/name | http://xmlns.com/foaf/0.1/firstName)

Modifiers (?, *, +) are done using * (the multiplication operator) and
the strings '*', '?', '+', also defined as constants in this file.

>>> foaf.knows*OneOrMore
Path(http://xmlns.com/foaf/0.1/knows+)

The path objects can also be used with the normal graph methods.

First some example data:

>>> g=Graph()

>>> g=g.parse(data='''
... @prefix : <ex:> .
...
... :a :p1 :c ; :p2 :f .
... :c :p2 :e ; :p3 :g .
... :g :p3 :h ; :p2 :j .
... :h :p3 :a ; :p2 :g .
...
... :q :px :q .
...
... ''', format='n3') # doctest: +ELLIPSIS

>>> e=Namespace('ex:')

Graph contains:
>>> (e.a, e.p1/e.p2, e.e) in g
True

Graph generator functions, triples, subjects, objects, etc. :

>>> list(g.objects(e.c, (e.p3*OneOrMore)/e.p2)) # doctest: +NORMALIZE_WHITESPACE
[rdflib.term.URIRef(u'ex:j'), rdflib.term.URIRef(u'ex:g'),
    rdflib.term.URIRef(u'ex:f')]

A more complete set of tests:

>>> list(evalPath(g, (None, e.p1/e.p2, None)))==[(e.a, e.e)]
True
>>> list(evalPath(g, (e.a, e.p1|e.p2, None)))==[(e.a,e.c), (e.a,e.f)]
True
>>> list(evalPath(g, (e.c, ~e.p1, None))) == [ (e.c, e.a) ]
True
>>> list(evalPath(g, (e.a, e.p1*ZeroOrOne, None))) == [(e.a, e.a), (e.a, e.c)]
True
>>> list(evalPath(g, (e.c, e.p3*OneOrMore, None))) == [
...     (e.c, e.g), (e.c, e.h), (e.c, e.a)]
True
>>> list(evalPath(g, (e.c, e.p3*ZeroOrMore, None))) == [(e.c, e.c),
...     (e.c, e.g), (e.c, e.h), (e.c, e.a)]
True
>>> list(evalPath(g, (e.a, -e.p1, None))) == [(e.a, e.f)]
True
>>> list(evalPath(g, (e.a, -(e.p1|e.p2), None))) == []
True
>>> list(evalPath(g, (e.g, -~e.p2, None))) == [(e.g, e.j)]
True
>>> list(evalPath(g, (e.e, ~(e.p1/e.p2), None))) == [(e.e, e.a)]
True
>>> list(evalPath(g, (e.a, e.p1/e.p3/e.p3, None))) == [(e.a, e.h)]
True

>>> list(evalPath(g, (e.q, e.px*OneOrMore, None)))
[(rdflib.term.URIRef(u'ex:q'), rdflib.term.URIRef(u'ex:q'))]

>>> list(evalPath(g, (None, e.p1|e.p2, e.c)))
[(rdflib.term.URIRef(u'ex:a'), rdflib.term.URIRef(u'ex:c'))]

>>> list(evalPath(g, (None, ~e.p1, e.a))) == [ (e.c, e.a) ]
True
>>> list(evalPath(g, (None, e.p1*ZeroOrOne, e.c))) # doctest: +NORMALIZE_WHITESPACE
[(rdflib.term.URIRef(u'ex:c'), rdflib.term.URIRef(u'ex:c')),
 (rdflib.term.URIRef(u'ex:a'), rdflib.term.URIRef(u'ex:c'))]

>>> list(evalPath(g, (None, e.p3*OneOrMore, e.a))) # doctest: +NORMALIZE_WHITESPACE
[(rdflib.term.URIRef(u'ex:h'), rdflib.term.URIRef(u'ex:a')),
 (rdflib.term.URIRef(u'ex:g'), rdflib.term.URIRef(u'ex:a')),
 (rdflib.term.URIRef(u'ex:c'), rdflib.term.URIRef(u'ex:a'))]

>>> list(evalPath(g, (None, e.p3*ZeroOrMore, e.a))) # doctest: +NORMALIZE_WHITESPACE
[(rdflib.term.URIRef(u'ex:a'), rdflib.term.URIRef(u'ex:a')),
 (rdflib.term.URIRef(u'ex:h'), rdflib.term.URIRef(u'ex:a')),
 (rdflib.term.URIRef(u'ex:g'), rdflib.term.URIRef(u'ex:a')),
 (rdflib.term.URIRef(u'ex:c'), rdflib.term.URIRef(u'ex:a'))]

>>> list(evalPath(g, (None, -e.p1, e.f))) == [(e.a, e.f)]
True
>>> list(evalPath(g, (None, -(e.p1|e.p2), e.c))) == []
True
>>> list(evalPath(g, (None, -~e.p2, e.j))) == [(e.g, e.j)]
True
>>> list(evalPath(g, (None, ~(e.p1/e.p2), e.a))) == [(e.e, e.a)]
True
>>> list(evalPath(g, (None, e.p1/e.p3/e.p3, e.h))) == [(e.a, e.h)]
True

>>> list(evalPath(g, (e.q, e.px*OneOrMore, None)))
[(rdflib.term.URIRef(u'ex:q'), rdflib.term.URIRef(u'ex:q'))]

>>> list(evalPath(g, (e.c, (e.p2|e.p3)*ZeroOrMore, e.j)))
[(rdflib.term.URIRef(u'ex:c'), rdflib.term.URIRef(u'ex:j'))]

No vars specified:

>>> sorted(list(evalPath(g, (None, e.p3*OneOrMore, None)))) #doctest: +NORMALIZE_WHITESPACE
[(rdflib.term.URIRef(u'ex:c'), rdflib.term.URIRef(u'ex:a')),
 (rdflib.term.URIRef(u'ex:c'), rdflib.term.URIRef(u'ex:g')),
 (rdflib.term.URIRef(u'ex:c'), rdflib.term.URIRef(u'ex:h')),
 (rdflib.term.URIRef(u'ex:g'), rdflib.term.URIRef(u'ex:a')),
 (rdflib.term.URIRef(u'ex:g'), rdflib.term.URIRef(u'ex:h')),
 (rdflib.term.URIRef(u'ex:h'), rdflib.term.URIRef(u'ex:a'))]

.. versionadded:: 4.0

"""


from rdflib.term import URIRef, Node


# property paths

ZeroOrMore = '*'
OneOrMore = '+'
ZeroOrOne = '?'


class Path(object):
    def eval(self, graph, subj=None, obj=None):
        raise NotImplementedError()

    def __hash__(self):
        return hash(repr(self))

    def __eq__(self, other):
        return repr(self) == repr(other)

    def __lt__(self, other):
        if not isinstance(other, (Path, Node)):
            raise TypeError('unorderable types: %s() < %s()' % (
                repr(self), repr(other)))
        return repr(self) < repr(other)

    def __le__(self, other):
        if not isinstance(other, (Path, Node)):
            raise TypeError('unorderable types: %s() < %s()' % (
                repr(self), repr(other)))
        return repr(self) <= repr(other)

    def __ne__(self, other):
        return not self == other

    def __gt__(self, other):
        return not self <= other

    def __ge__(self, other):
        return not self < other


class InvPath(Path):

    def __init__(self, arg):
        self.arg = arg

    def eval(self, graph, subj=None, obj=None):
        for s, o in evalPath(graph, (obj, self.arg, subj)):
            yield o, s

    def __repr__(self):
        return "Path(~%s)" % (self.arg,)

    def n3(self):
        return '^%s' % self.arg.n3()


class SequencePath(Path):
    def __init__(self, *args):
        self.args = []
        for a in args:
            if isinstance(a, SequencePath):
                self.args += a.args
            else:
                self.args.append(a)

    def eval(self, graph, subj=None, obj=None):
        def _eval_seq(paths, subj, obj):
            if paths[1:]:
                for s, o in evalPath(graph, (subj, paths[0], None)):
                    for r in _eval_seq(paths[1:], o, obj):
                        yield s, r[1]

            else:
                for s, o in evalPath(graph, (subj, paths[0], obj)):
                    yield s, o

        def _eval_seq_bw(paths, subj, obj):
            if paths[:-1]:
                for s, o in evalPath(graph, (None, paths[-1], obj)):
                    for r in _eval_seq(paths[:-1], subj, s):
                        yield r[0], o

            else:
                for s, o in evalPath(graph, (subj, paths[0], obj)):
                    yield s, o

        if subj:
            return _eval_seq(self.args, subj, obj)
        elif obj:
            return _eval_seq_bw(self.args, subj, obj)
        else:  # no vars bound, we can start anywhere
            return _eval_seq(self.args, subj, obj)

    def __repr__(self):
        return "Path(%s)" % " / ".join(str(x) for x in self.args)

    def n3(self):
        return '/'.join(a.n3() for a in self.args)


class AlternativePath(Path):
    def __init__(self, *args):
        self.args = []
        for a in args:
            if isinstance(a, AlternativePath):
                self.args += a.args
            else:
                self.args.append(a)

    def eval(self, graph, subj=None, obj=None):
        for x in self.args:
            for y in evalPath(graph, (subj, x, obj)):
                yield y

    def __repr__(self):
        return "Path(%s)" % " | ".join(str(x) for x in self.args)

    def n3(self):
        return '|'.join(a.n3() for a in self.args)



class MulPath(Path):
    def __init__(self, path, mod):
        self.path = path
        self.mod = mod

        if mod == ZeroOrOne:
            self.zero = True
            self.more = False
        elif mod == ZeroOrMore:
            self.zero = True
            self.more = True
        elif mod == OneOrMore:
            self.zero = False
            self.more = True
        else:
            raise Exception('Unknown modifier %s' % mod)

    def eval(self, graph, subj=None, obj=None, first=True):
        if self.zero and first:
            if subj and obj:
                if subj == obj:
                    yield (subj, obj)
            elif subj:
                yield (subj, subj)
            elif obj:
                yield (obj, obj)

        def _fwd(subj=None, obj=None, seen=None):
            seen.add(subj)

            for s, o in evalPath(graph, (subj, self.path, None)):
                if not obj or o == obj:
                    yield s, o
                if self.more:
                    if o in seen:
                        continue
                    for s2, o2 in _fwd(o, obj, seen):
                        yield s, o2

        def _bwd(subj=None, obj=None, seen=None):
            seen.add(obj)

            for s, o in evalPath(graph, (None, self.path, obj)):
                if not subj or subj == s:
                    yield s, o
                if self.more:
                    if s in seen:
                        continue

                    for s2, o2 in _bwd(None, s, seen):
                        yield s2, o

        def _all_fwd_paths():
            if self.zero:
                seen1 = set()
                # According to the spec, ALL nodes are possible solutions
                # (even literals)
                # we cannot do this without going through ALL triples
                # unless we keep an index of all terms somehow
                # but lets just hope this query doesnt happen very often...
                for s, o in graph.subject_objects(None):
                    if s not in seen1:
                        seen1.add(s)
                        yield s, s
                    if o not in seen1:
                        seen1.add(o)
                        yield o, o

            seen = set()
            for s, o in evalPath(graph, (None, self.path, None)):
                if not self.more:
                    yield s, o
                else:
                    if s not in seen:
                        seen.add(s)
                        f = list(_fwd(s, None, set()))
                        for s1, o1 in f:
                            assert s1 == s
                            yield(s1, o1)

        done = set()  # the spec does by defn. not allow duplicates
        if subj:
            for x in _fwd(subj, obj, set()):
                if x not in done:
                    done.add(x)
                    yield x
        elif obj:
            for x in _bwd(subj, obj, set()):
                if x not in done:
                    done.add(x)
                    yield x
        else:
            for x in _all_fwd_paths():
                if x not in done:
                    done.add(x)
                    yield x

    def __repr__(self):
        return "Path(%s%s)" % (self.path, self.mod)

    def n3(self):
        return '%s%s' % (self.path.n3(), self.mod)



class NegatedPath(Path):
    def __init__(self, arg):
        if isinstance(arg, (URIRef, InvPath)):
            self.args = [arg]
        elif isinstance(arg, AlternativePath):
            self.args = arg.args
        else:
            raise Exception(
                'Can only negate URIRefs, InvPaths or ' +
                'AlternativePaths, not: %s' % (arg,))

    def eval(self, graph, subj=None, obj=None):
        for s, p, o in graph.triples((subj, None, obj)):
            for a in self.args:
                if isinstance(a, URIRef):
                    if p == a:
                        break
                elif isinstance(a, InvPath):
                    if (o, a.arg, s) in graph:
                        break
                else:
                    raise Exception('Invalid path in NegatedPath: %s' % a)
            else:
                yield s, o

    def __repr__(self):
        return "Path(! %s)" % ",".join(str(x) for x in self.args)

    def n3(self):
        return '!(%s)' % ('|'.join(self.args))


class PathList(list):
    pass


def path_alternative(self, other):
    """
    alternative path
    """
    if not isinstance(other, (URIRef, Path)):
        raise Exception('Only URIRefs or Paths can be in paths!')
    return AlternativePath(self, other)


def path_sequence(self, other):
    """
    sequence path
    """
    if not isinstance(other, (URIRef, Path)):
        raise Exception('Only URIRefs or Paths can be in paths!')
    return SequencePath(self, other)


def evalPath(graph, t):
    return ((s, o) for s, p, o in graph.triples(t))

def mul_path(p, mul):
    """
    cardinality path
    """
    return MulPath(p, mul)


def inv_path(p):
    """
    inverse path
    """
    return InvPath(p)


def neg_path(p):
    """
    negated path
    """
    return NegatedPath(p)



if __name__ == '__main__':

    import doctest
    doctest.testmod()
else:
    # monkey patch
    # (these cannot be directly in terms.py
    #  as it would introduce circular imports)

    URIRef.__or__ = path_alternative
    URIRef.__mul__ = mul_path
    URIRef.__invert__ = inv_path
    URIRef.__neg__ = neg_path
    URIRef.__truediv__ = path_sequence
    if not PY3:
        URIRef.__div__ = path_sequence

    Path.__invert__ = inv_path
    Path.__neg__ = neg_path
    Path.__mul__ = mul_path
    Path.__or__ = path_alternative
    Path.__truediv__ = path_sequence
    if not PY3:
        Path.__div__ = path_sequence