-
Notifications
You must be signed in to change notification settings - Fork 123
/
core.py
2329 lines (1928 loc) · 87.9 KB
/
core.py
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import os
import yaml
import types
import tempfile
import mimetypes
import subprocess
import idlib
import rdflib
from inspect import getsourcefile
from pathlib import Path, PurePath
from itertools import chain
from collections import namedtuple
from urllib.parse import urlparse
import ontquery as oq
import augpathlib as aug
import requests
import htmlfn as hfn
from joblib import Parallel, delayed
from rdflib.extras import infixowl
from ttlser import CustomTurtleSerializer, natsort
from pyontutils import combinators as cmb
from pyontutils import closed_namespaces as cnses
from pyontutils.utils import (refile,
TODAY,
UTCNOW,
UTCNOWISO,
getSourceLine,
utcnowtz,
Async,
deferred,
TermColors as tc,
log)
from pyontutils.utils_extra import check_value
from pyontutils.config import working_dir, auth
from pyontutils.namespaces import (makePrefixes,
makeNamespaces,
makeURIs,
NIFRID,
ilxtr,
PREFIXES as uPREFIXES,
rdf,
rdfs,
owl,
skos,
dc,
dcterms,
prov,
oboInOwl)
from pyontutils.identity_bnode import IdentityBNode
current_file = Path(__file__).absolute()
oq.utils.log.removeHandler(oq.utils.log.handlers[0])
oq.utils.log.addHandler(log.handlers[0])
# common funcs
def relative_resources(pathstring, failover='nifstd/resources'):
""" relative paths to resources in this repository
`failover` matches the location relative to the
github location (usually for prov purposes) """
if working_dir is None:
return Path(failover, pathstring).resolve()
else:
return Path(auth.get_path('resources'), pathstring).resolve().relative_to(working_dir.resolve())
def standard_checks(graph):
def cardinality(predicate, card=1):
for subject in sorted(set(graph.subjects())):
for i, object in enumerate(graph.objects(subject, predicate)):
if i == 0:
first_error = tc.red('ERROR:'), subject, 'has more than one label!', object
elif i >= card:
print(tc.red('ERROR:'), subject, 'has more than one label!', object)
if i == card:
print(*first_error)
cardinality(rdfs.label)
def build(*onts, fail=False, n_jobs=9, write=True):
""" Set n_jobs=1 for debug or embed() will crash. """
tail = lambda:tuple()
lonts = len(onts)
if lonts > 1:
for i, ont in enumerate(onts):
if ont.__name__ == 'parcBridge':
onts = onts[:-1]
def tail(o=ont):
return o.setup(),
if i != lonts - 1:
raise ValueError('parcBridge should be built last to avoid weird errors!')
# ont_setup must be run first on all ontologies
# or we will get weird import errors
if n_jobs == 1 or True:
return tuple(ont.make(fail=fail, write=write) for ont in
tuple(ont.setup() for ont in onts) + tail())
# have to use a listcomp so that all calls to setup()
# finish before parallel goes to work
return Parallel(n_jobs=n_jobs)(delayed(o.make)(fail=fail, write=write)
for o in
#[ont_setup(ont) for ont in onts])
(tuple(Async()(deferred(ont.setup)()
for ont in onts)) + tail()
if n_jobs > 1
else [ont.setup()
for ont in onts]))
def yield_recursive(s, p, o, source_graph): # FIXME transitive_closure on rdflib.Graph?
yield s, p, o
new_s = o
if isinstance(new_s, rdflib.BNode):
for p, o in source_graph.predicate_objects(new_s):
yield from yield_recursive(new_s, p, o, source_graph)
# ontology resource object
from .iterio import IterIO
class OntRes(idlib.Stream):
""" Message manager for serialized ontology resource.
There are plenty of tools that already deal effectively
with a triplified store, but we need something that does
a better job at managing the interchange, esp in and out
of git. Sort of a better backend for ontquery services back by
serialized sources. May ultimately move this code there. """
#def __new__(cls, iri_or_path):
# TODO return an iri wrapper or a path wrapper
#pass
Graph = None # this is set below after OntGraph is created (derp)
def __init__(self, identifier, repo=None, Graph=None): # XXX DO NOT USE THIS IT IS BROKEN
self.identifier = identifier # the potential attribute error here is intentional
self.repo = repo # I have a repo augmented path in my thesis stats code
if Graph == None:
Graph = OntGraph
self.Graph = Graph
def _populate(self, graph, gen):
raise NotImplementedError('too many differences between header/data and xml/all the rest')
def populate(self, graph):
# TODO if self.header ...
self._populate(graph, self.data)
@property
def graph(self, cypher=None):
# FIXME transitions to other streams should be functions
# and it also allows passing an explicit cypher argument
# to enable checksumming in one pass, however this will
# require one more wrapper
if not hasattr(self, '_graph'):
kwargs = {}
if hasattr(self, 'path'):
kwargs['path'] = self.path
self._graph = self.Graph(**kwargs)
self.populate(self._graph)
return self._graph
@property
def identifier_bound(self):
return next(self.graph[:rdf.type:owl.Ontology])
@property
def identifier_version(self):
""" implicitly identifier_bound_version since we won't maniuplate a
version iri supplied as the identifi
the id to get
"""
return next(self.graph[self.identifier_bound:owl.versionIRI])
@property
def imports(self):
for object in self.graph[self.identifier_bound:owl.imports]:
# TODO switch this for _res_remote_class to abstract beyond just owl
yield OntResIri(object) # this is ok since files will be file:///
@property
def import_chain(self):
yield from self._import_chain({OntResIri(self.identifier_bound)})
def _import_chain(self, done):
imps = list(self.imports)
Async()(deferred(lambda r: r.metadata().graph)(_) for _ in imps)
for resource in imps:
if resource in done:
continue
done.add(resource)
yield resource
yield from resource.metadata()._import_chain(done)
def __eq__(self, other):
raise NotImplementedError
def __hash__(self):
raise NotImplementedError
def __repr__(self):
return self.__class__.__name__ + f'({self.identifier!r})'
class OntMeta(OntRes):
""" only the header of an ontology, e.g. the owl:Ontology section for OWL2 """
# headers all the way down data -> ontology header -> response header -> iri
def _graph_sideload(self, data):
# this will overwrite any existing graph
self._graph = self.Graph().parse(data=data, format=self.format)
def _populate(self, graph, gen):
# we don't pop request headers or file metadata off in here
# because different loading processes may use that information
# to dispatch different loading processes
if self.format == 'application/rdf+xml':
# rdflib xml parsing uses an incremental parser that
# constructs its own file object and byte stream
data = b''.join(gen)
graph.parse(data=data)
elif self.format == 'text/owl-functional': # FIXME TODO
log.error(f'TODO cannot parse owl functional syntax yet {self}')
else:
itio = IterIO(gen)
itio.name = self.identifier # some rdflib parses need a name
graph.parse(file=itio, format=self.format)
def __eq__(self, other):
# FIXME this is ... complicated
return self.identifier_bound == other.identifier_bound
def __hash__(self):
return hash((self.__class__, self.identifier_bound))
class OntResOnt(OntRes):
""" full ontology files """
_metadata_class = None # FIXME can we do this by dispatching OntMeta like Path?
def __eq__(self, other):
return self.metadata().identifier_bound == other.metadata().identifier_bound
def __hash__(self):
return hash((self.__class__, self.metadata().identifier_bound))
class OntIdIri(OntRes):
def __init__(self, iri):
self.iri = iri
# TODO version iris etc.
def _get(self):
return requests.get(self.iri, stream=True, headers={'Accept': 'text/turtle'}) # worth a shot ...
@property
def identifier(self):
return self.iri
@property
def headers(self):
""" request headers """
if not hasattr(self, '_headers'):
resp = requests.head(self.identifier) # TODO status handling for all these
self._headers = resp.headers
return self._headers
@headers.setter
def headers(self, value):
self._headers = value
class OntMetaIri(OntMeta, OntIdIri):
@property
def data(self):
gen = self._data()
format = next(gen) # advance to set self.format in _data
return gen
def _data(self, yield_response_gen=False):
if self.identifier.endswith('.zip'):
# TODO use Content-Range to retrieve only the central directory
# after we get the header here
# https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
# this could be another way to handle the filesystem issues for bf
# as well ...
pass
resp = self._get()
self.headers = resp.headers
# TODO consider yielding headers here as well?
gen = resp.iter_content(chunk_size=4096)
first = next(gen)
# TODO better type detection
if first.startswith(b'<?xml'):
start = b'<owl:Ontology'
stop = b'</owl:Ontology>'
sentinel = b'TODO'
self.format = 'application/rdf+xml'
elif first.startswith(b'@prefix') or first.startswith(b'#lang rdf/turtle'):
start = b' owl:Ontology' # FIXME this is not standard
stop = b' .\n' # FIXME can be fooled by strings
sentinel = b'### Annotations' # FIXME only works for ttlser
#sentinel = b' a ' # FIXME if a |owl:Ontology has a chunk break on | this is incorrect
# also needs to be a regex that ends in [^owl:Ontology]
self.format = 'text/turtle'
elif first.startswith(b'Prefix(:='):
start = b'\nOntology'
stop = b')\n\n' # FIXME I don't think owl functional syntax actually has a proper header :/
sentient = b'TODO'
self.format = 'text/owl-functional'
else:
'text/owl-manchester'
raise ValueError(first.decode())
yield self.format # we do this because self.format needs to be accessible before loading the graph
close_rdf = b'\n</rdf:RDF>\n'
searching = False
header_data = b''
for chunk in chain((first,), gen):
if start in chunk:
searching = True
# yield content prior to start since it may include a stop
# that we don't actually want to stop at
start_end_index = chunk.index(start) + len(start)
header_first_chunk = chunk[:start_end_index]
if yield_response_gen:
header_data += header_first_chunk
yield header_first_chunk
chunk = chunk[start_end_index:]
if searching and stop in chunk: # or test_chunk_ends_with_start_of_stop(stop, chunk)
# FIXME edge case where a stop crosses a chunk boundary
# if stop is short enough it may make sense to do a naieve contains check
# to start things off ...
stop_end_index = chunk.index(stop) + len(stop)
header_last_chunk = chunk[:stop_end_index]
if yield_response_gen:
header_data += header_last_chunk
yield header_last_chunk
if yield_response_gen:
if self.format == 'application/rdf+xml':
header_data += close_rdf
self._graph_sideload(header_data)
chunk = chunk[stop_end_index:]
yield resp, chain((chunk,), gen)
else:
# if we are not continuing then close the xml tags
if self.format == 'application/rdf+xml':
yield close_rdf
resp.close()
return
elif not searching and sentinel in chunk:
sent_end_index = chunk.index(sentinel) + len(sentinel)
header_last_chunk = chunk[:sent_end_index]
if yield_response_gen:
header_data += header_last_chunk
yield header_last_chunk
if yield_response_gen:
if self.format == 'application/rdf+xml':
header_data += close_rdf
self._graph_sideload(header_data)
chunk = chunk[sent_end_index:]
yield resp, chain((chunk,), gen)
else:
# if we are not continuing then close the xml tags
if self.format == 'application/rdf+xml':
yield close_rdf
resp.close()
return
else:
# FIXME TODO need a sentinel value where there isn't a header
# so that we can infer that there is no header, or at least
# no headerish data at the head of the file
if yield_response_gen:
header_data += chunk
yield chunk
class OntResIri(OntIdIri, OntResOnt):
_metadata_class = OntMetaIri
@property
def data(self):
format, *header_chunks, (resp, gen) = self.metadata()._data(yield_response_gen=True)
self.headers = resp.headers
self.format = format
# TODO populate header graph? not sure this is actually possible
# maybe need to double wrap so that the header chunks always get
# consumbed by the header object ?
if self.format == 'application/rdf+xml':
resp.close()
return None
return chain(header_chunks, gen)
def _populate(self, graph, gen):
# we don't pop request headers or file metadata off in here
# because different loading processes may use that information
# to dispatch different loading processes
if self.format == 'application/rdf+xml':
# rdflib xml parsing uses and incremental parser that
# constructs its own file object and byte stream
graph.parse(self.identifier, format=self.format)
elif self.format == 'text/owl-functional': # FIXME TODO
log.error(f'TODO cannot parse owl functional syntax yet {self}')
else:
itio = IterIO(gen)
itio.name = self.identifier
graph.parse(file=itio, format=self.format)
class OntIdPath(OntRes):
# FIXME should this be an instrumented path?
# should OntResIri be an instrumented iri?
def __init__(self, path):
# FIXME type caste?
self.path = path
@property
def identifier(self):
return self.path.as_posix()
def _get(self):
resp = requests.Response()
with open(self.path, 'rb') as f:
resp.raw = io.BytesIO(f.read()) # FIXME streaming file read should be possible ...
# TODO set headers here
#resp.headers = {'Content-Length': self.path.meta_no_checksum.size}
resp.status_code = 200
return resp
headers = OntIdIri.headers
class OntMetaPath(OntIdPath, OntMeta):
data = OntMetaIri.data
_data = OntMetaIri._data
class OntResPath(OntIdPath, OntResOnt):
""" ontology resource coming from a file """
_metadata_class = OntMetaPath
data = OntResIri.data
_populate = OntResIri._populate # FIXME application/rdf+xml is a mess ... cant parse streams :/
class OntIdGit(OntIdPath):
def __init__(self, path, ref='HEAD'):
""" ref can be HEAD, branch, commit hash, etc.
if ref = None, the working copy of the file is used
if ref = '', the index copy of the file is used """
self.path = path
self.ref = ref
@property
def identifier(self):
# FIXME this doesn't quite conform because it is a local identifier
# which neglects the repo portion of the id ...
if type(self.path) == str:
breakpoint()
if self.ref is None:
return self.path.as_posix()
return self.ref + ':' + self.path.repo_relative_path.as_posix()
def metadata(self):
if not hasattr(self, '_metadata'):
self._metadata = self._metadata_class(self.path, ref=self.ref)
return self._metadata
def _get(self):
resp = requests.Response()
if self.ref is None:
with open(self.path, 'rb') as f:
resp.raw = io.BytesIO(f.read()) # FIXME can't we stream/seek these?
else:
resp.raw = io.BytesIO(self.path.repo.git.show(self.identifier).encode())
resp.status_code = 200
return resp
headers = OntIdIri.headers
class OntMetaGit(OntIdGit, OntMeta):
data = OntMetaIri.data
_data = OntMetaIri._data
class OntResGit(OntIdGit, OntResOnt):
_metadata_class = OntMetaGit
data = OntResIri.data
_populate = OntResIri._populate # FIXME application/rdf+xml is a mess ... cant parse streams :/
class OntResAny:
def __new__(cls, path, ref=None, ref_failover=None):
# it really is better if people statically know so we don't have to guess
"""
if isinstance(path_or_iri, Path):
iri = None
path = path_or_iri
elif isinstance(path_or_iri, str):
if path_or_iri.startswith('http://') or path_or_iri.startswith('https://'):
iri = path_or_iri
# TODO try to find the local version?
path = None
else:
iri = None
path = path_or_iri
else:
raise TypeError(f'what is a {type(path_or_iri)} {path_or_iri!r}')
"""
try:
org = OntResGit(path, ref=ref)
org._get() # yes this is slow, but it is the safest way ...
return org
except BaseException as e:
#log.exception(e)
repo = path.repo
remote = repo.remote()
rnprefix = remote.name + '/'
url_base = next(remote.urls)
pu = urlparse(url_base)
if pu.netloc == 'github.com':
if not ref or ref == 'HEAD':
ref = repo.active_branch.name
elif ref not in [r.name.replace(rnprefix, '') for r in repo.refs]:
log.warning(f'unknown ref {ref}')
rpath = Path(pu.path).with_suffix('') / ref / path.repo_relative_path
iri = 'https://raw.githubusercontent.com' + rpath.as_posix()
return OntResIri(iri)
breakpoint()
class OntMetaInterLex(OntMeta):
pass
class OntResInterLex(OntResOnt):
""" ontology resource backed by interlex """
_metadata_class = OntMetaInterLex
class BetterNamespaceManager(rdflib.namespace.NamespaceManager):
def __call__(self, **kwargs):
""" set prefixes """
raise NotImplementedError
def __iter__(self):
yield from self.namespaces()
def qname(self, iri):
prefix, namespace, name = self.compute_qname(iri, generate=False)
if prefix == "":
return name
else:
return ":".join((prefix, name))
def populate(self, graph):
[graph.bind(k, v) for k, v in self.namespaces()]
def populate_from(self, *graphs):
[self.bind(k, v) for g in graphs for k, v in g.namespaces()]
class OntGraph(rdflib.Graph):
""" A 5th try at making one of these. ConjunctiveGraph version? """
metadata_type_markers = [owl.Ontology] # FIXME naming
def __init__(self, *args, path=None, existing=None, namespace_manager=None, **kwargs):
if existing:
self.__dict__ == existing.__dict__
if not hasattr(existing, '_namespace_manager'):
self._namespace_manager = BetterNamespaceManager(self)
self.namespace_manager.populate_from(existing)
else:
super().__init__(*args, **kwargs)
# FIXME the way this is implemented in rdflib makes it impossible to
# change the namespace manager type in subclasses which is _really_ annoying
# we shortcircuit this here
self._namespace_manager = namespace_manager
self.bind('owl', owl)
self.path = path
@property
def path(self):
return self.__path
@path.setter
def path(self, path):
if path is not None and not isinstance(path, Path):
log.warning(f'Not a pathlib.Path! {path}')
self.__path = path
# TODO id for graphs like this ... use InterLex IdentityBNode?
# TODO local_conventions aka curies
# NOTE you actually just use it the other way by passing this
# to OntCuries.populate
@oq.utils.mimicArgs(rdflib.Graph.parse)
def parse(self, *args, **kwargs):
if not args and not kwargs and self.path is not None:
# FIXME augpathlib.Path ;_;
mimetype, _ = mimetypes.guess_type(self.path.as_uri())
return super().parse(self.path.as_posix(), format=mimetype)
else:
args = [a.as_posix() if isinstance(a, Path) else a for a in args]
return super().parse(*args, **kwargs)
def _get_namespace_manager(self):
if self._namespace_manager is None:
self._namespace_manager = BetterNamespaceManager(self)
return self._namespace_manager
def _set_namespace_manager(self, nm):
self._namespace_manager = nm
namespace_manager = property(_get_namespace_manager,
_set_namespace_manager,
doc="this graph's namespace-manager")
@property
def prefixes(self):
""" the prefix/curie/qname section of an rdf file """
# a new OntCuries-like object that wraps NamespaceManager
# and can leverage its trie
self.namespace_manager
raise NotImplementedError('yet')
def metadata(self):
""" the header/metadata/ontology section of an rdf file """
raise NotImplementedError('yet')
return OntGraphMetadata(self)
@property
def data(self):
""" everything else """
# FIXME this is actually metadata + homogenous data
# question: should data sections automatically checksum
# their contents as it streams through?
# answer: no, if someone needs a checksum, they should ask
# for it explicitly when they transition to some other stream
# whether that is a file or a graph etc.
raise NotImplementedError('yet')
def write(self, path=None, format='nifttl'):
if path is None:
path = self.path
with open(path, 'wb') as f:
self.serialize(f, format=format)
@property
def ttl(self):
out = self.serialize(format='nifttl').decode()
return out
@property
def ttl_html(self):
out = self.serialize(format='htmlttl').decode()
return out
def debug(self):
print(self.ttl)
def matchNamespace(self, namespace, *, ignore_predicates=tuple()):
# FIXME can't we hit the cache for these?
sns = str(namespace)
for s, p, o in self:
if p not in ignore_predicates:
for e in (s, p, o):
if isinstance(e, rdflib.URIRef):
try:
pre, ns, suff = self.compute_qname(e, generate=False)
if str(ns) == sns:
yield e
except KeyError:
pass
def couldMapEntities(self, *temp_namespaces, ignore_predicates=tuple()):
yield from (e for ns in temp_namespaces
for e in self.matchNamespace(ns, ignore_predicates=ignore_predicates))
def diffFromReplace(self, replace_graph, *, new_replaces_old=True):
""" compute add, remove, same graphs based on a graph
the contains triples of the form `new replaces old`
where replaces can be any predicate set new_replaces_old=False
if the add_and_replace graph is of the form `old replacedBy new`
"""
if new_replaces_old:
replace = {old:new for new, _, old in replace_graph}
else:
replace = {old:new for old, _, new in replace_graph}
def iri_replace(t):
return tuple(replace[e] if e in replace else e for e in t)
add, rem, same = [self.__class__() for _ in range(3)]
for t in self:
nt = iri_replace(t)
if nt != t:
add.add(nt), rem.add(t)
else:
same.add(t)
return add, rem, same
def subjectGraph(self, subject):
# some days I am smart, as in years ago when working on neuron stuff
# TODO do we need to check for duplicates and cycels?
def f(triple, graph):
subject, predicate, object = triple
for p, o in graph[object]:
yield object, p, o
yield from self.transitiveClosure(f, (None, None, subject))
def _subjectGraph(self, subject, *, done=None):
# some days I am dumb
first = False
if done is None:
first = True
done = set()
done.add(subject)
for p, o in self[subject::]:
if first: # subject free subject graph
yield p, o
else:
yield subject, p, o
if isinstance(o, rdflib.BNode):
yield from self.subjectGraph(o, done=done)
elif isinstance(o, rdflib.URIRef):
# TODO if we want closed world identified subgraphs
# then we would compute the identity of the named
# here as well, however, that is a rare case and
# would cause identities to change at a distance
# which is bad, so probably should never do it
pass
def subjectIdentity(self, subject, *, debug=False):
""" calculate the identity of a subgraph for a particular subject
useful for determining whether individual records have changed
not quite
"""
pairs_triples = list(self.subjectGraph(subject))
ibn = IdentityBNode(pairs_triples, debug=False)
if debug:
triples = [(subject, *pos) if len(pos) == 2 else pos for pos in pairs_triples]
g = self.__class__()
_replaced = {}
def replace(e):
if isinstance(e, rdflib.BNode):
if e not in _replaced:
_replaced[e] = rdflib.BNode()
e = _replaced[e]
return e
def rebnode(t):
return tuple(replace(e) for e in t)
# switch out all the bnodes to double check
[g.add(rebnode(t)) for t in triples]
self.namespace_manager.populate(g)
dibn = g.subjectIdentity(subject, debug=False)
gibn = IdentityBNode(g, debug=True)
print(g.ttl)
print(ibn, dibn)
assert ibn == dibn
assert ibn != gibn
breakpoint()
return ibn
def named_subjects(self):
for s in self.subjects():
if isinstance(s, rdflib.URIRef):
yield s
def subjectsChanged(self, other_graph):
""" in order to detect this the mapped id must be persisted
by the process that is making the change
NOTE: To avoid the hashing chicken and egg problem here
one would have to explicitly exclude triples with the
predicate used to store the identity, which adds quite a
bit of complexity. To avoid this, simply keeping and old
version of the graph around might be easier. TODO explore
tradeoffs.
"""
# the case where an external process (e.g. editing in protege)
# has caused a change in the elements used to calculate the id
# of the class
# FIXME mapped but a change to the structure of the class has
# cause a change in the identity of the class
# in which case the old hasTemporaryId should still be attached
#temporary_id_changed = [e for e in self[:ilxtr.hasTemporaryId:] not_mapped ]
#changed_classes = [(s,
#ilxtr.hasTemporaryId,
#o) for s, o in self[:ilxtr.hasTemporaryId:]]
sid = {s:self.subjectIdentity(s) for s in set(self.named_subjects())}
osid = {s:other_graph.subjectIdentity(s) for s in set(other_graph.named_subjects())}
ssid = set(sid)
sosid = set(osid)
added = not_in_other = ssid - sosid
removed = not_in_self = sosid - ssid
changed = [(s, osid[s], i) for s, i in sid.items() if s in osid and i != osid[s]]
return added, removed, changed
def addReplaceGraph(self, index_graph, index_namespace, *temp_namespaces):
""" Given an index of existing ids that map to ids in temporary namespaces
return a graph of `new replaces old` triples. Currently this works on
temp_namespaces, but in theory it could operate on any namespace.
Note that this does attempt to detect changes to classes that
have already been mapped and have a new temporary id. That
functionality is implemented elsewhere. """
existing_indexes = list(set(index_graph.matchNamespace(index_namespace))) # target prefix?
lp = len(index_namespace)
suffixes = [int(u[lp:]) for u in existing_indexes]
start = max(suffixes) + 1 if suffixes else 1
# FIXME ignore predicates is more complex than this
# we want to filter out only cases that have already been mapped to
# the current index namespace
could_map = list(set(self.couldMapEntities(*temp_namespaces,
ignore_predicates=(ilxtr.hasTemporaryId,))))
mapped_triples = [(s,
ilxtr.hasTemporaryId,
o) for s, o in index_graph[:ilxtr.hasTemporaryId:]]
# FIXME could be mapped into another namespace ? what to do in that case?
already_mapped = [o for _, _, o in mapped_triples]
not_mapped = [e for e in could_map if e not in already_mapped]
# the iri replace operation is common enough that it probably
# deserves its own semantics since when combined with a known
# input qualifier the output graph is well defined and it provides
# much stronger and clearer semantics for what was going on
# allowing multiple different predicates is fine since different
# processes may have different use cases for the predicate
# in the case where the mapping is simply stored and added
# as an equivalent class along with hasInterLexId, then the new
# mappings are simply add rather than addAndReplaceUsingMapping
iri_replace_map = [(index_namespace[str(i + start)],
ilxtr.hasTemporaryId,
temp_id)
for i, temp_id in enumerate(sorted(not_mapped, key=natsort))]
# FIXME
# iris that have been mapped but not replaced
# this will probably be a bug in the future?
# the issue is that those triples shouldn't be added to add_replace_graph
# because they are already in the index_graph
# this is the more efficient place to obtain this list
# but it could also be obtained by comparing index_graph
# with add_replace_graph ... maybe ...
not_replaced = [(s, p, o) for s, p, o in mapped_triples if o in could_map]
# need to compute the id of the graph/triples opaque data section
# this is the pure add graph, in this case it is also used to
# compute the replace graph as well
add_replace_graph = self.__class__()
[add_replace_graph.add(t) for t in iri_replace_map]
return add_replace_graph, not_replaced
def mapTempToIndex(self, index_graph, index_namespace, *temp_namespaces):
""" In theory index_graph could be self if the namespace in use
is only relevant for a single file, otherwise there needs to be
a single shared reference file that maintains the the index for all
files
NOTE: either the current graph or the index_graph needs to have the
curie mapping for the namespaces defined prior to calling this
otherwise you will have to cross populate namespaces again
"""
if not isinstance(index_graph, self.__class__):
index_graph = self.__class__(existing=index_graph)
add_replace_graph, not_replaced = self.addReplaceGraph(index_graph,
index_namespace,
*temp_namespaces)
# TODO also want the transitions here if we
# want to record the record in InterLex
index_graph.namespace_manager.populate_from(self)
[index_graph.add(t) for t in add_replace_graph]
# FIXME for some reason I had a thought that the index
# graph should include labels as a semi-orthogonal check
# to make sure that everything lines up as expected
# if an identifier is used in multiple serialized graphs
# then we want to make sure that we can do a replacement
# if we find that temporary identifier somewhere else
# even if it has already been added to the index
# NOTE that this behavior is undesireable if the temp ids
# were originally minted per file, in which case this
# requires a two step process where the graph is run with itself
# as the index at which point it can safely be run again
# against a global index
# TODO detect use of likely non-unique suffixes in temp namespaces
[add_replace_graph.add(t) for t in not_replaced]
add_only_graph, remove_graph, same_graph = self.diffFromReplace(add_replace_graph)
# the other semantics that could be used here
# would be to do an in place modification of self
# to remove the remove graph and add the add_only_graph
# NOTE the BNodes need to retain their identity across the 3 graphs
# so that they reassemble correctly
new_self = self.__class__(path=self.path)
[new_self.add(t) for t in add_replace_graph]
[new_self.add(t) for t in add_only_graph]
[new_self.add(t) for t in same_graph]
new_self.namespace_manager.populate_from(index_graph)
return new_self
# variously named/connected subsets
@property
def boundIdentifiers(self):
""" There should only be one but ... """
for type in self.metadata_type_markers:
yield from self[:rdf.type:type]
@property
def boundIdentifier(self):
return next(self.boundIdentifiers)
@property
def versionIdentifiers(self):
""" There should only be one but ... """