maplib 0.19.3__cp310-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
maplib/__init__.pyi ADDED
@@ -0,0 +1,1023 @@
1
+ from pathlib import Path
2
+ from typing import Union, List, Dict, Optional, Callable, Tuple, Literal as LiteralType
3
+ from polars import DataFrame
4
+ from datetime import datetime, date
5
+ from maplib.maplib import rdf
6
+
7
+ a = rdf.type
8
+
9
+ class xsd:
10
+ """
11
+ The xsd namespace: http://www.w3.org/2001/XMLSchema#
12
+ """
13
+ anyURI:IRI
14
+ base64Binary:IRI
15
+ boolean:IRI
16
+ byte:IRI
17
+ date:IRI
18
+ dateTime:IRI
19
+ dateTimeStamp:IRI
20
+ dayTimeDuration:IRI
21
+ decimal:IRI
22
+ double:IRI
23
+ duration:IRI
24
+ float:IRI
25
+ gDay:IRI
26
+ gMonth:IRI
27
+ gMonthDay:IRI
28
+ gYear:IRI
29
+ gYearMonth:IRI
30
+ hexBinary:IRI
31
+ int_:IRI
32
+ integer:IRI
33
+ language:IRI
34
+ long:IRI
35
+ negativeInteger:IRI
36
+ nonNegativeInteger:IRI
37
+ nonPositiveInteger:IRI
38
+ normalizedString:IRI
39
+ short:IRI
40
+ string:IRI
41
+ token:IRI
42
+ unsignedByte:IRI
43
+ unsignedInt:IRI
44
+ unsignedLong:IRI
45
+ unsignedShort:IRI
46
+ yearMonthDuration:IRI
47
+
48
+
49
+ class rdf:
50
+ """
51
+ The rdf namespace: http://www.w3.org/1999/02/22-rdf-syntax-ns#
52
+ """
53
+ Alt:IRI
54
+ Bag:IRI
55
+ HTML:IRI
56
+ List:IRI
57
+ Property:IRI
58
+ Seq:IRI
59
+ Statement:IRI
60
+ XMLLiteral:IRI
61
+ first:IRI
62
+ langString:IRI
63
+ nil:IRI
64
+ object:IRI
65
+ predicate:IRI
66
+ rest:IRI
67
+ subject:IRI
68
+ type:IRI
69
+ value:IRI
70
+
71
+
72
+ class rdfs:
73
+ """
74
+ The rdfs namespace: http://www.w3.org/1999/02/22-rdf-syntax-ns#
75
+ """
76
+ Class:IRI
77
+ Container:IRI
78
+ ContainerMembershipProperty:IRI
79
+ Datatype:IRI
80
+ Literal:IRI
81
+ Resource:IRI
82
+ comment:IRI
83
+ domain:IRI
84
+ isDefinedBy:IRI
85
+ label:IRI
86
+ member:IRI
87
+ range:IRI
88
+ seeAlso:IRI
89
+ subClassOf:IRI
90
+ subPropertyOf:IRI
91
+
92
+
93
+ class owl:
94
+ """
95
+ The owl namespace: http://www.w3.org/2002/07/owl#
96
+ """
97
+ AllDifferent:IRI
98
+ AllDisjointClasses:IRI
99
+ AllDisjointProperties:IRI
100
+ Annotation:IRI
101
+ AnnotationProperty:IRI
102
+ Axiom:IRI
103
+ Class:IRI
104
+ DataRange:IRI
105
+ DatatypeProperty:IRI
106
+ DeprecatedClass:IRI
107
+ DeprecatedProperty:IRI
108
+ FunctionalProperty:IRI
109
+ InverseFunctionalProperty:IRI
110
+ IrreflexiveProperty:IRI
111
+ NamedIndividual:IRI
112
+ NegativePropertyAssertion:IRI
113
+ Nothing:IRI
114
+ ObjectProperty:IRI
115
+ Ontology:IRI
116
+ OntologyProperty:IRI
117
+ ReflexiveProperty:IRI
118
+ Restriction:IRI
119
+ SymmetricProperty:IRI
120
+ Thing:IRI
121
+ TransitiveProperty:IRI
122
+ allValuesFrom:IRI
123
+ annotatedProperty:IRI
124
+ annotatedSource:IRI
125
+ annotatedTarget:IRI
126
+ assertionProperty:IRI
127
+ backwardCompatibleWith:IRI
128
+ bottomDataProperty:IRI
129
+ bottomObjectProperty:IRI
130
+ cardinality:IRI
131
+ complementOf:IRI
132
+ datatypeComplementOf:IRI
133
+ deprecated:IRI
134
+ differentFrom:IRI
135
+ disjointUnionOf:IRI
136
+ disjointWith:IRI
137
+ distinctMembers:IRI
138
+ equivalentClass:IRI
139
+ equivalentProperty:IRI
140
+ hasKey:IRI
141
+ hasSelf:IRI
142
+ hasValue:IRI
143
+ imports:IRI
144
+ incompatibleWith:IRI
145
+ intersectionOf:IRI
146
+ inverseOf:IRI
147
+ maxCardinality:IRI
148
+ maxQualifiedCardinality:IRI
149
+ members:IRI
150
+ minCardinality:IRI
151
+ minQualifiedCardinality:IRI
152
+ onClass:IRI
153
+ onDataRange:IRI
154
+ onDatatype:IRI
155
+ onProperties:IRI
156
+ onProperty:IRI
157
+ oneOf:IRI
158
+ priorVersion:IRI
159
+ propertyChainAxiom:IRI
160
+ propertyDisjointWith:IRI
161
+ qualifiedCardinality:IRI
162
+ rational:IRI
163
+ real:IRI
164
+ sameAs:IRI
165
+ someValuesFrom:IRI
166
+ sourceIndividual:IRI
167
+ targetIndividual:IRI
168
+ targetValue:IRI
169
+ topDataProperty:IRI
170
+ topObjectProperty:IRI
171
+ unionOf:IRI
172
+ versionIRI:IRI
173
+ versionInfo:IRI
174
+ withRestrictions:IRI
175
+
176
+
177
+ class RDFType:
178
+ """
179
+ The type of a column containing a RDF variable.
180
+ For instance, IRIs are RDFType.IRI and a string literal is RDFType.Literal("http://www.w3.org/2001/XMLSchema#string")
181
+ """
182
+
183
+ IRI: "RDFType"
184
+ BlankNode: "RDFType"
185
+ Literal: Callable[[Union[str, "IRI"]], "RDFType"]
186
+ Multi: Callable[[List["RDFType"]], "RDFType"]
187
+ Nested: Callable[["RDFType"], "RDFType"]
188
+ Unknown: "RDFType"
189
+
190
+ class SolutionMappings:
191
+ """
192
+ Detailed information about the solution mappings, the types of the variables and debugging for queries.
193
+ """
194
+
195
+ mappings: DataFrame
196
+ rdf_types: Dict[str, RDFType]
197
+ debug: Optional[str]
198
+
199
+ class Variable:
200
+ """
201
+ A variable in a template.
202
+ """
203
+
204
+ name: str
205
+
206
+ def __init__(self, name: str):
207
+ """
208
+ Create a new variable.
209
+ :param name: The name of the variable.
210
+ """
211
+ ...
212
+
213
+ class IRI:
214
+ iri: str
215
+ """
216
+ An IRI.
217
+ """
218
+
219
+ def __init__(self, iri: str):
220
+ """
221
+ Create a new IRI
222
+ :param iri: IRI (without < and >).
223
+ """
224
+
225
+ class BlankNode:
226
+ """
227
+ A Blank Node.
228
+ """
229
+
230
+ name: str
231
+
232
+ def __init__(self, name: str):
233
+ """
234
+ Create a new Blank Node
235
+ :param name: Name of blank node (without _:).
236
+ """
237
+
238
+ class Prefix:
239
+ """
240
+ A prefix that can be used to ergonomically build iris.
241
+ """
242
+
243
+ def __init__(self, iri, prefix_name=None):
244
+ """
245
+ Create a new prefix.
246
+ :param iri: The prefix IRI.
247
+ :param prefix_name: The name of the prefix
248
+ """
249
+
250
+ def suf(self, suffix: str) -> IRI:
251
+ """
252
+ Create an IRI by appending the suffix.
253
+ :param suffix: The suffix to append.
254
+ :return:
255
+ """
256
+
257
+ class Literal:
258
+ """
259
+ An RDF literal.
260
+ """
261
+
262
+ value: str
263
+ datatype: Optional[IRI]
264
+ language: Optional[str]
265
+
266
+ def __init__(self, value: str, data_type: IRI = None, language: str = None):
267
+ """
268
+ Create a new RDF Literal
269
+ :param value: The lexical representation of the value.
270
+ :param data_type: The data type of the value (an IRI).
271
+ :param language: The language tag of the value.
272
+ """
273
+
274
+ def to_native(self) -> Union[int, float, bool, str, datetime, date]:
275
+ """
276
+
277
+ :return:
278
+ """
279
+
280
+ class Parameter:
281
+ variable: Variable
282
+ optional: bool
283
+ allow_blank: bool
284
+ rdf_type: Optional[RDFType]
285
+ default_value: Optional[Union[Literal, IRI, BlankNode]]
286
+ """
287
+ Parameters for template signatures.
288
+ """
289
+
290
+ def __init__(
291
+ self,
292
+ variable: Variable,
293
+ optional: Optional[bool] = False,
294
+ allow_blank: Optional[bool] = True,
295
+ rdf_type: Optional[RDFType] = None,
296
+ default_value: Optional[Union[Literal, IRI, BlankNode]] = None,
297
+ ):
298
+ """
299
+ Create a new parameter for a Template.
300
+ :param variable: The variable.
301
+ :param optional: Can the variable be unbound?
302
+ :param allow_blank: Can the variable be bound to a blank node?
303
+ :param rdf_type: The type of the variable. Can be nested.
304
+ :param default_value: Default value when no value provided.
305
+ """
306
+
307
+ class Argument:
308
+ def __init__(
309
+ self, term: Union[Variable, IRI, Literal], list_expand: Optional[bool] = False
310
+ ):
311
+ """
312
+ An argument for a template instance.
313
+ :param term: The term.
314
+ :param list_expand: Should the argument be expanded? Used with the list_expander argument of instance.
315
+ """
316
+
317
+ class Instance:
318
+ def __init__(
319
+ self,
320
+ iri: IRI,
321
+ arguments: List[Union[Argument, Variable, IRI, Literal, BlankNode, None]],
322
+ list_expander: Optional[LiteralType["cross", "zipMin", "zipMax"]] = None,
323
+ ):
324
+ """
325
+ A template instance.
326
+ :param iri: The IRI of the template to be instantiated.
327
+ :param arguments: The arguments for template instantiation.
328
+ :param list_expander: (How) should we do list expansion?
329
+ """
330
+
331
+ class Template:
332
+ iri: str
333
+ parameters: List[Parameter]
334
+ instances: List[Instance]
335
+ """
336
+ An OTTR Template.
337
+ Note that accessing parameters- or instances-fields returns copies.
338
+ To change these fields, you must assign new lists of parameters or instances.
339
+ """
340
+
341
+ def __init__(
342
+ self,
343
+ iri: IRI,
344
+ parameters: List[Union[Parameter, Variable]],
345
+ instances: List[Instance],
346
+ ):
347
+ """
348
+ Create a new OTTR Template
349
+ :param iri: The IRI of the template
350
+ :param parameters:
351
+ :param instances:
352
+ """
353
+
354
+ def instance(
355
+ self,
356
+ arguments: List[Union[Argument, Variable, IRI, Literal, None]],
357
+ list_expander: LiteralType["cross", "zipMin", "zipMax"] = None,
358
+ ) -> Instance:
359
+ """
360
+
361
+ :param arguments: The arguments to the template.
362
+ :param list_expander: (How) should we list-expand?
363
+ :return:
364
+ """
365
+
366
+ def Triple(
367
+ subject: Union["Argument", IRI, Variable, BlankNode],
368
+ predicate: Union["Argument", IRI, Variable, BlankNode],
369
+ object: Union["Argument", IRI, Variable, Literal, BlankNode],
370
+ list_expander: Optional[LiteralType["cross", "zipMin", "zipMax"]] = None,
371
+ ):
372
+ """
373
+ An OTTR Triple Pattern used for creating templates.
374
+ This is the basis pattern which all template instances are rewritten into.
375
+ Equivalent to:
376
+
377
+ >>> ottr = Prefix("http://ns.ottr.xyz/0.4/")
378
+ ... Instance(ottr.suf("Triple"), subject, predicate, object, list_expander)
379
+
380
+ :param subject:
381
+ :param predicate:
382
+ :param object:
383
+ :param list_expander:
384
+ :return:
385
+ """
386
+
387
+ class XSD:
388
+ """
389
+ The xsd namespace, for convenience.
390
+ """
391
+
392
+ boolean: IRI
393
+ byte: IRI
394
+ date: IRI
395
+ dateTime: IRI
396
+ dateTimeStamp: IRI
397
+ decimal: IRI
398
+ double: IRI
399
+ duration: IRI
400
+ float: IRI
401
+ int_: IRI
402
+ integer: IRI
403
+ language: IRI
404
+ long: IRI
405
+ short: IRI
406
+ string: IRI
407
+
408
+ def __init__(self):
409
+ """
410
+ Create the xsd namespace helper.
411
+ """
412
+
413
+ # END COMMON WITH CHRONTEXT
414
+
415
+ class IndexingOptions:
416
+ """
417
+ Options for indexing
418
+ """
419
+
420
+ def __init__(
421
+ self,
422
+ object_sort_all: bool = None,
423
+ object_sort_some: List["IRI"] = None,
424
+ fts_path: str = None,
425
+ ):
426
+ """
427
+ Defaults to indexing on subjects and objects for select types (e.g. rdf:type and rdfs:label)
428
+
429
+ :param object_sort_all: Enable object-indexing for all suitable predicates (doubles memory requirement).
430
+ :param object_sort_some: Enable object-indexing for a selected list of predicates.
431
+ :param fts_path: Enable full text search, stored at the path
432
+ """
433
+
434
+ ParametersType = Dict[str, Tuple[DataFrame, Dict[str, RDFType]]]
435
+
436
+ class ValidationReport:
437
+ """
438
+ SHACL Validation report.
439
+ Only constructed by maplib.
440
+ """
441
+
442
+ conforms: bool
443
+ "Whether or not the validation report conforms to the shapes"
444
+
445
+ shape_targets: DataFrame
446
+ "A DataFrame containing the counts of the targets of each shape and constraint"
447
+
448
+ performance: DataFrame
449
+ "Performance statistics for the validation process"
450
+
451
+ def results(
452
+ self,
453
+ native_dataframe: bool = False,
454
+ include_datatypes: bool = False,
455
+ streaming: bool = False,
456
+ ) -> Optional[Union[DataFrame, "SolutionMappings"]]:
457
+ """
458
+ Return the results of the validation report, if they exist.
459
+
460
+ :param native_dataframe: Return columns with maplib-native formatting. Useful for round-trips.
461
+ :param include_datatypes: Return datatypes of the results DataFrame (returns SolutionMappings instead of DataFrame).
462
+ :param streaming: Use the Polars streaming functionality.
463
+ :return: The SHACL validation report, as a DataFrame
464
+ """
465
+
466
+ def details(
467
+ self,
468
+ native_dataframe: bool = False,
469
+ include_datatypes: bool = False,
470
+ streaming: bool = False,
471
+ ) -> Optional[DataFrame]:
472
+ """
473
+ Returns the details of the validation report.
474
+ Only available if validation was called with include_details=True.
475
+
476
+ :param native_dataframe: Return columns with maplib-native formatting. Useful for round-trips.
477
+ :param include_datatypes: Return datatypes of the results DataFrame (returns SolutionMappings instead of DataFrame).
478
+ :param streaming: Use the Polars streaming functionality.
479
+ :return: Details of the SHACL validation report, as a DataFrame
480
+ """
481
+
482
+ def graph(self) -> "Mapping":
483
+ """
484
+ Creates a new model object where the base graph is the validation report with results.
485
+ Includes the details of the validation report in the new graph if they exist.
486
+
487
+ :return:
488
+ """
489
+
490
+ class Model:
491
+ """
492
+ A model session allowing:
493
+
494
+ * Iterative model using OTTR templates
495
+ * Interactive SPARQL querying and enrichment
496
+ * SHACL validation
497
+
498
+ Usage:
499
+
500
+ >>> from maplib import Model
501
+ ... doc = '''
502
+ ... @prefix ex:<http://example.net/ns#>.
503
+ ... ex:ExampleTemplate [?MyValue] :: {
504
+ ... ottr:Triple(ex:myObject, ex:hasValue, ?MyValue)
505
+ ... } .'''
506
+ ... m = Model()
507
+ ... m.add_template(doc)
508
+
509
+ :param documents: a stOTTR document or a list of these
510
+ :param indexing_options: options for indexing
511
+ """
512
+
513
+ def __init__(
514
+ self,
515
+ indexing_options: "IndexingOptions" = None,
516
+ ) -> "Model": ...
517
+
518
+ def add_template(self, template: Union["Template", str]):
519
+ """
520
+ Add a template to the model. Overwrites any existing template with the same IRI.
521
+ :param template: The template to add, as a stOTTR string or as a programmatically constructed Template.
522
+ :return:
523
+ """
524
+
525
+ def add_prefixes(self, prefixes: Dict[str, str]):
526
+ """
527
+ Add prefixes that will be used in parsing of SPARQL, Datalog and OTTR.
528
+
529
+ Usage:
530
+ >>> m.add_prefixes({"ex" : "http:://example.net/"})
531
+
532
+ :param prefixes: Known prefixes
533
+ :return:
534
+ """
535
+
536
+ def map(
537
+ self,
538
+ template: Union[str, "Template", IRI],
539
+ df: DataFrame = None,
540
+ graph: str = None,
541
+ types: Dict[str, RDFType] = None,
542
+ validate_iris: bool = True,
543
+ ) -> None:
544
+ """
545
+ Map a template using a DataFrame
546
+ Usage:
547
+
548
+ >>> m.map("ex:ExampleTemplate", df)
549
+
550
+ If the template has no arguments, the df argument is not necessary.
551
+
552
+ :param template: Template, IRI, IRI string or prefixed template name.
553
+ :param df: DataFrame where the columns have the same names as the template arguments
554
+ :param graph: The IRI of the graph to add triples to.
555
+ :param types: The types of the columns.
556
+ :param validate_iris: Validate any IRI-columns.
557
+ """
558
+
559
+ def map_triples(
560
+ self,
561
+ df: DataFrame = None,
562
+ predicate: str = None,
563
+ graph: str = None,
564
+ types: Dict[str, RDFType] = None,
565
+ validate_iris: bool = True,
566
+ ) -> None:
567
+ """
568
+ Map a template using a DataFrame with columns subject, object and predicate
569
+ The predicate column can also be supplied as a string if it is the same for all rows.
570
+ Usage:
571
+
572
+ >>> m.map_triples(df)
573
+
574
+ If the template has no arguments, the df argument is not necessary.
575
+
576
+ :param df: DataFrame where the columns are named subject and object. May also contain a verb-column.
577
+ :param verb: The uri of the verb.
578
+ :param graph: The IRI of the graph to add triples to.
579
+ :param types: The types of the columns.
580
+ :param validate_iris: Validate any IRI-columns.
581
+ """
582
+
583
+ def map_default(
584
+ self,
585
+ df: DataFrame,
586
+ primary_key_column: str,
587
+ dry_run: bool = False,
588
+ graph: str = None,
589
+ types: Dict[str, RDFType] = None,
590
+ validate_iris: bool = True,
591
+ ) -> str:
592
+ """
593
+ Create a default template and map it based on a dataframe.
594
+ Usage:
595
+
596
+ >>> template_string = m.map_default(df, "myKeyCol")
597
+ ... print(template_string)
598
+
599
+ :param df: DataFrame where the columns have the same names as the template arguments
600
+ :param primary_key_column: This column will be the subject of all triples in the generated template.
601
+ :param dry_run: Do not map the template, only return the string.
602
+ :param graph: The IRI of the graph to add triples to.
603
+ :param types: The types of the columns.
604
+ :param validate_iris: Validate any IRI-columns.
605
+ :return: The generated template
606
+ """
607
+
608
+ def query(
609
+ self,
610
+ query: str,
611
+ parameters: ParametersType = None,
612
+ include_datatypes: bool = False,
613
+ native_dataframe: bool = False,
614
+ graph: str = None,
615
+ streaming: bool = False,
616
+ return_json: bool = False,
617
+ include_transient: bool = True,
618
+ max_rows: int = None,
619
+ debug: bool = False,
620
+ ) -> Union[
621
+ DataFrame, SolutionMappings, List[Union[DataFrame, SolutionMappings, str]], None
622
+ ]:
623
+ """
624
+ Query the contained knowledge graph using SPARQL
625
+ Currently, SELECT, CONSTRUCT and INSERT are supported.
626
+ Usage:
627
+
628
+ >>> df = model.query('''
629
+ ... PREFIX ex:<http://example.net/ns#>
630
+ ... SELECT ?obj1 ?obj2 WHERE {
631
+ ... ?obj1 ex:hasObj ?obj2
632
+ ... }''')
633
+ ... print(df)
634
+
635
+ :param query: The SPARQL query string
636
+ :param parameters: PVALUES Parameters, a DataFrame containing the value bindings in the custom PVALUES construction.
637
+ :param native_dataframe: Return columns with maplib-native formatting. Useful for round-trips.
638
+ :param include_datatypes: Datatypes are not returned by default, set to true to return a dict with the solution mappings and the datatypes.
639
+ :param graph: The IRI of the graph to query.
640
+ :param streaming: Use Polars streaming
641
+ :param return_json: Return JSON string.
642
+ :param include_transient: Include transient triples when querying.
643
+ :param max_rows: Maximum estimated rows in result, helps avoid out-of-memory errors.
644
+ :param debug: Why does my query have no results?
645
+ :return: DataFrame (Select), list of DataFrames (Construct) containing results, None for Insert-queries, or SolutionMappings when debug or native_dataframe is set.
646
+
647
+ """
648
+
649
+ def update(
650
+ self,
651
+ update: str,
652
+ parameters: ParametersType = None,
653
+ streaming: bool = False,
654
+ include_transient: bool = True,
655
+ max_rows: int = None,
656
+ debug: bool = False,
657
+ ):
658
+ """
659
+ Insert the results of a Construct query in the graph.
660
+ Useful for being able to use the same query for inspecting what will be inserted and actually inserting.
661
+ Usage:
662
+
663
+ >>> m = Model(doc)
664
+ ... # Omitted
665
+ ... update_pizzas = '''
666
+ ... ...'''
667
+ ... m.update(update_pizzas)
668
+
669
+ :param update: The SPARQL Update string
670
+ :param parameters: PVALUES Parameters, a DataFrame containing the value bindings in the custom PVALUES construction.
671
+ :param streaming: Use Polars streaming
672
+ :param include_transient: Include transient triples when querying (but see "transient" above).
673
+ :param max_rows: Maximum estimated rows in result, helps avoid out-of-memory errors.
674
+ :param debug: Why does my query have no results?
675
+ :return: None
676
+ """
677
+
678
+ def insert(
679
+ self,
680
+ query: str,
681
+ parameters: ParametersType = None,
682
+ include_datatypes: bool = False,
683
+ native_dataframe: bool = False,
684
+ transient: bool = False,
685
+ streaming: bool = False,
686
+ source_graph: str = None,
687
+ target_graph: str = None,
688
+ include_transient: bool = True,
689
+ max_rows: int = None,
690
+ debug: bool = False,
691
+ ):
692
+ """
693
+ Insert the results of a Construct query in the graph.
694
+ Useful for being able to use the same query for inspecting what will be inserted and actually inserting.
695
+ Usage:
696
+
697
+ >>> m = Model(doc)
698
+ ... # Omitted
699
+ ... hpizzas = '''
700
+ ... PREFIX pizza:<https://github.com/magbak/maplib/pizza#>
701
+ ... PREFIX ing:<https://github.com/magbak/maplib/pizza/ingredients#>
702
+ ... CONSTRUCT { ?p a pizza:HeterodoxPizza }
703
+ ... WHERE {
704
+ ... ?p a pizza:Pizza .
705
+ ... ?p pizza:hasIngredient ing:Pineapple .
706
+ ... }'''
707
+ ... m.insert(hpizzas)
708
+
709
+ :param query: The SPARQL Insert query string
710
+ :param parameters: PVALUES Parameters, a DataFrame containing the value bindings in the custom PVALUES construction.
711
+ :param native_dataframe: Return columns with maplib-native formatting. Useful for round-trips.
712
+ :param include_datatypes: Datatypes are not returned by default, set to true to return a dict with the solution mappings and the datatypes.
713
+ :param transient: Should the inserted triples be transient?
714
+ :param source_graph: The IRI of the source graph to execute the construct query.
715
+ :param target_graph: The IRI of the target graph to insert into.
716
+ :param streaming: Use Polars streaming
717
+ :param include_transient: Include transient triples when querying (but see "transient" above).
718
+ :param max_rows: Maximum estimated rows in result, helps avoid out-of-memory errors.
719
+ :param debug: Why does my query have no results?
720
+ :return: None
721
+ """
722
+
723
+ def validate(
724
+ self,
725
+ shape_graph: str,
726
+ data_graph: str = None,
727
+ include_details: bool = False,
728
+ include_conforms: bool = False,
729
+ include_shape_graph: bool = True,
730
+ streaming: bool = False,
731
+ max_shape_constraint_results: int = None,
732
+ only_shapes: List[str] = None,
733
+ deactivate_shapes: List[str] = None,
734
+ dry_run: bool = False,
735
+ max_rows: int = None,
736
+ serial: bool = False,
737
+ ) -> ValidationReport:
738
+ """
739
+ Validate the contained knowledge graph using SHACL
740
+ Assumes that the contained knowledge graph also contains SHACL Shapes.
741
+
742
+ :param shape_graph: The IRI of the Shape Graph.
743
+ :param data_graph: The IRI of the Data Graph (defaults to the default graph).
744
+ :param include_details: Include details of SHACL evaluation alongside the report. Currently uses a lot of memory.
745
+ :param include_conforms: Include those results that conformed. Also applies to details.
746
+ :param include_shape_graph: Include the shape graph in the report, useful when creating the graph from the report.
747
+ :param include_datatypes: Return the datatypes of the validation report (and details).
748
+ :param streaming: Use Polars streaming
749
+ :param max_shape_constraint_results: Maximum number of results per shape and constraint. Reduces the size of the result set.
750
+ :param only_shapes: Validate only these shapes, None means all shapes are validated (must be IRI, cannot be used with deactivate_shapes).
751
+ :param deactivate_shapes: Disable validation of these shapes (must be IRI, cannot be used with deactivate_shapes).
752
+ :param dry_run: Only find targets of shapes, but do not validate them.
753
+ :param max_rows: Maximum estimated rows in underlying SPARQL results, helps avoid out-of-memory errors.
754
+ :param serial: Turns off most parallell validation of shapes.
755
+ :return: Validation report containing a report (report.df) and whether the graph conforms (report.conforms)
756
+ """
757
+
758
+ def read(
759
+ self,
760
+ file_path: Union[str, Path],
761
+ format: LiteralType["ntriples", "turtle", "rdf/xml", "xml", "rdfxml"] = None,
762
+ base_iri: str = None,
763
+ transient: bool = False,
764
+ parallel: bool = None,
765
+ checked: bool = True,
766
+ graph: str = None,
767
+ replace_graph: bool = False,
768
+ ) -> None:
769
+ """
770
+ Reads triples from a file path.
771
+ You can specify the format, or it will be derived using file extension, e.g. filename.ttl or filename.nt.
772
+ Specify transient if you only want the triples to be available for further querying and validation,
773
+ but not persisted using write-methods.
774
+
775
+ Usage:
776
+
777
+ >>> m.read("my_triples.ttl")
778
+
779
+ :param file_path: The path of the file containing triples
780
+ :param format: One of "ntriples", "turtle", "rdf/xml", otherwise it is inferred from the file extension.
781
+ :param base_iri: Base iri
782
+ :param transient: Should these triples be included when writing the graph to the file system?
783
+ :param parallel: Parse triples in parallel, currently only NTRiples and Turtle. Assumes all prefixes are in the beginning of the document. Defaults to true only for NTriples.
784
+ :param checked: Check IRIs etc.
785
+ :param graph: The IRI of the graph to read the triples into, if None, it will be the default graph.
786
+ :param replace_graph: Replace the graph with these triples? Will replace the default graph if no graph is specified.
787
+ """
788
+
789
+ def read_template(
790
+ self,
791
+ file_path: Union[str, Path],
792
+ ) -> None:
793
+ """
794
+ Reads template(s) from a file path.
795
+
796
+ Usage:
797
+
798
+ >>> m.read("templates.ttl")
799
+
800
+ :param file_path: The path of the file containing templates in stOTTR format
801
+ """
802
+
803
+ def reads(
804
+ self,
805
+ s: str,
806
+ format: LiteralType["ntriples", "turtle", "rdf/xml", "xml", "rdfxml"],
807
+ base_iri: str = None,
808
+ transient: bool = False,
809
+ parallel: bool = None,
810
+ checked: bool = True,
811
+ graph: str = None,
812
+ replace_graph: bool = False,
813
+ ) -> None:
814
+ """
815
+ Reads triples from a string.
816
+ Specify transient if you only want the triples to be available for further querying and validation,
817
+ but not persisted using write-methods.
818
+
819
+ Usage:
820
+
821
+ >>> m.reads(my_ntriples_string, format="ntriples")
822
+
823
+ :param s: String containing serialized triples.
824
+ :param format: One of "ntriples", "turtle", "rdf/xml".
825
+ :param base_iri: Base iri
826
+ :param transient: Should these triples be included when writing the graph to the file system?
827
+ :param parallel: Parse triples in parallel, currently only NTRiples and Turtle. Assumes all prefixes are in the beginning of the document. Defaults to true for NTriples.
828
+ :param checked: Check IRIs etc.
829
+ :param graph: The IRI of the graph to read the triples into.
830
+ :param replace_graph: Replace the graph with these triples? Will replace the default graph if no graph is specified.
831
+ """
832
+
833
+ def write_cim_xml(
834
+ self,
835
+ file_path: Union[str, Path],
836
+ profile_graph: str,
837
+ model_iri: str = None,
838
+ version: str = None,
839
+ description: str = None,
840
+ created: str = None,
841
+ scenario_time: str = None,
842
+ modeling_authority_set: str = None,
843
+ prefixes: Dict[str, str] = None,
844
+ graph: str = None,
845
+ ) -> None:
846
+ """
847
+ Write the legacy CIM XML format.
848
+
849
+ >>> PROFILE_GRAPH = "urn:graph:profiles"
850
+ >>> m = Model()
851
+ >>> m.read(model_path, base_iri=publicID, format="rdf/xml")
852
+ >>> m.read("61970-600-2_Equipment-AP-Voc-RDFS2020_v3-0-0.rdf", graph=PROFILE_GRAPH, format="rdf/xml")
853
+ >>> m.read("61970-600-2_Operation-AP-Voc-RDFS2020_v3-0-0.rdf", graph=PROFILE_GRAPH, format="rdf/xml")
854
+ >>> m.write_cim_xml(
855
+ >>> "model.xml",
856
+ >>> profile_graph=PROFILE_GRAPH,
857
+ >>> description = "MyModel",
858
+ >>> created = "2023-09-14T20:27:41",
859
+ >>> scenario_time = "2023-09-14T02:44:43",
860
+ >>> modeling_authority_set="www.westernpower.co.uk",
861
+ >>> version="22",
862
+ >>> )
863
+
864
+ :param file_path: The path of the file containing triples
865
+ :param profile_graph: The IRI of the graph containing the ontology of the CIM profile to write.
866
+ :param model_iri: model_iri a md:FullModel. Is generated if not provided.
867
+ :param version: model_iri md:Model.version version .
868
+ :param description: model_iri md:Model.description description .
869
+ :param created: model_iri md:Model.created created .
870
+ :param scenario_time: model_iri md:Model.scenarioTime scenario_time .
871
+ :param modeling_authority_set: model_iri md:Model.modelingAuthoritySet modeling_authority_set .
872
+ :param prefixes: Prefixes to be used in XML export.
873
+ :param graph: The graph to write, defaults to the default graph.
874
+ """
875
+
876
+ def write(
877
+ self,
878
+ file_path: Union[str, Path],
879
+ format=LiteralType["ntriples", "turtle", "rdf/xml"],
880
+ graph: str = None,
881
+ ) -> None:
882
+ """
883
+ Write the non-transient triples to the file path specified in the NTriples format.
884
+
885
+ Usage:
886
+
887
+ >>> m.write("my_triples.nt", format="ntriples")
888
+
889
+ :param file_path: The path of the file containing triples
890
+ :param format: One of "ntriples", "turtle", "rdf/xml".
891
+ :param graph: The IRI of the graph to write.
892
+ """
893
+
894
+ def writes(
895
+ self, format=LiteralType["ntriples", "turtle", "rdf/xml"], graph: str = None
896
+ ) -> str:
897
+ """
898
+ DEPRECATED: use writes with format="ntriples"
899
+ Write the non-transient triples to a string in memory.
900
+
901
+ Usage:
902
+
903
+ >>> s = m.write_ntriples_string(format="turtle")
904
+
905
+ :param format: One of "ntriples", "turtle", "rdf/xml".
906
+ :param graph: The IRI of the graph to write.
907
+ :return Triples in model in the NTriples format (potentially a large string)
908
+ """
909
+
910
+ def write_native_parquet(
911
+ self, folder_path: Union[str, Path], graph: str = None
912
+ ) -> None:
913
+ """
914
+ Write non-transient triples using the internal native Parquet format.
915
+
916
+ Usage:
917
+
918
+ >>> m.write_native_parquet("output_folder")
919
+
920
+ :param folder_path: The path of the folder to write triples in the native format.
921
+ :param graph: The IRI of the graph to write.
922
+ """
923
+
924
+ def detach_graph(self, graph:str=None, preserve_name:bool=False) -> "Model":
925
+ """
926
+ Detaches and returns a named graph as their own Model object.
927
+ The named graph is removed from the original Model.
928
+
929
+ :param graph: The name of the graph to detach. Defaults to the default graph.
930
+ :param preserve_name: Preserve the name of the graph in the new Model, defaults to False.
931
+ :return: A model.
932
+ """
933
+
934
+ def get_predicate_iris(
935
+ self, graph: str = None, include_transient: bool = False
936
+ ) -> List["IRI"]:
937
+ """
938
+ :param graph: The graph to get the predicate iris from.
939
+ :param include_transient: Should we include predicates only between transient triples?
940
+ :return: The IRIs of the predicates currently in the given graph.
941
+ """
942
+
943
+ def get_predicate(
944
+ self, iri: "IRI", graph: str = None, include_transient: bool = False
945
+ ) -> List["SolutionMappings"]:
946
+ """
947
+ :param iri: The predicate IRI
948
+ :param graph: The graph to get the predicate from.
949
+ :param include_transient: Should we include transient triples?
950
+ :return: A list of the underlying tables that store a given predicate.
951
+ """
952
+
953
+ def create_index(
954
+ self, options: "IndexingOptions" = None, all: bool = True, graph: str = None
955
+ ):
956
+ """
957
+ :param options: Indexing options
958
+ :param all: Apply to all existing and new graphs
959
+ :param graph: The graph where indexes should be added
960
+ :return:
961
+ """
962
+
963
+ def infer(
964
+ self,
965
+ ruleset: Union[str, List[str]],
966
+ graph: str = None,
967
+ include_datatypes: bool = False,
968
+ native_dataframe: bool = False,
969
+ max_iterations: int = 100_000,
970
+ max_results: int = 10_000_000,
971
+ include_transient: bool = True,
972
+ max_rows: int = 100_000_000,
973
+ debug: bool = False,
974
+ ) -> Optional[Dict[str, DataFrame]]:
975
+ """
976
+ Run the inference rules that are provided
977
+ :param ruleset: The Datalog ruleset (a string).
978
+ :param graph: Apply the ruleset to this graph, defaults to the default graph, or the graph specified in the rules.
979
+ :param native_dataframe: Return columns with maplib-native formatting. Useful for round-trips.
980
+ :param include_datatypes: Datatypes are not returned by default, set to true to return a dict with the solution mappings and the datatypes.
981
+ :param max_iterations: Maximum number of iterations.
982
+ :param max_results: Maximum number of results.
983
+ :param include_transient: Include transient triples when reasoning.
984
+ :param max_rows: Maximum estimated rows in result, helps avoid out-of-memory errors.
985
+ :param debug: Debugs rule bodies for executions that give no triples.
986
+ :return: The inferred N-Tuples.
987
+ """
988
+
989
+ class MaplibException(Exception): ...
990
+
991
+ def explore(
992
+ m: "Model",
993
+ host: str = "localhost",
994
+ port: int = 8000,
995
+ bind: str = "localhost",
996
+ popup=True,
997
+ fts=True,
998
+ ):
999
+ """Starts a graph explorer session.
1000
+ To run from Jupyter Notebook use:
1001
+ >>> from maplib import explore
1002
+ >>>
1003
+ >>> server = explore(m)
1004
+ You can later stop the server with
1005
+ >>> server.stop()
1006
+
1007
+ :param m: The Model to explore
1008
+ :param host: The hostname that we will point the browser to.
1009
+ :param port: The port where the graph explorer webserver listens on.
1010
+ :param bind: Bind to the following host / ip.
1011
+ :param popup: Pop up the browser window.
1012
+ :param fts: Enable full text search indexing
1013
+ """
1014
+
1015
+ def generate_templates(m: Model, graph: Optional[str]) -> Dict[str, Template]:
1016
+ """Generate templates for instantiating the classes in an ontology
1017
+
1018
+ :param m: The model where the ontology is stored. We mainly rely on rdfs:subClassOf, rdfs:range and rdfs:domain.
1019
+ :param graph: The named graph where the ontology is stored.
1020
+
1021
+ :return A dictionary of templates for instantiating the classes in the ontology, where the keys are the class URIs.
1022
+
1023
+ Usage example - note that it is important to add the templates to the Model you want to populate."""