forked from gonum/gonum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
equi_canonical.go
576 lines (537 loc) · 13.3 KB
/
equi_canonical.go
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
// Copyright ©2021 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rdf
import (
"errors"
"sort"
)
// Throughout, the comments refer to doi:10.1145/3068333 which should be
// understood as a synonym for http://aidanhogan.com/docs/rdf-canonicalisation.pdf
// although there are differences between the two, see http://aidanhogan.com/#errataH17.
// Where there are differences, the document at http://aidanhogan.com/ is the
// canonical truth. The DOI reference is referred to for persistence.
// Lean returns an RDF core of g that entails g. If g contains any non-zero
// labels, Lean will return a non-nil error and a core of g assuming no graph
// labels exist.
//
// See http://aidanhogan.com/docs/rdf-canonicalisation.pdf for details of
// the algorithm.
func Lean(g []*Statement) ([]*Statement, error) {
// BUG(kortschak): Graph leaning does not take into account graph label terms
// since the formal semantics for a multiple graph data model have not been
// defined. See https://www.w3.org/TR/rdf11-datasets/#declaring.
var (
hasBlanks bool
err error
)
for _, s := range g {
if isBlank(s.Subject.Value) || isBlank(s.Object.Value) {
hasBlanks = true
if err != nil {
break
}
}
if s.Label.Value != "" && err == nil {
err = errors.New("rdf: data-set contains graph names")
if hasBlanks {
break
}
}
}
if hasBlanks {
g = lean(&dfs{}, g)
}
return g, err
}
// removeRedundantBnodes removes blank nodes whose edges are a subset of
// another term in the RDF graph.
//
// This is algorithm 4 in doi:10.1145/3068333.
func removeRedundantBnodes(g []*Statement) []*Statement {
g = append(g[:0:0], g...)
for {
edges := make(map[string]map[triple]bool)
for _, s := range g {
for i, t := range []string{
s.Subject.Value,
s.Object.Value,
} {
e, ok := edges[t]
if !ok {
e = make(map[triple]bool)
edges[t] = e
}
switch i {
case 0:
e[triple{s.Predicate.Value, s.Object.Value, "+"}] = true
case 1:
e[triple{s.Predicate.Value, s.Subject.Value, "-"}] = true
}
}
}
seen := make(map[string]bool)
bNodes := make(map[string]bool)
terms := make(map[string]bool)
for _, s := range g {
for _, t := range []string{
s.Subject.Value,
s.Predicate.Value,
s.Object.Value,
} {
terms[t] = true
if isBlank(t) {
bNodes[t] = true
} else {
seen[t] = true
}
}
}
redundant := make(map[string]bool)
for x := range bNodes {
for xp := range terms {
if isProperSubset(edges[x], edges[xp]) || (seen[xp] && isEqualEdges(edges[x], edges[xp])) {
redundant[x] = true
break
}
}
seen[x] = true
}
n := len(g)
for i := 0; i < len(g); {
if !redundant[g[i].Subject.Value] && !redundant[g[i].Object.Value] {
i++
continue
}
g[i], g = g[len(g)-1], g[:len(g)-1]
}
if n == len(g) {
return g
}
}
}
type triple [3]string
func isProperSubset(a, b map[triple]bool) bool {
for k := range a {
if !b[k] {
return false
}
}
return len(a) < len(b)
}
func isEqualEdges(a, b map[triple]bool) bool {
if len(a) != len(b) {
return false
}
for k := range a {
if !b[k] {
return false
}
}
return true
}
// findCandidates finds candidates for blank nodes and blank nodes that are fixed.
//
// This is algorithm 5 in doi:10.1145/3068333.
func findCandidates(g []*Statement) ([]*Statement, map[string]bool, map[string]map[string]bool, bool) {
g = removeRedundantBnodes(g)
edges := make(map[triple]bool)
f := make(map[string]bool)
for _, s := range g {
sub := s.Subject.Value
prd := s.Predicate.Value
obj := s.Object.Value
edges[triple{sub, prd, obj}] = true
edges[triple{sub, prd, "*"}] = true
edges[triple{"*", prd, obj}] = true
switch {
case isBlank(sub) && isBlank(obj):
f[sub] = false
f[obj] = false
case isBlank(sub):
if _, ok := f[sub]; !ok {
f[sub] = true
}
case isBlank(obj):
if _, ok := f[obj]; !ok {
f[obj] = true
}
}
}
for k, v := range f {
if !v {
delete(f, k)
}
}
if len(f) == 0 {
f = nil
}
cands := make(map[string]map[string]bool)
bnodes := make(map[string]bool)
for _, s := range g {
for _, b := range []string{
s.Subject.Value,
s.Object.Value,
} {
if !isBlank(b) {
continue
}
bnodes[b] = true
if f[b] {
cands[b] = map[string]bool{b: true}
} else {
terms := make(map[string]bool)
for _, s := range g {
for _, t := range []string{
s.Subject.Value,
s.Predicate.Value,
s.Object.Value,
} {
terms[t] = true
}
}
cands[b] = terms
}
}
}
if isEqualTerms(f, bnodes) {
return g, f, cands, true
}
for {
bb := make(map[string]bool)
for b := range bnodes {
if !f[b] {
bb[b] = true
}
}
for b := range bb {
for x := range cands[b] {
if x == b {
continue
}
for _, s := range g {
if s.Subject.Value != b {
continue
}
prd := s.Predicate.Value
obj := s.Object.Value
if (inILF(obj, f) && !edges[triple{x, prd, obj}]) || (bb[obj] && !edges[triple{x, prd, "*"}]) {
delete(cands[b], x)
break
}
}
if !cands[b][x] {
continue
}
for _, s := range g {
if s.Object.Value != b {
continue
}
sub := s.Subject.Value
prd := s.Predicate.Value
if (inIF(sub, f) && !edges[triple{sub, prd, x}]) || (bb[sub] && !edges[triple{"*", prd, x}]) {
delete(cands[b], x)
break
}
}
}
}
fp := f
f = make(map[string]bool)
for b := range fp {
f[b] = true
}
for b := range bb { // Mark newly fixed blank nodes.
if len(cands[b]) == 1 && cands[b][b] {
f[b] = true
}
}
allFixed := isEqualTerms(f, bnodes)
if isEqualTerms(fp, f) || allFixed {
if len(f) == 0 {
f = nil
}
return g, f, cands, allFixed
}
}
}
// inILF returns whether t is in IL or F.
func inILF(t string, f map[string]bool) bool {
return isIRI(t) || isLiteral(t) || f[t]
}
// inIF returns whether t is in I or F.
func inIF(t string, f map[string]bool) bool {
return isIRI(t) || f[t]
}
// dfs is a depth-first search strategy.
type dfs struct{}
// lean returns a core of the RDF graph g using the given strategy.
//
// This is lines 1-9 of algorithm 6 in doi:10.1145/3068333.
func lean(strategy *dfs, g []*Statement) []*Statement {
foundBnode := false
search:
for _, s := range g {
for _, t := range []string{
s.Subject.Value,
s.Object.Value,
} {
if isBlank(t) {
foundBnode = true
break search
}
}
}
if !foundBnode {
return g
}
g, fixed, cands, allFixed := findCandidates(g)
if allFixed {
return g
}
for _, s := range g {
if isBlank(s.Subject.Value) && isBlank(s.Object.Value) {
mu := make(map[string]string, len(fixed))
for b := range fixed {
mu[b] = b
}
mu = findCoreEndomorphism(strategy, g, cands, mu)
return applyMu(g, mu)
}
}
return g
}
// findCoreEndomorphism returns a core solution using the given strategy.
//
// This is lines 10-14 of algorithm 6 in doi:10.1145/3068333.
func findCoreEndomorphism(strategy *dfs, g []*Statement, cands map[string]map[string]bool, mu map[string]string) map[string]string {
var q []*Statement
preds := make(map[string]int)
seen := make(map[triple]bool)
for _, s := range g {
preds[s.Predicate.Value]++
if isBlank(s.Subject.Value) && isBlank(s.Object.Value) {
if seen[triple{s.Subject.Value, s.Predicate.Value, s.Object.Value}] {
continue
}
seen[triple{s.Subject.Value, s.Predicate.Value, s.Object.Value}] = true
q = append(q, s)
}
}
sort.Slice(q, func(i, j int) bool {
return selectivity(q[i], cands, preds) < selectivity(q[j], cands, preds)
})
return strategy.evaluate(g, q, cands, mu)
}
// selectivity returns the selectivity heuristic score for s. Lower scores
// are more selective.
func selectivity(s *Statement, cands map[string]map[string]bool, preds map[string]int) int {
return min(len(cands[s.Subject.Value])*len(cands[s.Object.Value]), preds[s.Predicate.Value])
}
// evaluate returns an endomorphism using a DFS strategy.
//
// This is lines 25-32 of algorithm 6 in doi:10.1145/3068333.
func (st *dfs) evaluate(g, q []*Statement, cands map[string]map[string]bool, mu map[string]string) map[string]string {
mu = st.search(g, q, cands, mu)
for len(mu) != len(codom(mu)) {
mupp := fixedFrom(cands)
mup := findCoreEndomorphism(st, applyMu(g, mu), cands, mupp)
if isAutomorphism(mup) {
return mu
}
for b, x := range mu {
if _, ok := mup[b]; !ok {
mup[b] = x
}
}
mu = mup
}
return mu
}
func fixedFrom(cands map[string]map[string]bool) map[string]string {
fixed := make(map[string]string)
for b, m := range cands {
if len(m) == 1 && m[b] {
fixed[b] = b
}
}
return fixed
}
// applyMu applies mu to g returning the result.
func applyMu(g []*Statement, mu map[string]string) []*Statement {
back := make([]Statement, 0, len(g))
dst := make([]*Statement, 0, len(g))
seen := make(map[Statement]bool)
for _, s := range g {
n := Statement{
Subject: Term{Value: translate(s.Subject.Value, mu)},
Predicate: Term{Value: s.Predicate.Value},
Object: Term{Value: translate(s.Object.Value, mu)},
Label: Term{Value: s.Label.Value},
}
if seen[n] {
continue
}
seen[n] = true
back = append(back, n)
dst = append(dst, &back[len(back)-1])
}
return dst
}
// search returns a minimum endomorphism using a DFS strategy.
//
// This is lines 33-46 of algorithm 6 in doi:10.1145/3068333.
func (st *dfs) search(g, q []*Statement, cands map[string]map[string]bool, mu map[string]string) map[string]string {
qMin := q[0]
m := st.join(qMin, g, cands, mu)
if len(m) == 0 {
// Early exit if no mapping found.
return nil
}
sortByCodom(m)
mMin := m[0]
qp := q[1:]
if len(qp) != 0 {
for len(m) != 0 {
mMin = m[0]
mup := st.search(g, qp, cands, mMin)
if !isAutomorphism(mup) {
return mup
}
m = m[1:]
}
}
return mMin
}
// isAutomorphism returns whether mu is an automorphism, this is equivalent to
// dom(mu) == codom(mu).
func isAutomorphism(mu map[string]string) bool {
return isEqualTerms(dom(mu), codom(mu))
}
// dom returns the domain of mu.
func dom(mu map[string]string) map[string]bool {
d := make(map[string]bool, len(mu))
for v := range mu {
d[v] = true
}
return d
}
// codom returns the codomain of mu.
func codom(mu map[string]string) map[string]bool {
cd := make(map[string]bool, len(mu))
for _, v := range mu {
cd[v] = true
}
return cd
}
// isEqualTerms returns whether a and b are identical.
func isEqualTerms(a, b map[string]bool) bool {
if len(a) != len(b) {
return false
}
for k := range a {
if !b[k] {
return false
}
}
return true
}
// sortByCodom performs a sort of maps ordered by fewest blank nodes in
// codomain, then fewest self mappings.
func sortByCodom(maps []map[string]string) {
m := orderedByCodom{
maps: maps,
attrs: make([]attrs, len(maps)),
}
for i, mu := range maps {
m.attrs[i].blanks = make(map[string]bool)
for x, y := range mu {
if isBlank(y) {
m.attrs[i].blanks[y] = true
}
if x == y {
m.attrs[i].selfs++
}
}
}
sort.Sort(m)
}
type orderedByCodom struct {
maps []map[string]string
attrs []attrs
}
type attrs struct {
blanks map[string]bool
selfs int
}
func (m orderedByCodom) Len() int { return len(m.maps) }
func (m orderedByCodom) Less(i, j int) bool {
attrI := m.attrs[i]
attrJ := m.attrs[j]
switch {
case len(attrI.blanks) < len(attrJ.blanks):
return true
case len(attrI.blanks) > len(attrJ.blanks):
return false
default:
return attrI.selfs < attrJ.selfs
}
}
func (m orderedByCodom) Swap(i, j int) {
m.maps[i], m.maps[j] = m.maps[j], m.maps[i]
m.attrs[i], m.attrs[j] = m.attrs[j], m.attrs[i]
}
// join evaluates the given pattern, q, joining with solutions in m.
// This takes only a single mapping and so only works for the DFS strategy.
//
// This is lines 47-51 of algorithm 6 in doi:10.1145/3068333.
func (st *dfs) join(q *Statement, g []*Statement, cands map[string]map[string]bool, m map[string]string) []map[string]string {
var mp []map[string]string
isLoop := q.Subject.Value == q.Object.Value
for _, s := range g {
// Line 45: M_q ← {µ | µ(q) ∈ G}
// | µ(q) ∈ G
//
// µ(q) ∈ G ↔ (µ(q_s),q_p,µ(q_o)) ∈ G
if q.Predicate.Value != s.Predicate.Value {
continue
}
// q_s = q_o ↔ µ(q_s) =_µ(q_o)
if isLoop && s.Subject.Value != s.Object.Value {
continue
}
// Line 46: M_q' ← {µ ∈ M_q | for all b ∈ bnodes({q}), µ(b) ∈ cands[b]}
// | for all b ∈ bnodes({q}), µ(b) ∈ cands[b]
if !cands[q.Subject.Value][s.Subject.Value] || !cands[q.Object.Value][s.Object.Value] {
continue
}
// Line 47: M' ← M_q' ⋈ M
// M₁ ⋈ M₂ = {μ₁ ∪ μ₂ | μ₁ ∈ M₁, μ₂ ∈ M₂ and μ₁, μ₂ are compatible mappings}
// | μ₁ ∈ M₁, μ₂ ∈ M₂ and μ₁, μ₂ are compatible mappings
if mq, ok := m[q.Subject.Value]; ok && mq != s.Subject.Value {
continue
}
if !isLoop {
if mq, ok := m[q.Object.Value]; ok && mq != s.Object.Value {
continue
}
}
// Line 47: μ₁ ∪ μ₂
var mu map[string]string
if isLoop {
mu = map[string]string{
q.Subject.Value: s.Subject.Value,
}
} else {
mu = map[string]string{
q.Subject.Value: s.Subject.Value,
q.Object.Value: s.Object.Value,
}
}
for b, mb := range m {
mu[b] = mb
}
mp = append(mp, mu)
}
return mp
}