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