fastrdf API usage guide¶
This guide walks through the fastrdf Python API by task, with an example for each public method of
Model and ModelStream, and for the module-level functions. The README has the
short overview, and each method’s docstring (help(Model.query)) lists every parameter. The
documentation site has this guide and the API reference, generated from
the docstrings, side by side.
Contents:
The examples use this prefix throughout:
EX = "http://example.net/ns#"
1. Conventions¶
Terms in results¶
Query results are Polars DataFrames, with one column per variable:
IRIs are strings in angle brackets:
"<http://example.net/ns#alice>".Blank nodes are strings that start with
_:, such as"_:b_0". The label is given by fastrdf: each document that is read, each update and eachmapcall has its own blank nodes, also when the same labels are used again and afterserializeanddeserialize, and the label ends with a number that tells them apart. Use a label only to tell blank nodes apart within one model, not across models or runs.Literals come back as native Polars values when a column holds a single datatype:
xsd:stringasstr,xsd:integerasi64,xsd:doubleasf64,xsd:booleanasbool,xsd:dateTimeasdatetime, and so on. Language-tagged strings are formatted as"hei"@no.A column that mixes types, for example the
?oof?s ?p ?o, holds formatted N-Triples-style strings:"<http://...>","\"Alice\"","\"30\"^^<http://www.w3.org/2001/XMLSchema#integer>".
Pass solution_mappings=True to query to get the DataFrame together with the RDF type of
each column (see Round trips).
Terms in input¶
When you map a DataFrame, IRI columns hold plain strings without brackets
("http://example.net/ns#alice"). Whether a value becomes an IRI or a literal is decided by the
template’s parameter type (ottr:IRI) or, without one, by the column’s Polars type. The same holds
for bindings= and for the Python term classes:
from fastrdf import IRI, Literal, BlankNode, Variable, Prefix, xsd, rdf, rdfs, owl, a
ex = Prefix(EX)
alice = ex.suf("alice") # IRI("http://example.net/ns#alice")
print(alice.iri) # http://example.net/ns#alice
age = Literal("30", data_type=xsd.integer)
print(age.to_native()) # 30
greeting = Literal("hei", language="no")
b = BlankNode("b1")
print(xsd.string.iri, rdfs.label.iri, a.iri) # the built-in namespaces hold IRIs
Prefixes¶
add_prefixes registers prefixes for SPARQL queries and updates, Datalog rules and stOTTR
templates, so that you don’t have to repeat PREFIX declarations:
from fastrdf import Model
m = Model()
m.add_prefixes({"ex": EX})
m.reads(f"<{EX}alice> <{EX}name> \"Alice\" .", format="ntriples")
print(m.query("SELECT ?n WHERE { ex:alice ex:name ?n }"))
The common prefixes rdf, rdfs, xsd, owl and ottr are known in templates without
declaration. Template IRIs can be given as prefixed names, e.g. m.map("ex:Person", df).
2. Creating a model¶
from fastrdf import Model, IndexingOptions
m = Model() # everything in memory
A Model holds triples (in a default graph and any number of named graphs), templates, prefixes,
user-defined functions and settings.
Storage modes¶
|
Dictionaries of IRIs and literals |
Triple tables |
|---|---|---|
|
memory |
memory |
|
disk |
memory |
|
disk |
disk, as Parquet files |
As a guide to sizing, 20 million triples of synthetic test data took about 1.5 GB of memory with
"memory" storage.
m = Model(storage="disk", storage_folder="fastrdf_disk")
m = Model(storage_folder="fastrdf_disk") # hybrid is the default with a folder
fastrdf keeps its working files in a folder named fastrdf_storage inside the storage folder. It
is emptied each time a model is created there, so a storage folder does not keep a model between
runs: use serialize for that.
Indexing options¶
IndexingOptions choose the indexes a model builds. Subjects are always indexed, and by default
rdf:type and rdfs:label also get object indexes, which make lookups by value fast.
from fastrdf import IRI
m = Model(indexing_options=IndexingOptions(
object_sort_some=[IRI(EX + "serialNumber")], # object index for these predicates
))
# IndexingOptions(object_sort_all=True) indexes all suitable predicates (about twice the memory)
Full-text search (fts=True, fts_predicates, fts_local_names, fts_iris) and GeoSPARQL
(geo=True) are, see section 9. Use create_index to change the
indexes of an existing model (section 14).
Memory limit¶
Queries spill joins, aggregations, sorts and results to disk when fastrdf uses more memory than the limit, which is 80% of the system memory by default (respecting container limits). The setting applies to the whole process.
import fastrdf
fastrdf.set_memory_limit(max_memory_mb=8000)
print(fastrdf.memory_limit()) # the limit, in bytes
print(fastrdf.memory_usage()) # the estimated bytes fastrdf has allocated
fastrdf.set_memory_limit() # back to the defaults
set_memory_limit also takes spill_dir (set it before the first query: it is fixed at the
first spill), max_spill_mb (default 64 GB) and abort_above_mb, which stops the process with a
message on stderr before the operating system would kill it. Before that, a query raises a
MemoryError when the process uses more than 90% of abort_above_mb (less with many threads, so
that the batches every thread has in flight fit below it, but at least half), which is checked as
the solutions of its joins are produced and between the steps of the query. Each call sets all four; arguments left as None get their defaults.
3. Templates¶
Templates are reusable patterns of triples in OTTR. Mapping a template with a DataFrame instantiates it once per row, with each parameter taken from the column of the same name, all rows at once.
stOTTR syntax¶
m = Model()
m.add_template("""
@prefix ex: <http://example.net/ns#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ex:Person [
ottr:IRI ?id, # typed: the values must be IRIs
xsd:string ?name,
? xsd:integer ?age, # optional: may be null
ottr:IRI ?country = ex:Norway, # default value, used when the value is null
List<ottr:IRI> ?knows # a list, from a Polars list column
] :: {
ottr:Triple(?id, a, ex:Person),
ottr:Triple(?id, ex:name, ?name),
ottr:Triple(?id, ex:age, ?age),
ottr:Triple(?id, ex:livesIn, ?country),
cross | ottr:Triple(?id, ex:knows, ++?knows)
} .
""")
A template is iri [ parameters ] :: { instances } .. Each instance calls another template, and
ottr:Triple(subject, predicate, object) is the built-in base template. a stands for
rdf:type.
Parameters are [modifiers] [type] ?name [= default]:
Part |
Meaning |
|---|---|
|
optional: the value may be null (no triples are made from instances that need it) |
|
non-blank: the value may not be a blank node |
type |
|
|
a constant used when the value is null: an IRI, a literal ( |
Arguments of instances are variables, IRIs (full <...> or prefixed), literals ("text",
"text"@en, "1"^^xsd:integer, 42, true), blank nodes ([] or _:b) or lists ((1, 2)).
OTTR’s none is not supported: leave an optional parameter null in the data instead.
List expansion. A list expander before an instance makes one instance per list element of the
arguments marked with ++:
Expander |
With several |
|---|---|
|
every combination of their elements |
|
element by element, stopping at the shortest list |
|
element by element, to the longest list (missing elements are null) |
m.add_template("""
@prefix ex: <http://example.net/ns#> .
ex:Scores [ ottr:IRI ?id, List<ottr:IRI> ?tests, List<xsd:integer> ?scores ] :: {
zipMin | ex:Score(?id, ++?tests, ++?scores)
} .
ex:Score [ ottr:IRI ?id, ottr:IRI ?test, xsd:integer ?score ] :: {
ottr:Triple(?id, ex:took, ?test),
ottr:Triple(?test, ex:score, ?score)
} .
""")
This also shows a nested template call: ex:Scores instantiates ex:Score, which is defined
in the same document. Templates may be defined in any order, and add_template replaces an
existing template with the same IRI.
Mapping the two templates:
import polars as pl
people = pl.DataFrame({
"id": [EX + "alice", EX + "bob"],
"name": ["Alice", "Bob"],
"age": [30, None], # Bob gets no ex:age triple
"country": [None, EX + "Sweden"], # Alice gets the default, ex:Norway
"knows": [[EX + "bob"], []], # Bob knows nobody: no ex:knows triples
})
m.map("ex:Person", people)
scores = pl.DataFrame({
"id": [EX + "alice"],
"tests": [[EX + "t1", EX + "t2"]],
"scores": [[90, 75]],
})
m.map("ex:Scores", scores)
print(m.query("SELECT ?test ?score WHERE { ?test <http://example.net/ns#score> ?score }"))
Templates can also be read from a file, or a URL of object storage:
with open("templates.stottr", "w") as f:
f.write("""@prefix ex: <http://example.net/ns#> .
ex:Named [ ottr:IRI ?id, ?label ] :: { ottr:Triple(?id, rdfs:label, ?label) } .""")
m.read_template("templates.stottr")
Syntax errors point at the offending source and suggest a fix:
from fastrdf import FastrdfException
try:
m.add_template("""@prefix ex: <http://example.net/ns#> .
ex:T [ ?a ] :: { ottr:Triple(?a, ex:p, nothing) } .""")
except FastrdfException as e:
print(e)
# OTTR syntax error at line 2, column 39: `nothing` is not a valid term
# ...
# = help: write a variable as `?nothing`, a prefixed name as `ex:nothing`, or a full IRI as ...
Function calls in templates¶
Templates can compute their arguments with SPARQL functions, so that IRIs, casts and string or date manipulations are defined once in the template instead of in every data source. A function call is written Lisp-style, (function argument ...), with the arguments separated by spaces, and can be used wherever a template argument can. The syntax and semantics follow Frog, an extension of OTTR with functions [3]:
m = Model()
m.add_template("""
@prefix ex: <http://example.net/ns#> .
def ex:toIRI(xsd:string ?localName) -> ottr:IRI :: (
IRI (CONCAT "http://example.net/" (ENCODE_FOR_URI ?localName))
) .
ex:Planet [ xsd:string ?name, ? xsd:string ?starName, xsd:string ?mass ] :: {
ottr:Triple((ex:toIRI ?name), rdfs:label, ?name),
ottr:Triple((ex:toIRI ?name), ex:orbits, (ex:toIRI ?starName)),
ottr:Triple((ex:toIRI ?name), ex:mass, (xsd:decimal ?mass))
} .
""")
m.map("ex:Planet", pl.DataFrame({"name": ["11 Com b"], "starName": ["11 Com"], "mass": ["19.4"]}))
Functions are the SPARQL built-in functions (
CONCAT,STR,IRI,REPLACE,UCASE,SUBSTR,YEAR,NOW,SHA256,IF,COALESCE,BOUND,IN, …; case insensitive), the operators+ - * / = != < > <= >= && || !(+,*,&&and||take two or more arguments), XSD casts such as(xsd:integer ?x), functions registered as UDFs, and functions defined withdefas above. Frog’s base functions (fn:plus,fn:concat,fn:castToIRI, … inhttp://ns.frog.ottr.xyz/0.1/function/) can be used where SPARQL has the same function. A call without arguments of a function given by an IRI must be written(frog:functionCall ex:f), as(ex:f)is a list.Function calls are evaluated by fastrdf’s SPARQL expression engine, for all rows at once, when the instance that contains them is expanded, before list expansion.
As in SPARQL, errors give no value (
none): then an optional parameter is left out, a parameter with a default value gets the default, and otherwise the instance is not expanded.Function calls can not be list expanded, and lists can not be function arguments. Functions defined with
defcan not be recursive, and their parameter and return types are documentation; fastrdf infers the types of the results from the data.From Python, use
FunctionCall, e.g.Triple(p, label, FunctionCall("UCASE", [name])).In the templates of virtualized resources, e.g.
ottr:Triple(?dp, ex:valueW, (* ?value 1000)), function calls are evaluated on the rows the virtualized database returns. Filters on their values are evaluated by fastrdf, not pushed down.
Function calls follow Frog: M. Jarholt, “Frog: Functions for ontologies — An extension for the OTTR-framework”, Master’s thesis, University of Oslo, 2022, https://hdl.handle.net/10852/96925.
Building templates in Python¶
The same templates can be built with Template, Parameter, Variable, Argument, Instance
and Triple:
from fastrdf import Template, Parameter, Variable, Argument, Instance, Triple, RDFType, Prefix, xsd, a
ex = Prefix(EX)
pizza, country, ings = Variable("pizza"), Variable("country"), Variable("ingredients")
pizza_template = Template(
iri=ex.suf("Pizza"),
parameters=[
Parameter(pizza, rdf_type=RDFType.IRI), # RDFType.IRI is an attribute, not a call
Parameter(country, optional=True, rdf_type=RDFType.IRI),
Parameter(ings, rdf_type=RDFType.Nested(RDFType.IRI)), # List<ottr:IRI>
],
instances=[
Triple(pizza, a, ex.suf("Pizza")),
Triple(pizza, ex.suf("fromCountry"), country),
Triple(pizza, ex.suf("hasIngredient"), Argument(ings, list_expand=True), list_expander="cross"),
],
)
print(pizza_template) # prints the template as stOTTR
m = Model()
m.add_template(pizza_template)
m.map(pizza_template, pl.DataFrame({
"pizza": [EX + "Hawaiian"],
"country": [EX + "CAN"],
"ingredients": [[EX + "Pineapple", EX + "Ham"]],
}))
Parameter(variable, optional=False, allow_blank=True, rdf_type=None, default_value=None). A plainVariablein the parameter list is an untyped, required parameter.RDFType.IRI,RDFType.BlankNode,RDFType.Literal(xsd.string),RDFType.Nested(t)(a list) andRDFType.Multi([...])describe types.Instance(iri, arguments, list_expander=None)calls another template, andtemplate.instance(arguments, list_expander=None)makes an instance oftemplate. An argument ofNoneis unbound.Triple(s, p, o, list_expander=None)is shorthand for anottr:Tripleinstance.
wrapper = Template(
iri=ex.suf("CanadianPizza"),
parameters=[pizza, ings],
instances=[pizza_template.instance([pizza, ex.suf("CAN"), ings])],
)
m.add_template(wrapper)
m.map(wrapper, pl.DataFrame({"pizza": [EX + "Poutine"], "ingredients": [[EX + "Gravy"]]}))
Inspecting templates¶
get_templates returns the templates of the model (without the built-in ottr:Triple), and
templates_to_graph writes them as RDF in the fastrdf template vocabulary, so their structure can
be queried with SPARQL:
print([t.iri.iri for t in m.get_templates()])
m.templates_to_graph("urn:templates")
print(m.query("""
PREFIX fastrdf: <https://datatreehouse.github.io/fastrdf/vocab#>
SELECT ?template ?iri WHERE { ?template fastrdf:referencesIri ?iri }
""", graph="urn:templates"))
The parameters, instances and arguments of a template are blank nodes. Calling
templates_to_graph again with the same templates adds nothing, and a template that was changed
in between gets new blank nodes, next to the triples of its earlier version.
A Template’s iri, parameters and instances fields return copies; assign new lists to
change them.
Printing (
repr) a template that was parsed from stOTTR text currently panics with “not yet implemented”. Templates built in Python print fine.
4. Mapping data¶
map¶
map(template, data=None, graph=None, validate_iris=True, stream=False) instantiates a template
once per row. The template can be a Template, an IRI, an IRI string, a prefixed name or a
stOTTR document. data can be:
a Polars
DataFrame, with one column per parameter;a
LazyFrame, consumed in one pass withcollect_batches(), so it never needs to fit in memory;SolutionMappings, e.g. fromquery(..., solution_mappings=True);an iterable of any of these, mapped batch by batch;
nothing, for a template without parameters.
m = Model()
m.add_template("""
@prefix ex: <http://example.net/ns#> .
ex:Reading [ ottr:IRI ?sensor, xsd:double ?value, xsd:dateTime ?at ] :: {
ottr:Triple(?sensor, ex:value, ?value),
ottr:Triple(?sensor, ex:at, ?at)
} .
""")
from datetime import datetime
df = pl.DataFrame({
"sensor": [EX + "s1", EX + "s2"],
"value": [1.5, 2.5],
"at": [datetime(2024, 1, 1), datetime(2024, 1, 2)],
})
m.map("ex:Reading", df) # the default graph
m.map("ex:Reading", df.lazy(), graph="urn:readings") # a LazyFrame, into a named graph
m.map("ex:Reading", (df.slice(i, 1) for i in range(2))) # an iterable of batches
Polars types map to XSD datatypes: Utf8 to xsd:string, Int64 to xsd:long, Int32 to
xsd:int, UInt32 to xsd:unsignedInt, Float64 to xsd:double, Boolean to xsd:boolean,
Datetime to xsd:dateTime, Date to xsd:date, and List to lists. Decimal columns must have
precision 38 and scale 16 (pl.Decimal(38, 16)) to map to xsd:decimal. A typed parameter checks
the column, and validate_iris=False skips checking IRI columns.
map_triples¶
map_triples(data, predicate=None, graph=None, validate_iris=True, stream=False) adds triples
straight from columns subject, object and, optionally, predicate:
m = Model()
m.map_triples(pl.DataFrame({
"subject": [EX + "alice", EX + "bob"],
"object": [EX + "bob", EX + "carol"],
}), predicate=EX + "knows")
m.map_triples(pl.DataFrame({
"subject": [EX + "alice"],
"predicate": [EX + "name"],
"object": ["Alice"],
}))
print(m.writes(format="ntriples"))
Strings in subject and predicate are IRIs. A string object column holds either only IRIs or
only literals: mixing them raises an error. Use a template when the object type needs to be explicit.
map_default and generate_template¶
map_default(data, primary_key_column) maps a DataFrame without writing a template: it makes a
default template where the key column is the subject of one ottr:Triple per other column, with
predicates in the urn:fastrdf_default: namespace, adds it to the model, maps the data with it and
returns it. It takes graph, validate_iris and stream like map, and a LazyFrame or an
iterable of batches, where the template comes from the first batch with all parameters optional.
df = pl.DataFrame({"id": [EX + "a", EX + "b"], "weight": [1.5, None], "label": ["A", "B"]})
template = m.map_default(df, "id")
print(template)
The returned text ends with a usage example in stOTTR comments, so it is still a template that
map takes:
# This template is added to the Model, and the data is mapped with it.
# Usage example, mapping more data with the same columns:
# m.map("urn:fastrdf_default:default_template_...", df)
# Usage example, querying the mapped data:
# m.query("SELECT ?id ?weight WHERE { ?id <urn:fastrdf_default:weight> ?weight }")
generate_template(data, primary_key_column) is its dry run: it returns the same template without
mapping anything or adding it to the model. Review or edit it, then map with it:
template = m.generate_template(df, "id")
print(template) # ? xsd:double ?weight is optional, as the column has nulls
m.map(template, df)
Façade-X: map_df, map_json and map_xml¶
map_df, map_json and map_xml map data generically, mirroring its structure with the
Façade-X vocabulary
(fx: <http://sparql.xyz/facade-x/ns/>, keys and columns as xyz: <http://sparql.xyz/facade-x/data/>).
Query or insert CONSTRUCT queries to turn it into your own model.
m = Model()
m.map_df(pl.DataFrame({"name": ["Alice", "Bob"], "age": [30, 40]})) # one fx:child node per row
m.map_json('{"name": "Alice", "address": {"city": "Oslo"}, "tags": ["a", "b"]}')
m.map_xml('<root><person id="1"><name>Alice</name></person></root>')
print(m.query("""
PREFIX xyz: <http://sparql.xyz/facade-x/data/>
SELECT ?name ?city WHERE { ?r xyz:name ?name ; xyz:address/xyz:city ?city }
"""))
map_json and map_xml take a path, a string or an iterable of them (e.g. the lines of a JSON
Lines file), mapped one document at a time. uuid_namespace makes the generated IRIs reproducible
(UUID v5); document number i of an iterable then uses the namespace <uuid_namespace>/<i>. All
three take graph=.
records = ['{"id": 1, "name": "Alice"}', '{"id": 2, "name": "Bob"}']
m.map_json(records, graph="urn:records", uuid_namespace="urn:records")
CSV on the Web: map_csvw¶
map_csvw(source, metadata=None, graph=None, minimal=False, iri_mappings=None) converts CSV and
TSV files to RDF as the W3C CSV on the Web recommendations
specify. source is a metadata document or a tabular file: for a CSV file, fastrdf looks for
<file>-metadata.json or csv-metadata.json next to it, and otherwise uses the header row. It
returns the SPARQL Update it generated, so you can inspect or adapt it.
import json
with open("trees.csv", "w") as f:
f.write("id,species,height\n1,Oak,12.5\n2,Birch,8\n")
with open("trees.csv-metadata.json", "w") as f:
json.dump({
"@context": "http://www.w3.org/ns/csvw",
"url": "trees.csv",
"tableSchema": {
"columns": [
{"name": "id", "titles": "id", "datatype": "integer"},
{"name": "species", "titles": "species"},
{"name": "height", "titles": "height", "datatype": "decimal"},
],
"aboutUrl": "http://example.net/tree/{id}",
"propertyUrl": "http://example.net/ns#{_name}",
},
}, f)
m = Model()
update = m.map_csvw("trees.csv", minimal=True) # minimal: only the triples of the cells
print(m.writes(format="turtle"))
# <http://example.net/tree/1> <http://example.net/ns#height> "12.5"^^xsd:decimal ;
# <http://example.net/ns#id> "1"^^xsd:integer ; <http://example.net/ns#species> "Oak" . ...
Documents are never fetched over the network: file: IRIs are read directly, and
iri_mappings={"https://example.org/data/": "local_folder"} maps other IRIs to local folders.
Cells that don’t match their datatype give Python warnings.
Relational databases: map_r2rml¶
map_r2rml(mapping=None, database=None, tables=None, base_iri=None, graph=None, ignore_data_errors=False, mapping_graph=None) maps relational data to RDF with a W3C
R2RML mapping. Each logical table of the mapping (rr:tableName
or rr:sqlQuery) is queried once, and the term maps are then evaluated column by column, so no
rows are handled one by one in Python.
import duckdb
con = duckdb.connect()
con.execute("CREATE TABLE site AS SELECT * FROM (VALUES ('N1', 'North')) t(code, label)")
con.execute("""CREATE TABLE pump AS SELECT * FROM (VALUES
(1, 'Feed pump', 'N1', 7.5::DOUBLE), (2, 'Booster', 'N1', NULL)) t(id, name, site, kw)""")
mapping = """
@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix ex: <http://example.net/ns#> .
<#Pump> rr:logicalTable [ rr:tableName "pump" ] ;
rr:subjectMap [ rr:template "http://example.net/pump/{id}" ; rr:class ex:Pump ] ;
rr:predicateObjectMap [ rr:predicate ex:name ;
rr:objectMap [ rr:column "name" ; rr:language "en" ] ] ;
rr:predicateObjectMap [ rr:predicate ex:powerKW ; rr:objectMap [ rr:column "kw" ] ] ;
rr:predicateObjectMap [ rr:predicate ex:site ;
rr:objectMap [ rr:parentTriplesMap <#Site> ;
rr:joinCondition [ rr:child "site" ; rr:parent "code" ] ] ] .
<#Site> rr:logicalTable [ rr:sqlQuery "SELECT code, label FROM site" ] ;
rr:subjectMap [ rr:template "http://example.net/site/{code}" ] ;
rr:predicateObjectMap [ rr:predicate ex:label ; rr:objectMap [ rr:column "label" ] ] .
"""
m = Model()
m.map_r2rml(mapping, database=con)
print(m.writes(format="turtle"))
# <http://example.net/pump/1> a <http://example.net/ns#Pump> ;
# <http://example.net/ns#name> "Feed pump"@en ;
# <http://example.net/ns#powerKW> "7.5"^^xsd:double ;
# <http://example.net/ns#site> <http://example.net/site/N1> .
# <http://example.net/pump/2> a <http://example.net/ns#Pump> ;
# <http://example.net/ns#name> "Booster"@en ;
# <http://example.net/ns#site> <http://example.net/site/N1> .
# <http://example.net/site/N1> <http://example.net/ns#label> "North" .
mapping is a path to a Turtle file or the Turtle itself. A NULL gives no triple, as for the
power of the second pump.
Where the rows come from. fastrdf never opens the database connection itself: it calls your
Python object with the SQL of each logical table (SELECT * FROM <rr:tableName>, or the
rr:sqlQuery as written) and takes the result.
databaseis any object whosequery(sql)returns a PolarsDataFrame, such as the databases infastrdf.virtualization, or a DuckDB connection, whose results are taken as Arrow record batches.tablesholds results you fetched yourself as Polars DataFrames, keyed by therr:tableNameor by the SQL query. Tables that are not intablesare queried fromdatabase.
import polars as pl
class Postgres: # an adapter for any other driver
def __init__(self, uri):
self.uri = uri
def query(self, sql: str) -> pl.DataFrame:
return pl.read_database_uri(sql, self.uri)
m.map_r2rml("mapping.ttl", database=Postgres("postgresql://user@host/plant"))
m.map_r2rml(mapping, tables={"pump": pump_df, "SELECT code, label FROM site": site_df})
The SQL is sent as it is in the mapping, without translation between dialects, so write table names and queries for the database you use.
The mapping in a named graph. With mapping_graph, the mapping is read from the triples of a
graph of the model instead. It can then be queried, changed with update, validated with SHACL,
and it is kept by serialize.
m = Model()
m.reads(mapping, format="turtle", graph="urn:graph:r2rml", base_iri="http://example.net/maps")
m.map_r2rml(mapping_graph="urn:graph:r2rml", database=con, graph="urn:graph:plant")
m.query("""PREFIX rr: <http://www.w3.org/ns/r2rml#>
SELECT ?map ?table WHERE { ?map rr:logicalTable/rr:tableName ?table }""",
graph="urn:graph:r2rml")
# <http://example.net/maps#Pump>, "pump"
A mapping with relative IRIs such as <#Pump> needs a base_iri when it is read into the graph.
graph is the graph of the triples without a graph map (and of rr:defaultGraph); triples with
rr:graph or rr:graphMap go to the graphs these give. Keep it apart from the mapping graph
unless you want the mapping and the data together.
IRIs. Values in an IRI template are percent encoded (A b becomes A%20b). Relative IRIs
that the mapping generates are resolved against base_iri, which defaults to urn:fastrdf:r2rml:.
With mapping, base_iri also resolves the relative IRIs of the mapping document, such as
<#Pump>; a mapping in a graph was resolved when it was read.
Data errors. A value that gives an invalid IRI, or that is not valid for the rr:datatype of
its term map, raises an exception. With ignore_data_errors=True the term is left out and a
Python warning describes it.
What is supported. rr:tableName and rr:sqlQuery; constant, column and template term maps
and the shortcuts rr:subject, rr:predicate, rr:object and rr:graph; rr:termType,
rr:language and rr:datatype; literals typed after the column type when no datatype is given;
rr:class; graph maps; and referencing object maps with and without join conditions. Column
names may be delimited ("Name", matched exactly) or regular (Name, matched exactly or else
without regard to case). The W3C R2RML test cases are included in the tests, run with DuckDB.
Things to know:
Each logical table is read into memory in full, and joins between triples maps are done by fastrdf, not by the database. Put the join in an
rr:sqlQueryto have the database do it.rr:sqlVersionandrr:inverseExpressionare ignored.This materializes the triples. To leave time series in the database and query them through SPARQL, see Virtualization.
m.map_fabric(...)generates an R2RML mapping from a Microsoft Fabric ontology, runs it withmap_r2rmland returns it.
CSV, JSON and XML with RML: map_rml¶
map_rml(mapping=None, sources=None, mapping_graph=None, database=None, tables=None, base_iri=None, graph=None, ignore_data_errors=False, namespaces=None) maps CSV, JSON and XML sources with an
RML mapping. RML is R2RML with two changes: a logical source
(rml:logicalSource) with a reference formulation and an iterator takes the place of the logical
table, and references (rml:reference, and {reference} in templates) take the place of
columns. Term maps, classes, graphs, joins, base IRIs and data errors work as in
map_r2rml.
plant = """{
"pumps": [
{"id": 1, "name": "Feed pump", "kw": 7.5, "site": {"code": "N1"}, "tags": ["feed", "main"]},
{"id": 2, "name": "Booster", "kw": 11, "site": {"code": "N1"}, "tags": []}
],
"sites": [{"code": "N1", "label": "North"}]
}"""
mapping = """
@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix rml: <http://semweb.mmlab.be/ns/rml#> .
@prefix ql: <http://semweb.mmlab.be/ns/ql#> .
@prefix ex: <http://example.net/ns#> .
<#Pump> rml:logicalSource [ rml:source "plant.json" ;
rml:referenceFormulation ql:JSONPath ; rml:iterator "$.pumps[*]" ] ;
rr:subjectMap [ rr:template "http://example.net/pump/{id}" ; rr:class ex:Pump ] ;
rr:predicateObjectMap [ rr:predicate ex:name ; rr:objectMap [ rml:reference "name" ] ] ;
rr:predicateObjectMap [ rr:predicate ex:powerKW ; rr:objectMap [ rml:reference "kw" ] ] ;
rr:predicateObjectMap [ rr:predicate ex:tag ; rr:objectMap [ rml:reference "tags[*]" ] ] ;
rr:predicateObjectMap [ rr:predicate ex:site ;
rr:objectMap [ rr:parentTriplesMap <#Site> ;
rr:joinCondition [ rr:child "site.code" ; rr:parent "code" ] ] ] .
<#Site> rml:logicalSource [ rml:source "plant.json" ;
rml:referenceFormulation ql:JSONPath ; rml:iterator "$.sites[*]" ] ;
rr:subjectMap [ rr:template "http://example.net/site/{code}" ] ;
rr:predicateObjectMap [ rr:predicate ex:label ; rr:objectMap [ rml:reference "label" ] ] .
"""
m = Model()
m.map_rml(mapping, sources={"plant.json": plant})
print(m.writes(format="turtle"))
# <http://example.net/pump/1> a <http://example.net/ns#Pump> ;
# <http://example.net/ns#name> "Feed pump" ;
# <http://example.net/ns#powerKW> "7.5"^^xsd:double ;
# <http://example.net/ns#site> <http://example.net/site/N1> ;
# <http://example.net/ns#tag> "feed", "main" .
# <http://example.net/pump/2> a <http://example.net/ns#Pump> ;
# <http://example.net/ns#name> "Booster" ;
# <http://example.net/ns#powerKW> "11.0"^^xsd:double ;
# <http://example.net/ns#site> <http://example.net/site/N1> .
# <http://example.net/site/N1> <http://example.net/ns#label> "North" .
The iterator selects the records, and each reference is evaluated on a record. A reference with
several values, such as tags[*], gives a triple per value, and a missing key, a null or an
empty array gives none.
Sources. sources holds the sources by their rml:source in the mapping: a path, the document
as a string or bytes, or for CSV also a Polars DataFrame. A source that is not in sources is
read from the file that its rml:source names, relative to the working directory or to the folder
of the mapping file. Nothing is fetched over the network. A mapping may also have logical tables of
R2RML next to its logical sources, which are queried in database or given in tables, so one
mapping can join a database table with a file. mapping_graph reads the mapping from a graph of
the model, as for map_r2rml.
m.map_rml("mapping.ttl") # the files named in the mapping
m.map_rml(mapping, sources={"plant.json": "/data/plant-2026.json"})
m.map_rml(mapping, sources={"sites.csv": sites_df}, database=con)
A source can also be described in the mapping, in the vocabulary of the W3C community group, with the values that are no value, a compression and an encoding:
rml:source [ a rml:FilePath ; rml:path "readings.csv.gz" ;
rml:compression rml:gzip ; # also rml:zip, rml:tarxz, rml:targz (the first file)
rml:encoding rml:UTF-16 ; # when the file is not UTF-8
rml:null "" , "NULL" , "n/a" ] ; # these values give no term
rml:null applies to the strings of any source, also one given as a DataFrame. A compressed or
encoded source is read from its file, or from bytes in sources.
XML sources have the reference formulation ql:XPath:
mapping = """
@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix rml: <http://semweb.mmlab.be/ns/rml#> .
@prefix ql: <http://semweb.mmlab.be/ns/ql#> .
@prefix ex: <http://example.net/ns#> .
<#Pump> rml:logicalSource [ rml:source "plant.xml" ;
rml:referenceFormulation ql:XPath ; rml:iterator "/plant/pump[@kind='feed']" ] ;
rr:subjectMap [ rr:template "http://example.net/pump/{@id}" ] ;
rr:predicateObjectMap [ rr:predicate ex:name ; rr:objectMap [ rml:reference "name" ] ] ;
rr:predicateObjectMap [ rr:predicate ex:plant ; rr:objectMap [ rml:reference "../@name" ] ] .
"""
m.map_rml(mapping, sources={"plant.xml": """<plant name="North">
<pump id="1" kind="feed"><name>Feed pump</name></pump>
<pump id="2" kind="booster"><name>Booster</name></pump>
</plant>"""})
# <http://example.net/pump/1> <http://example.net/ns#name> "Feed pump" ;
# <http://example.net/ns#plant> "North" .
XML namespaces. As in XPath, a name without a prefix has no namespace, so a document with a
default namespace (xmlns="...") needs prefixes in the paths. A prefix is looked up in
namespaces, then in the mapping (rml:namespace on an rml:XPathReferenceFormulation), then in
the document. namespaces={"": "..."} lets names without a prefix match the default namespace:
doc = """<plant xmlns="http://example.com/plant"><pump id="1" kind="feed"><name>Feed pump</name></pump></plant>"""
m.map_rml(mapping, sources={"plant.xml": doc}, namespaces={"": "http://example.com/plant"})
An iterator without prefixes that selects nothing in such a document raises an error that names the namespace.
CSV sources have the reference formulation ql:CSV and no iterator: the records are the rows
and the references are the column names.
Types. JSON numbers and booleans give xsd:integer, xsd:double and xsd:boolean literals
when all the values of a reference have that type. The values of CSV and XML sources are strings.
Give the term map an rr:datatype for another type.
Term maps beyond R2RML. These work in map_rml and in map_r2rml, on any kind of source:
In the mapping |
Gives |
|---|---|
|
the language of each literal from its record; a record without one gives no literal |
|
the datatype of each literal from its record |
|
the base IRI of the relative IRIs of that triples map, instead of |
|
a join on the values of a reference, a template or a constant, compared as strings |
a subject or object map with only |
a blank node per record |
|
an IRI whose template values are percent encoded outside ASCII too ( |
|
an IRI whose template values are not encoded; a value that makes the IRI invalid is a data error |
With rr:termType rr:IRI, or none, the values of a template are IRI-safe as R2RML defines it:
characters that are reserved in IRIs are percent encoded (A b becomes A%20b), and letters
outside ASCII are kept (Zoë stays Zoë).
The references of a triples map are evaluated independently of each other. A literal and its
language map therefore pair up per record, not per value: when a record has several labels, each
with a language, iterate over the labels (rml:iterator ".../label" with the references . and
@lang) rather than over their parent.
Vocabularies. Both RML vocabularies are read, also mixed in one mapping: the first one shown
above (rml: is http://semweb.mmlab.be/ns/rml#, with rr: term maps and the ql: reference
formulations), and that of the W3C community group, where every term is in http://w3id.org/rml/
(rml:subjectMap, rml:template, rml:JSONPath, …).
Paths. JSON and XML sources are mapped to a temporary graph with the
Façade-X mapping of map_json and map_xml, and the
iterator and references are translated to SPARQL over it. The supported paths are those that
translate; anything else raises an error that names it:
Supported |
Not supported |
|
|---|---|---|
JSONPath |
|
indexes and slices, filters, |
XPath |
names, |
positions, functions, axes, unions, comparisons other than |
Array items have no order and equal items are one value; the value of an XML element is its own
text; a JSON reference must select values, not an object or an array (tags[*], not tags). A
reference that matches nothing gives no value, except a missing CSV column, which is an error.
Not supported: RML functions (FnO), RML-star, logical targets, remote sources and sources
described as databases. map_rml passes 214 of the 225 cases of the RML-Core, RML-IO and first
RML test suites; py_fastrdf/tests/rml_community_known_failures.txt lists the others with reasons.
Templates from an ontology: generate_templates¶
fastrdf.generate_templates(m, graph=None, prefixes=None) makes one template per class of an
ontology, from rdfs:subClassOf, rdfs:domain, rdfs:range (also through owl:unionOf),
owl:Restriction and the declared property types. The subject parameter is id. The other,
optional, parameters are named by the prefixed IRIs of the properties, e.g. ex:flowRate, so name
the DataFrame columns like that. prefixes gives the prefix names (common ones such as rdfs and
skos are known), and other namespaces get ns1, ns2, … Properties whose range is the class
are included in reverse, with the suffix _inverse. Each class gets a template with the class IRI,
which also adds the rdf:type triple, and one suffixed _notype without it. Add all of them to the
model you populate, since subclass templates call the superclass templates.
from fastrdf import generate_templates
ontology = Model()
ontology.reads("""
@prefix ex: <http://example.net/ns#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ex:Pump a owl:Class .
ex:flowRate a owl:DatatypeProperty ; rdfs:domain ex:Pump ; rdfs:range xsd:double .
""", format="turtle")
templates = generate_templates(ontology, prefixes={"ex": EX})
print([p.variable.name for p in templates[EX + "Pump"].parameters]) # ['id', 'ex:flowRate']
m = Model()
for t in templates.values():
m.add_template(t)
m.map(EX + "Pump", pl.DataFrame({"id": [EX + "p1"], "ex:flowRate": [12.0]}))
print(m.writes(format="turtle"))
Copying triples between models: add_triples¶
fastrdf.add_triples(source, target, source_graph=None, target_graph=None) copies the triples of a
graph of one model into another, predicate by predicate. Model.add_graph
(section 7) does the same as a method.
from fastrdf import add_triples
target = Model()
add_triples(m, target, target_graph="urn:copy")
print(target.size("urn:copy"))
OPC UA NodeSets¶
m.map_opc_ua("my_opc_ua_nodeset2_xmls", graph="urn:fastrdf:uagraphs")
The folder must contain the Namespace 0 NodeSet2 XML.
m.opcua.add_typing_shapes(shapes_graph=None, type_namespaces=None, instance_namespaces=None) generates
SHACL shapes from the type definitions in the mapped nodesets: a shape for each ObjectType and VariableType
(targeting the nodes with that HasTypeDefinition), one for each browse path of their fully inherited
instance declarations, and cardinality shapes requiring each Mandatory instance declaration exactly once.
Shapes of types with no instances are deactivated. All have fastrdf:shapeCategory uamapper:OPCUATypingValidation
(uamapper: is https://github.com/DataTreehouse/uamapper#). Give either the instance namespaces or the
type namespaces; without either, a namespace holds types when it has type nodes. The generation also adds
helper triples that your own shapes can use, such as ?ns uamapper:typeNamespace false for instance namespaces.
m.opcua.add_typing_shapes(shapes_graph="urn:shapes", instance_namespaces=["urn:my:instances"])
m.read("my_opc_ua_shapes.ttl", graph="urn:shapes") # your own rules
report = m.validate(shape_graph="urn:shapes", report_graph="urn:report")
5. Streaming with ModelStream¶
map, map_triples, map_json and map_xml take stream=True and then return a lazy
ModelStream instead of mapping into the model. You add steps to it, each returning a new
ModelStream, and nothing runs until collect():
Step |
Does |
|---|---|
|
a SPARQL Update, as |
|
inserts the results of a CONSTRUCT, as |
|
Datalog inference, as |
|
appends the batch to a file: |
|
runs the pipeline |
For each batch of the input, collect() maps the batch into a fresh in-memory model that has the
templates, prefixes and UDFs of the model, runs the steps in order, appends to the files, and drops
the batch model. Memory use depends on the batch size, not on the input size.
m = Model()
m.add_prefixes({"ex": EX})
m.add_template("""
@prefix ex: <http://example.net/ns#> .
ex:Upper [ ottr:IRI ?s, ?u ] :: { ottr:Triple(?s, ex:upper, ?u) } .
""")
big = pl.DataFrame({"s": [f"{EX}n{i}" for i in range(10_000)], "u": [f"N{i}" for i in range(10_000)]})
batches = (big.slice(i, 1_000) for i in range(0, 10_000, 1_000))
(
m.map("ex:Upper", batches, stream=True)
.write("before.nt")
.update("INSERT { ?s a ex:Node } WHERE { ?s ex:upper ?u }")
.insert("CONSTRUCT { ?s ex:label ?u } WHERE { ?s ex:upper ?u }")
.write("after.ttl", format="turtle")
.collect()
)
print(m.size()) # 0: the model itself is unchanged
Things to know:
Steps only see the triples of the current batch, so joins across batches find nothing. Split the input so that what belongs together is in one batch.
Files are created (or truncated) when
collect()starts.writealso takes a binary file-like object, which is flushed but not closed. Iterators given as input are consumed.Blank node labels stay unique across batches.
A useful pattern is to map documents into the transient graph and write only what a CONSTRUCT query makes from them:
from fastrdf import TRANSIENT_GRAPH
with open("records.jsonl", "w") as f:
f.write('{"name": "Alice"}\n{"name": "Bob"}\n')
records = """
PREFIX fx: <http://sparql.xyz/facade-x/ns/>
PREFIX xyz: <http://sparql.xyz/facade-x/data/>
PREFIX ex: <http://example.net/ns#>
CONSTRUCT { ?r a ex:Record ; ex:name ?name } WHERE { ?r a fx:root ; xyz:name ?name }
"""
with open("records.jsonl") as lines:
(
Model()
.map_json(lines, graph=TRANSIENT_GRAPH, stream=True, documents_per_batch=1_000)
.insert(records)
.write("records.nt")
.collect()
)
print(open("records.nt").read())
6. Reading and writing¶
Formats¶
Format |
|
Read |
Write |
|---|---|---|---|
N-Triples |
|
yes (parallel) |
yes |
Turtle |
|
yes (parallel with |
yes, pretty-printed |
N-Quads |
|
yes (parallel) |
yes |
TriG |
|
yes |
yes |
RDF/XML |
|
yes (parallel) |
yes |
JSON-LD |
|
yes |
yes, compacted |
HDT |
|
yes |
yes ( |
Jelly |
|
yes (Jelly-RDF 1.0, 1.1 and 1.2) |
yes, Jelly-RDF 1.2 ( |
CIM/XML |
|
yes (parallel) |
|
Without format, it is taken from the file extension (.nt, .ttl, .nq, .trig, .rdf/.xml,
.jsonld, .hdt, .jelly).
m = Model()
m.reads(f"""
@prefix ex: <{EX}> .
ex:alice ex:name "Alice" ; ex:knows ex:bob .
""", format="turtle")
m.write("people.ttl", format="turtle", prefixes={"ex": EX})
m.write("people.nt") # format from the extension
m2 = Model()
m2.read("people.ttl")
m2.read("people.nt", graph="urn:copy", replace_graph=True)
s = m2.writes(format="ntriples", graph="urn:copy")
read and reads options:
graph=reads into a named graph (for TriG, N-Quads, JSON-LD and Jelly, the graphs named in the document are used when it is not given), andreplace_graph=Truereplaces the graph’s triples.base_iri=sets the base for relative IRIs.parallel=parses N-Triples, N-Quads, Turtle, RDF/XML and CIM/XML in parallel. It is on by default for N-Triples, N-Quads, RDF/XML and CIM/XML, and for Turtle it assumes that all prefixes come at the start of the document.checked=Falseskips IRI checks.strict=Trueraises on literals that don’t parse as their datatype (e.g."abc"^^xsd:integer). By default such triples are dropped with a warning.triples_batch_size=sets the number of triples read per batch.known_contexts=resolves JSON-LD contexts locally (see below).geo=Trueonly applies to CIM/XML.
Jelly¶
Jelly-RDF is a binary format of Protocol Buffers messages. Streams of
Jelly-RDF 1.2 (the column layout) and of 1.0 and 1.1 (the row layout) are read, with triples, quads
or graphs. write gives a Jelly-RDF 1.2 stream: the triples of one graph, or with a list of graphs
their quads.
m.write("people.jelly", format="jelly") # the triples of the default graph
m.write("dataset.jelly", format="jelly", graph=[DEFAULT_GRAPH, "urn:copy"]) # quads
m5 = Model()
m5.read("dataset.jelly") # quads go to their graphs
A stream of RDF Messages is read as the union of its messages, and the blank nodes of each message
are kept apart. RDF 1.2 triple terms and base directions, RDF-star quoted triples and generalized
statements are not supported, and a stream that has them is rejected. So is a stream whose lookups
are larger than the sizes the Jelly specification recommends to accept (16,384 names, 4,096 prefixes
and 256 datatypes), unless the environment variable FASTRDF_JELLY_MAX_NAME_TABLE_SIZE,
FASTRDF_JELLY_MAX_PREFIX_TABLE_SIZE or FASTRDF_JELLY_MAX_DATATYPE_TABLE_SIZE is set to a larger
size.
Bytes and file-like objects¶
read also takes bytes, bytearray, memoryview or a file-like object with a read method
(text streams are read as UTF-8). format is then required, except for HDT and Jelly, which are detected.
write takes a binary file-like object, and write_bytes returns bytes in any format:
import io
hdt = m.write_bytes(format="hdt")
m3 = Model()
m3.read(hdt) # HDT is detected
buf = io.BytesIO()
m.write(buf, format="ntriples")
m4 = Model()
m4.read(io.BytesIO(buf.getvalue()), format="ntriples")
with open("people.nt", "rb") as f:
m4.read(f, format="ntriples")
Object storage¶
read, read_template, write, write_cim_xml, serialize and deserialize take URLs of
Amazon S3 (s3://bucket/path), Google Cloud Storage (gs://bucket/path), Azure Blob Storage
(az://container/path, abfss://container@account.dfs.core.windows.net/path,
https://account.blob.core.windows.net/container/path), HTTP(S) and file://. Credentials come
from the environment as the cloud SDKs find them (e.g. AWS_ACCESS_KEY_ID,
GOOGLE_APPLICATION_CREDENTIALS, AZURE_STORAGE_ACCOUNT_NAME and AZURE_STORAGE_ACCOUNT_KEY), or from
storage_options, with the option names of Polars’ storage_options:
m.read("s3://my-bucket/data/triples.ttl")
m.write("gs://my-bucket/out/triples.nt")
m.read("az://my-container/data.nt",
storage_options={"azure_storage_account_name": "acc", "azure_storage_account_key": "..."})
Files that are read are downloaded to the system temporary folder first (set TMPDIR to change
it). Written objects are uploaded as they are written, and appear when the write completes.
JSON-LD¶
Writing JSON-LD gives a compacted document with a @context of the prefixes used and one node
object per subject. known_contexts maps context URLs to their content when reading, so that
nothing is fetched:
doc = '{"@context": "https://example.net/context.jsonld", "@id": "http://example.net/ns#alice", "name": "Alice"}'
ctx = '{"@context": {"name": "http://example.net/ns#name"}}'
m = Model()
m.reads(doc, format="json-ld", known_contexts={"https://example.net/context.jsonld": ctx})
print(m.writes(format="json-ld", prefixes={"ex": EX}))
Several graphs in one file¶
For the dataset formats (JSON-LD, TriG and N-Quads), graph can be a list of graphs to write.
fastrdf.DEFAULT_GRAPH names the default graph in such a list. Without graph, TriG and N-Quads
write every graph except the transient graph.
from fastrdf import DEFAULT_GRAPH
m = Model()
m.reads(f"<{EX}a> <{EX}p> <{EX}b> .", format="ntriples")
m.reads(f"<{EX}c> <{EX}p> <{EX}d> .", format="ntriples", graph="http://example.net/g1")
m.write("dataset.jsonld", format="json-ld", graph=[DEFAULT_GRAPH, "http://example.net/g1"])
m.write("dataset.trig", format="trig") # all graphs
m.write("dataset.nq", format="nquads", graph=["http://example.net/g1"])
serialize and deserialize¶
serialize saves the whole model in fastrdf’s own Parquet-based format, by default as a single
file (.fastrdf by convention). This is much faster to load than RDF text. Model.deserialize
restores it, also into hybrid or disk storage. It also reads the files that maplib serialized, see
the migration guide.
Blank nodes that are read, inserted or mapped into the restored model are new ones, also when a document that the model already has is read again.
m.serialize("model.fastrdf")
m2 = Model.deserialize("model.fastrdf")
print(m2.size(), m2.size("http://example.net/g1"))
m.serialize("model_folder", single_file=False) # a folder of Parquet files
m3 = Model.deserialize("model_folder") # files and folders are both detected
m.serialize("model.fastrdf", raw_db=True) # DuckDB dictionaries, used in place
m = Model.deserialize("model.fastrdf", storage="disk", storage_folder="fastrdf_disk")
m.serialize("gs://my-bucket/models/model", single_file=False, raw_db=True)
m = Model.deserialize("gs://my-bucket/models/model", storage="disk",
storage_folder="/mnt/nvme/fastrdf", cache_size=200 * 2**30)
With raw_db=True, the full text search index of the model and its options are serialized too,
and the deserialized model is searched without create_index. Other serializations have no index.
Serializing a folder to object storage writes a new generation folder and then publishes it
atomically, so readers see either the old or the new model. With storage="disk", the triple
tables of such a folder are downloaded when they are first read, and cache_size bounds how much
of them is kept locally.
CIM/XML¶
PROFILE_GRAPH = "urn:graph:profiles"
m = Model()
m.read("model.xml", format="cim/xml", geo=True) # geo maps cim:Location to GeoSPARQL
m.read("61970-600-2_Equipment-AP-Voc-RDFS2020_v3-0-0.rdf", graph=PROFILE_GRAPH, format="rdf/xml")
m.write_cim_xml(
"out.xml",
profile_graph=PROFILE_GRAPH,
description="MyModel",
created="2023-09-14T20:27:41",
scenario_time="2023-09-14T02:44:43",
modeling_authority_set="www.example.org",
version="22",
)
Cutting a part of a CIM grid¶
m.cim.cut_to_graph cuts the grid around interior equipment out of a
model, stopping at border equipment, which is left out. The cut holds the equipment reached
through terminals and connectivity nodes (by default the normal topology: normally open switches
and equipment normally out of service are not passed), their terminals with connectivity nodes,
those connectivity nodes, and the resources they refer to up to context_hops (10) steps away
(containers, base voltages, locations, transformer ends, …), but never other conducting
equipment, terminals or connectivity nodes. Every step is SPARQL that fastrdf evaluates:
fastrdf:component with fastrdf:avoid for the reachable topology, fastrdf:shortestPath for
max_distance, and INSERTs for the rest.
m = Model()
m.read("EQ.xml", format="cim/xml", graph="urn:graph:eq")
m.read("GL.xml", format="cim/xml", graph="urn:graph:gl")
m.read("61970-600-2_Equipment-AP-Voc-RDFS2020_v3-0-0.rdf", format="rdf/xml", graph="urn:graph:rdfs")
counts = m.cim.cut_to_graph(
["urn:uuid:busbar-in-the-area"], # interior equipment
["urn:uuid:line-leaving-the-area"], # border equipment, left out
target_graph="urn:graph:cut", # without it, nothing is written
graphs=["urn:graph:eq", "urn:graph:gl", "urn:graph:rdfs"], # None: the default graph
)
print(counts) # members, equipment, terminals, connectivity_nodes, non_members, context,
# boundary_equipment, triples
The graphs are read as one dataset, so the instance data, the rdf:type triples, the profiles
(EQ, SSH, TP, SV, GL) and the CIM vocabulary may each be in a graph of their own. The context
follows the CIM properties whose range is not an XML Schema datatype in the vocabulary (any CIM
predicate with IRI objects when there is none). cim.cut(m, border_equipment_iris, interior_equipment_iri, ...) returns the cut as a Model of its own (m.cim.cut(...)).
m.cim holds the CIM grid tools bound to the model: cut_to_graph and
cut, the serves relations (add_serves, see its docstring), reading types, and the templates and
annotations of the time series of measurements and meter readings
(CIM time series). Each is the function of the cim package with the
same name, with the model as its first argument.
7. Named graphs and the transient graph¶
Most methods take graph= to work on a named graph instead of the default graph.
m = Model()
m.reads(f"<{EX}a> <{EX}p> <{EX}b> .", format="ntriples")
m.reads(f"<{EX}b> <{EX}p> <{EX}c> .", format="ntriples", graph="urn:g1")
print(m.size(), m.size("urn:g1")) # 1 1
print(m.query("SELECT * WHERE { ?s ?p ?o }", graph="urn:g1"))
print(m.query("SELECT * WHERE { GRAPH <urn:g1> { ?s ?p ?o } }")) # GRAPH works too
include_graphs (in query, update, insert and infer) merges other graphs into the queried graph, as FROM does:
print(m.query("SELECT ?s ?o WHERE { ?s <http://example.net/ns#p>+ ?o }", include_graphs=["urn:g1"]))
TRANSIENT_GRAPH¶
fastrdf.TRANSIENT_GRAPH is a reserved graph for triples that should take part in querying,
validation and reasoning, but not be written: map, read or insert into it. Queries, updates,
inserts and inference include it by default (include_graphs=None); pass include_graphs=[] to
leave it out. Writing all graphs as TriG or N-Quads leaves it out; write it with
graph=TRANSIENT_GRAPH.
from fastrdf import TRANSIENT_GRAPH
m.reads(f"<{EX}a> <{EX}helper> <{EX}x> .", format="ntriples", graph=TRANSIENT_GRAPH)
print(m.query("SELECT * WHERE { ?s <http://example.net/ns#helper> ?o }").height) # 1
print(m.query("SELECT * WHERE { ?s <http://example.net/ns#helper> ?o }", include_graphs=[]).height) # 0
print("helper" in m.writes(format="ntriples")) # False
Copying, detaching and emptying graphs¶
other = Model()
other.reads(f"<{EX}x> <{EX}p> <{EX}y> .", format="ntriples")
m.add_graph(other, source_graph=None, target_graph="urn:g2") # copy other's default graph into urn:g2
g1 = m.detach_graph("urn:g1") # urn:g1 becomes the default graph of a new Model
print(g1.size(), m.size("urn:g1")) # 1 0
g2 = m.detach_graph("urn:g2", preserve_name=True) # keeps the graph name in the new model
m.truncate_graph() # empty the default graph
print(m.size()) # 0
Comparing graphs: isomorphic and blank_node_mapping¶
Two graphs that hold the same data rarely hold the same triples, because blank nodes get new
labels every time a file is read. isomorphic says whether two graphs are the same once the
blank nodes of one are renamed, each to a different blank node of the other. IRIs and literals
must be the same.
a, b = Model(), Model()
a.reads(f'_:x <{EX}knows> _:y . _:y <{EX}name> "Bob" .', format="turtle")
b.reads(f'_:n <{EX}name> "Bob" . _:m <{EX}knows> _:n .', format="turtle")
print(a.isomorphic(b)) # True
print(a.blank_node_mapping(b)) # blank_node, other_blank_node: _:x.. -> _:m.., _:y.. -> _:n..
m.isomorphic(m, graph="urn:g1", other_graph="urn:g2") # two graphs of one model
a.isomorphic_dataset(b) # all graphs of both models
a.isomorphic(b, timeout=10) # QueryTimeoutError after 10 seconds
blank_node_mappingreturnsNonewhen the graphs are not isomorphic, and otherwise a DataFrame with one row per blank node and the string columnsblank_nodeandother_blank_node. Blank nodes are written as queries return them, so the mapping joins with query results. A graph with symmetries has several mappings; one of them is returned.isomorphic_datasetandblank_node_mapping_datasetcompare all graphs with one renaming: the default graphs must be the same, and every named graph the same as the graph of the same name. A blank node that is used in two graphs must be one blank node in the other model too, which comparing graph by graph does not check. Graphs named by blank nodes take part in the renaming, and graphs without triples do not count.Literals are compared as they are stored: numbers, booleans, dates and times are stored as values, so
"01"^^xsd:integerand"1"^^xsd:integerare the same literal.A graph without triples is isomorphic to a graph that does not exist.
The answer is exact, never an estimate. The work is done on the stored columns: tables are
compared by their sizes first, triples without blank nodes as sets, and blank nodes are told
apart by the triples around them, in rounds over all of them at once. That settles most graphs,
including long lists and thousands of blank nodes that look alike. What is left is searched:
structures made only of blank nodes in which every node looks like every other (for example
some regular graphs) can take very long, so set timeout when the graphs are not your own.
8. Querying¶
query(query, ...) runs the four SPARQL 1.1 query forms: SELECT, CONSTRUCT, ASK and
DESCRIBE.
m = Model()
m.add_prefixes({"ex": EX})
m.reads(f"""
@prefix ex: <{EX}> .
ex:alice ex:name "Alice" ; ex:age 30 ; ex:knows ex:bob .
ex:bob ex:name "Bob" ; ex:age 25 .
""", format="turtle")
Return types¶
Query |
Returns |
|---|---|
|
a |
|
a list of DataFrames with columns |
|
a |
|
as |
df = m.query("SELECT ?p ?name ?age WHERE { ?p ex:name ?name ; ex:age ?age } ORDER BY ?age")
print(df) # p: "<http://example.net/ns#bob>", name: "Bob", age: 25 ...
print(df["age"].sum()) # literals are native Polars values
triples = m.query("CONSTRUCT { ?p a ex:Adult } WHERE { ?p ex:age ?a FILTER(?a >= 18) }")
print(triples[0])
print(m.query("ASK { ex:alice ex:knows ex:bob }")) # True
DESCRIBE¶
DESCRIBE gives the triples whose subject is a described IRI, as a CONSTRUCT result. The
described IRIs are the constant IRIs after DESCRIBE, the IRIs the listed variables are bound to by
the WHERE pattern, or the IRIs every variable of the pattern is bound to with DESCRIBE *.
Blank nodes are not described, and triples where the resource is only the object are not included.
print(m.query("DESCRIBE ex:alice")) # alice's name, age and knows triples
d = m.query("DESCRIBE ?p WHERE { ?p ex:age ?a FILTER(?a < 30) }")
print(sum(df.height for df in d)) # 2: bob's name and age
d = m.query("DESCRIBE * WHERE { ex:alice ex:knows ?f }") # bob's triples (?f is bob)
print(m.query("DESCRIBE ex:bob", return_format="turtle"))
DESCRIBE reads the queried graph (graph=, include_graphs= and FROM apply as for CONSTRUCT),
and the SPARQL endpoint of Model.serve() gives the same triples. query_external refuses
DESCRIBE.
return_format¶
return_format="json" gives SPARQL JSON results (SELECT and ASK), "turtle" gives Turtle
(CONSTRUCT and DESCRIBE), and "trig" gives TriG (CONSTRUCT, including quads from GRAPH blocks):
print(m.query("SELECT ?name WHERE { ?p ex:name ?name }", return_format="json"))
print(m.query("CONSTRUCT { ?p ex:label ?n } WHERE { ?p ex:name ?n }", return_format="turtle"))
CONSTRUCT with quads: GRAPH blocks¶
A CONSTRUCT template can contain GRAPH blocks, so one query constructs quads: triples in named graphs
as well as in the default graph. This is the syntax of Apache Jena and of SPARQL Update’s INSERT
templates (w3c/sparql-dev#31). The graph is an IRI or a
variable from the WHERE clause:
m = Model()
m.add_prefixes({"ex": EX})
m.reads(f"""
@prefix ex: <{EX}> .
ex:alice ex:name "Alice" ; ex:age 30 ; ex:team ex:red .
ex:bob ex:name "Bob" ; ex:age 25 ; ex:team ex:blue .
""", format="turtle")
q = """
CONSTRUCT {
?p a ex:Person # default graph
GRAPH ex:ages { ?p ex:age ?a } # a fixed named graph
GRAPH ?t { ?p ex:name ?n } # one graph per team, from the WHERE clause
} WHERE { ?p ex:age ?a ; ex:name ?n ; ex:team ?t }
"""
for df in m.query(q):
print(df) # the GRAPH parts have an extra `graph` column
print(m.query(q, return_format="trig"))
m.insert(q) # each GRAPH block goes to its own graph, in one pass
The results:
Variable graph. Each solution gives triples in the graph the variable is bound to. Solutions where it is unbound, or bound to something other than an IRI, give none.
queryreturns one DataFrame per template triple and graph, as before. The default-graph part has the columnssubject,predicateandobject. The DataFrames from GRAPH blocks also have agraphcolumn with the graph’s IRI.return_format."trig"gives the quads as TriG."turtle"raises an error when the result has triples in named graphs.insertadds the triples of each GRAPH block to that graph, and the other triples totarget_graph(the default graph if not given). The WHERE clause is evaluated once, not once per graph.Blank nodes in the template are shared between its GRAPH blocks, within each solution.
The short form works too:
CONSTRUCT WHERE { GRAPH ?g { ?s ex:age ?a } }copies the matching quads.
bindings¶
bindings binds variables to constant terms, for parameterised queries without string
formatting. Values are IRI or Literal objects, or strings in N-Triples syntax ("<...>"):
from fastrdf import IRI, Literal, xsd
q = "SELECT ?name WHERE { ?p ex:name ?name ; ex:age ?age }"
print(m.query(q, bindings={"p": IRI(EX + "alice")}))
print(m.query(q, bindings={"p": "<http://example.net/ns#bob>"}))
print(m.query(q, bindings={"age": Literal("25", data_type=xsd.integer)}))
Round trips with SolutionMappings¶
With solution_mappings=True, query returns a SolutionMappings with mappings (a DataFrame
in fastrdf’s native encoding) and rdf_types (the RDF type of each variable). It can be mapped
straight back with a template, or passed as parameters to a query with PVALUES:
sm = m.query("SELECT ?p ?name WHERE { ?p ex:name ?name }", solution_mappings=True)
print(sm.rdf_types) # {'p': RDFType.IRI(), 'name': RDFType.Literal("http://www.w3.org/2001/XMLSchema#string")}
m.add_template("""
@prefix ex: <http://example.net/ns#> .
ex:Label [ ?p, ?name ] :: { ottr:Triple(?p, rdfs:label, ?name) } .
""")
m.map("ex:Label", sm) # types are kept
people = m.query("SELECT ?p WHERE { ?p ex:age ?a FILTER(?a > 26) }", solution_mappings=True)
print(m.query("SELECT ?p ?name WHERE { ?p ex:name ?name . PVALUES (?p) people }",
parameters={"people": people}))
You can build SolutionMappings(mappings, rdf_types) yourself, too.
graph, include_graphs and max_rows¶
graph= queries a named graph and include_graphs= merges others in (section 7).
max_rows= fails a query whose estimated result is larger, which guards against running out of memory:
try:
m.query("SELECT * WHERE { ?a ?b ?c . ?d ?e ?f . ?g ?h ?i }", max_rows=10)
except Exception as e:
print(type(e).__name__)
debug¶
debug=True explains why a query has no results, by reporting the patterns that match nothing:
m.query("SELECT ?x WHERE { ?x ex:nosuchpredicate ?y }", debug=True)
# The following triple pattern has no solution mappings: ?x <http://example.net/ns#nosuchpredicate> ?y
# - The predicate <http://example.net/ns#nosuchpredicate> is not used in the queried graph
The lines under a pattern are hints about it:
for a triple pattern: a predicate or subject that the graph does not have (with the graphs that use the predicate, and predicates with the same local name), an object that is written like objects in the data but is another term (
"42"for the integer42,"Bob"for"Bob"@en), examples of the objects that are there, and whether subject and object are in each other’s placefor patterns that match apart but not together: the variables they join on, and the kinds of terms each side has for them (e.g. IRIs on one side, strings on the other)
for a
FILTER: the number of solution mappings before it, the kinds of terms of its variables and which of the conditions joined with&&are never true
With solution_mappings=True the explanation is also in the debug field of the result.
Ctrl-C stops a running query.
Other endpoints: endpoint and query_external¶
query(..., endpoint=url) sends the query to a fastrdf server started with Model.serve()
and returns exactly what query returns on the served model (as Arrow over HTTP, with fastrdf’s
types). endpoint_token gives the server’s auth_token. parameters and debug can’t be used
with an endpoint.
query_external(query, endpoint, method="GET", ...) runs a SELECT, CONSTRUCT or ASK query on any
SPARQL 1.1 endpoint and returns a DataFrame (or SolutionMappings, JSON or Turtle, as query does).
It refuses DESCRIBE. headers is a list of
(name, value) pairs.
df = m.query_external("SELECT ?s WHERE { ?s ?p ?o } LIMIT 10",
"https://query.wikidata.org/sparql",
headers=[("User-Agent", "my-app/1.0")])
df = m.query("SELECT * WHERE { ?s ?p ?o } LIMIT 10", endpoint="http://127.0.0.1:7878/sparql")
9. SPARQL extensions¶
On top of SPARQL 1.1, fastrdf supports arithmetic and comparisons on durations, dates and times as
the XPath operators define them, e.g. ?end - ?start giving an xsd:dayTimeDuration, and
"P1D"^^xsd:dayTimeDuration = "PT24H"^^xsd:dayTimeDuration.
m = Model()
m.add_prefixes({"ex": EX, "xsd": "http://www.w3.org/2001/XMLSchema#"})
print(m.query("""
SELECT ?d WHERE {
BIND("2024-03-01T12:00:00"^^xsd:dateTime - "2024-02-28T00:00:00"^^xsd:dateTime AS ?d)
}"""))
Statistical aggregates¶
fastrdf has the statistical aggregates of Apache Jena ARQ, with the same names, namespace and
results, so queries run unchanged on both. They are in the Jena aggregate namespace
http://jena.apache.org/ARQ/function/aggregate#, and, as in Jena, also in the ARQ function
namespace http://jena.apache.org/ARQ/function# (afn:stdev and so on). Declare the prefix in the
query or with add_prefixes; it is not predefined.
Aggregate |
Computes |
Fewest values |
|---|---|---|
|
sample standard deviation (divides by n - 1) |
2 |
|
population standard deviation (divides by n) |
1 |
|
sample variance |
2 |
|
population variance |
1 |
m = Model()
m.add_prefixes({"ex": EX, "agg": "http://jena.apache.org/ARQ/function/aggregate#"})
m.reads(f"""
@prefix ex: <{EX}> .
ex:pump1 ex:reading 10, 12, 11, 15 .
ex:pump2 ex:reading 7.5, 8.0 .
""", format="turtle")
print(m.query("""
SELECT ?pump (AVG(?r) AS ?mean) (agg:stdev(?r) AS ?sd) (agg:var_pop(DISTINCT ?r) AS ?var)
WHERE { ?pump ex:reading ?r } GROUP BY ?pump
"""))
They work as other aggregates: with
DISTINCT, inHAVING, in expressions such as(MAX(?r) - AVG(?r)) / agg:stdev(?r), and as window functions, e.g.agg:stdev(?r) OVER (PARTITION BY ?pump ORDER BY ?t ROWS BETWEEN 9 PRECEDING AND CURRENT ROW)for a rolling standard deviation. Used outside an aggregation they are a syntax error.The result is an
xsd:double. Values of any numeric datatype are converted to doubles, and a group may mix numeric datatypes.DISTINCTcompares RDF terms, so1and1.0are both kept.A group with a value that is not numeric (a string, a boolean, an IRI, a date, …) gives an error, so the result is unbound. So does a group with fewer values than the table says: no values at all, or a single value for the sample statistics. The population statistics of one value are
0.0. Without GROUP BY over no solutions there is one solution with the result unbound.Unbound values (from OPTIONAL, or from an expression error) are skipped, as fastrdf does for SUM and AVG.
They are checked against Jena’s own tests for them (TestStatisticsAggregates, ported in
py_fastrdf/tests/test_statistical_aggregates.py) and against Python’s statistics module.
Jena’s ARQ syntax keywords (STDEV(?x), AGG agg:stdev(?x)) and its MEDIAN and MODE, which Jena
has only as keywords and not in the aggregate namespace, are not supported.
XPath math functions: math:sqrt, math:pow, math:log, math:sin, …¶
The trigonometric and exponential functions of XPath and XQuery Functions and Operators 3.1
(section 4.8) are SPARQL functions in
their standard namespace, PREFIX math: <http://www.w3.org/2005/xpath-functions/math#>:
Function |
Value |
|---|---|
|
π |
|
eˣ, 10ˣ |
|
the natural and the base 10 logarithm |
|
xʸ (also a negative x with an integer y) |
|
√x |
|
x in radians |
|
the angle in radians |
|
the angle of the point (x, y), in -π..π |
As the specification says, the arguments of any numeric datatype are cast to xsd:double, and the
result is an xsd:double that follows IEEE 754 (math:sqrt(-1) is NaN, math:log(0) is
-INF). An unbound argument, or one that is not a number, leaves the result unbound, as for the
other numeric functions of SPARQL. The apparent power of equipment from its active and reactive
power, and the current through a three-phase line from its power and voltage:
m = Model()
m.add_prefixes({"ex": EX, "math": "http://www.w3.org/2005/xpath-functions/math#"})
m.reads(f"""
@prefix ex: <{EX}> .
ex:line1 ex:p 30.0 ; ex:q 40.0 ; ex:kv 132.0 .
""", format="turtle")
print(m.query("""
SELECT ?s ?amps WHERE {
?l ex:p ?p ; ex:q ?q ; ex:kv ?kv .
BIND(math:sqrt(math:pow(?p, 2) + math:pow(?q, 2)) AS ?s) # MVA: 50.0
BIND(?s * 1000 / (math:sqrt(3) * ?kv) AS ?amps) # A: about 218.7
}"""))
The distance in kilometres between two points by the haversine formula:
BIND(math:pi() / 180 AS ?rad)
BIND(math:pow(math:sin((?lat2 - ?lat1) * ?rad / 2), 2)
+ math:cos(?lat1 * ?rad) * math:cos(?lat2 * ?rad)
* math:pow(math:sin((?lon2 - ?lon1) * ?rad / 2), 2) AS ?h)
BIND(2 * 6371 * math:atan2(math:sqrt(?h), math:sqrt(1 - ?h)) AS ?km)
Every example of the specification is a test in py_fastrdf/tests/test_xpath_math.py, with the
special cases of -0, INF and NaN.
Units of measure: QUDT and UCUM¶
fastrdf converts and combines quantities in two unit systems, with SPARQL functions in the
predefined fastrdf: namespace:
QUDT (qudt.org), the units ontology of RDF data. A quantity is a
qudt:QuantityValuewith aqudt:numericValueand aqudt:unit. Units are IRIs such asunit:FT(PREFIX unit: <http://qudt.org/vocab/unit/>). The 2,945 units of QUDT 3.5.4 are built in with their conversion multipliers and offsets, dimension vectors and quantity kinds, so the model doesn’t need to contain QUDT.UCUM (ucum.org), the unit codes of FHIR, SOSA/SSN and many data formats. Units are strings such as
"mm[Hg]","kg.m/s2"or"10*3/uL". Any UCUM expression is parsed and evaluated, not only a fixed list of codes.
Mixing units that don’t fit together never gives a number: the result is unbound, as for other SPARQL functions given values of the wrong type. That covers different dimensions (metres and seconds), unknown units, invalid UCUM, and the operations listed below.
Function |
Result |
|---|---|
|
|
|
the sum or difference, in |
|
-1, 0 or 1 |
|
the product or quotient, in |
|
whether two QUDT units can be converted into each other |
|
the IRI of the unit’s QUDT dimension vector |
|
the QUDT unit for a UCUM expression |
|
|
|
|
|
the product or quotient, in UCUM unit |
|
whether two UCUM units can be converted into each other |
|
whether a string is a valid UCUM expression |
|
the factor and UCUM base units, e.g. |
Values of any numeric datatype are read as xsd:double, and the numeric results are
xsd:double. Units are compared and converted once per distinct pair of units, then applied to
whole columns, so a conversion over millions of rows costs about as much as an arithmetic
expression.
Temperatures on the °C, °F and °Ré scales are converted with their offsets: 0 °C is 273.15 K. A sum, difference or comparison reads the values as points on their scale, so 20 °C minus 68 °F is 0. The operations that can’t give a definite answer are unbound instead:
sums of two such temperatures in different units (20 °C + 10 °F: is 10 °F a temperature or a difference?);
products and quotients with such a unit;
converting between currencies (QUDT’s currency multipliers are not exchange rates);
the 73 QUDT units that QUDT gives the conversion multiplier 0 because they have no linear conversion: decibels and nepers, pH, degrees Baumé and Brix, international units, and others. They count as unknown units.
Two QUDT units are commensurable when they have the same dimension vector. A dimensionless unit,
a counting unit, or a QUDT contextual unit must also share a quantity kind with the other, so that
percent doesn’t convert to radians. Products and quotients must land in a unit with the product
or quotient of the dimensions: multiplyQuantities(2, unit:N, 3, unit:M, unit:J) is 6, and with
unit:W it is unbound.
m = Model()
m.add_prefixes({"ex": EX, "qudt": "http://qudt.org/schema/qudt/",
"unit": "http://qudt.org/vocab/unit/"})
m.reads(f"""
@prefix ex: <{EX}> .
@prefix qudt: <http://qudt.org/schema/qudt/> .
@prefix unit: <http://qudt.org/vocab/unit/> .
ex:tank1 ex:temperature [ qudt:numericValue 20.0 ; qudt:unit unit:DEG_C ] ;
ex:height [ qudt:numericValue 12.0 ; qudt:unit unit:FT ] .
ex:tank2 ex:temperature [ qudt:numericValue 80.6 ; qudt:unit unit:DEG_F ] ;
ex:height [ qudt:numericValue 3.5 ; qudt:unit unit:M ] .
ex:tank3 ex:temperature [ qudt:numericValue 300 ; qudt:unit unit:K ] ;
ex:height [ qudt:numericValue 2.0 ; qudt:unit unit:KiloGM ] . # a mistake in the data
""", format="turtle")
# every temperature in °C, and the tanks below 25 °C whatever unit they were measured in
print(m.query("""
SELECT ?tank ?celsius WHERE {
?tank ex:temperature [ qudt:numericValue ?v ; qudt:unit ?u ] .
BIND(fastrdf:convertUnit(?v, ?u, unit:DEG_C) AS ?celsius)
FILTER(fastrdf:compareQuantities(?v, ?u, 25, unit:DEG_C) < 0)
}""")) # tank1: 20.0
# the total height in metres; the height in kilograms is unbound and left out of the sum
print(m.query("""
SELECT (SUM(fastrdf:convertUnit(?v, ?u, unit:M)) AS ?metres) WHERE {
?tank ex:height [ qudt:numericValue ?v ; qudt:unit ?u ] .
}""")) # 3.6576 + 3.5 = 7.1576
To find the data with units that don’t fit, ask where the conversion is unbound:
FILTER(!BOUND(fastrdf:convertUnit(?v, ?u, unit:M))), or
FILTER(!fastrdf:commensurableUnits(?u, unit:M)).
UCUM codes work the same way, as strings:
m = Model()
m.add_prefixes({"ex": EX, "unit": "http://qudt.org/vocab/unit/"})
m.reads(f"""
@prefix ex: <{EX}> .
ex:obs1 ex:value 120 ; ex:code "mm[Hg]" .
ex:obs2 ex:value 16.2 ; ex:code "kPa" .
ex:obs3 ex:value 5.4 ; ex:code "mmol/L" .
ex:obs4 ex:value 7 ; ex:code "mm Hg" .
""", format="turtle")
print(m.query("""
SELECT ?obs ?ok ?kpa ?unit WHERE {
?obs ex:value ?v ; ex:code ?c .
BIND(fastrdf:validUcum(?c) AS ?ok) # false for "mm Hg"
BIND(fastrdf:convertUcum(?v, ?c, "kPa") AS ?kpa) # 15.99864, 16.2, unbound, unbound
BIND(fastrdf:unitFromUcum(?c) AS ?unit) # unit:MilliM_HG, unit:KiloPA, ...
} ORDER BY ?obs"""))
UCUM is implemented as the specification defines it, read from the official ucum-essence.xml
(UCUM 2.2, shipped unmodified under the UCUM licence): the 24 prefixes and 312 atoms, exponents
(m2, s-1), . and /, parentheses, integer factors (4.s), powers of ten (10*-7), and
annotations ({cells}/uL, which count as 1).
Arbitrary units such as
[iU]convert only to the same arbitrary units, so[iU]/mLconverts to[iU]/Lbut not to[arb'U]/L.Special units on a non-ratio scale behave as follows.
Cel,[degF]and[degRe]convert with their offsets when they stand alone. The logarithmic ones (B,Np,[pH], …) convert only to themselves. No special unit can be part of a product (Cel/sis unbound).fastrdf:unitFromUcumfirst looks for a QUDT unit whosequdt:ucumCodeis the code. Otherwise it evaluates the expression and looks for a QUDT unit with the same dimension, multiplier and offset, so"s/m"and"m-1.s"both giveunit:SEC-PER-M. When several match, it prefers one that isn’t deprecated and has a UCUM code, then the shortest name; so"kg.m2/s2"givesunit:J, notunit:N-M.fastrdf:convertUcumToUnitconverts through SI. UCUM counts moles as a number (6.02214076e23), but the mole is mapped to QUDT’s amount of substance, so"mmol/L"converts tounit:MOL-PER-M3. UCUM keeps the radian as a dimension, while QUDT counts angles as dimensionless, so a UCUM angle converts only to a QUDT angle unit and"%"doesn’t convert tounit:RAD.
Not supported:
UCUM’s case-insensitive codes (
"MM[HG]");quantities as literals with a unit datatype (
"5 km"^^cdt:ucum);uncertainty;
user-defined units, since the QUDT table is built in.
The tests are:
the whole UCUM functional test suite: 529 validation cases, 30 conversions, 2 multiplications and 3 divisions, in
py_fastrdf/tests/test_units_ucum.py;NIST SP 811’s conversion factors, mapped to 96 QUDT units;
QUDT’s own consistency rules;
every
qudt:ucumCodeof QUDT converted into its own unit.
The last check agrees for 2,136 of QUDT’s UCUM codes. The qudt:ucumCodes that don’t agree are listed
in lib/units/conformance/qudt_ucum/known_differences.tsv. Some aren’t valid UCUM (VA,
ston_av), and some use different definitions, such as QUDT’s synodic month against UCUM’s mean
Julian month.
The path examples below use this graph: a chain a -> b -> c -> d and a shortcut a -> d with
cost on the nodes.
m.reads(f"""
@prefix ex: <{EX}> .
ex:a ex:next ex:b . ex:b ex:next ex:c . ex:c ex:next ex:d . ex:a ex:jump ex:d .
ex:b ex:cost 1 . ex:c ex:cost 1 . ex:d ex:cost 5 .
""", format="turtle")
Bounded paths: {n,m}¶
Any property path element can have bounds, as in Apache Jena: elt{n} (exactly n), elt{n,m},
elt{n,} (n or more) and elt{,m} (0 to m). Each pair of nodes is returned once.
print(m.query("SELECT ?o WHERE { ex:a ex:next{2,3} ?o }")) # c and d
print(m.query("SELECT ?o WHERE { ex:a (ex:next|ex:jump){1} ?o }")) # b and d
fastrdf:path¶
The magic predicate fastrdf:path (PREFIX fastrdf: <https://datatreehouse.github.io/fastrdf/vocab#>)
also returns the lengths, the paths and their nodes, and can rule out paths that revisit nodes.
Its subject is the start, and a blank node holds the options:
m.add_prefixes({"fastrdf": "https://datatreehouse.github.io/fastrdf/vocab#"})
print(m.query("""
SELECT ?o ?len WHERE {
ex:a fastrdf:path [
fastrdf:predicate ex:next, ex:jump ;
fastrdf:minLength 1 ;
fastrdf:maxLength 3 ;
fastrdf:object ?o ;
fastrdf:length ?len
]
} ORDER BY ?o ?len"""))
Option |
Value |
Default |
|---|---|---|
|
IRI, can repeat: steps from subject to object |
any predicate |
|
IRI, can repeat: steps from object to subject |
|
|
non-negative integers |
1, unbounded |
|
the end: a variable or a term |
|
|
variable: the number of steps |
|
|
|
|
|
|
|
|
variables: one row per node of each path |
Walks with fastrdf:length or path outputs need fastrdf:maxLength (or fastrdf:shortest true), as
a cycle gives walks of every length. To list the nodes of each path:
print(m.query("""
SELECT ?path ?i ?node WHERE {
ex:a fastrdf:path [
fastrdf:predicate ex:next, ex:jump ;
fastrdf:object ex:d ;
fastrdf:maxLength 3 ;
fastrdf:pathIndex ?path ; fastrdf:nodeIndex ?i ; fastrdf:pathNode ?node
]
} ORDER BY ?path ?i"""))
fastrdf:shortestPath¶
fastrdf:shortestPath finds the shortest (or cheapest) paths from sources to targets. Its subject
is the source, and the options go on a node:
print(m.query("""
SELECT ?target ?len ?nodes WHERE {
ex:a fastrdf:shortestPath ?p .
?p fastrdf:predicate ex:next, ex:jump ;
fastrdf:object ?target ;
fastrdf:length ?len ;
fastrdf:pathNodes ?nodes .
VALUES ?target { ex:d }
}""")) # 1 step, via ex:jump
print(m.query("""
SELECT ?cost ?nodes WHERE {
ex:a fastrdf:shortestPath ?p .
?p fastrdf:predicate ex:next, ex:jump ;
fastrdf:object ex:d ;
fastrdf:weight ex:cost ; # the cost of entering a node: Dijkstra
fastrdf:cost ?cost ;
fastrdf:kShortest 2 ;
fastrdf:pathNodes ?nodes .
}"""))
The other patterns of the group give the sources, the targets (fastrdf:object) and the nodes to
avoid (fastrdf:avoid), or they are constants. An unbound fastrdf:object makes every node reached
a target. FILTERs apply after the search, so put a target filter in a nested group or subquery.
Option |
|
|---|---|
|
the edges, followed forwards and backwards (give a predicate as both for undirected edges) |
|
follow every predicate with IRI or blank node objects (except |
|
the fewest (default 1) and most edges |
|
the number of nearest targets per source |
|
a numeric predicate giving the cost of entering a node, the cost of nodes without it (default 0), and the highest cost |
|
nodes that paths may start or end at, but not pass through |
|
the k shortest simple paths (Yen) |
|
all shortest paths, at most |
Outputs: fastrdf:length, fastrdf:cost, fastrdf:pathIndex, fastrdf:pathNodes (a JSON array of
the nodes), and, for one row per node, fastrdf:pathNode, fastrdf:nodeIndex,
fastrdf:stepPredicate and fastrdf:stepInverse.
Graph algorithms: fastrdf:component, fastrdf:bridge, fastrdf:articulationPoint¶
Three questions come up whenever a graph is a network (a power grid, a rail net, a supply chain, a dependency graph): which parts hang together, which single link would split them, and which single node would. fastrdf answers them with three magic predicates, so they are plain SPARQL that can be combined with any other pattern, and run without changing or copying the model:
Question |
Predicate |
Typical use |
|---|---|---|
Which nodes are connected? |
|
islands, switch-bounded areas, what is still supplied |
Which edges split their part when lost? |
|
lines without a backup, N-1 on lines |
Which nodes split their part when lost? |
|
single points of failure, N-1 on substations |
The examples use this small graph of ex:line edges: two triangles joined by c - d, a tail
f - g - h, and a separate pair x - y.
m = Model()
m.add_prefixes({"ex": EX, "fastrdf": "https://datatreehouse.github.io/fastrdf/vocab#"})
m.reads(f"""
@prefix ex: <{EX}> .
ex:a ex:line ex:b . ex:b ex:line ex:c . ex:c ex:line ex:a .
ex:c ex:line ex:d .
ex:d ex:line ex:e . ex:e ex:line ex:f . ex:f ex:line ex:d .
ex:f ex:line ex:g . ex:g ex:line ex:h .
ex:x ex:line ex:y .
""", format="turtle")
The figures are drawn from fastrdf’s own answers by docs/images/graph_algorithms_figures.py.
Connected components¶
fastrdf:component gives every node the number of its component (fastrdf:componentId, 1 for the
largest, then by decreasing size) and the component’s size. The edges are followed in both
directions:
print(m.query("""
SELECT ?node ?id ?size WHERE {
?node fastrdf:component ?c .
?c fastrdf:predicate ex:line ;
fastrdf:componentId ?id ;
fastrdf:componentSize ?size .
} ORDER BY ?id ?node""")) # a to h: 1, 8; x and y: 2, 2
The options are on a blank node or a variable (?c above); [ ... ] works as well. Every
predicate below takes the same edge options.
What-ifs: fastrdf:avoid¶
fastrdf:avoid takes nodes out of the graph, with their edges, for this query only. It is a what-if
(open switches, equipment out of service, a closed station) without changing the model. The avoided
nodes have no row:
print(m.query("""
SELECT ?node ?id WHERE {
?node fastrdf:component [
fastrdf:predicate ex:line ; fastrdf:avoid ex:d ; fastrdf:componentId ?id
]
} ORDER BY ?id ?node""")) # e, f, g, h: 1; a, b, c: 2; x, y: 3
fastrdf:avoid also takes a variable that the group binds, so the nodes to avoid can be found by a
query, e.g. every node marked as open. Put the patterns that find them in a subquery before the
magic predicate:
m.reads(f"@prefix ex: <{EX}> . ex:d ex:open true .", format="turtle")
print(m.query("""
SELECT ?node ?id WHERE {
{ SELECT ?open WHERE { ?open ex:open true } }
?node fastrdf:component [ fastrdf:predicate ex:line ; fastrdf:avoid ?open ; fastrdf:componentId ?id ]
} ORDER BY ?id ?node""")) # as above
Bridges¶
A bridge is an edge whose loss splits its component. ?a fastrdf:bridge ?o gives one row per
bridge, with fastrdf:object binding the other end and fastrdf:cutOff the number of nodes on the
smaller side, which is how much the loss would cut off:
print(m.query("""
SELECT ?a ?b ?cut WHERE {
?a fastrdf:bridge ?o .
?o fastrdf:object ?b ; fastrdf:predicate ex:line ; fastrdf:cutOff ?cut .
} ORDER BY DESC(?cut)""")) # c-d 3, f-g 2, g-h 1, x-y 1
The edges of the triangles are not bridges, as each has a way around it. Parallel edges are not
bridges either. fastrdf:edgePredicate gives the predicate of the bridge’s edge.
Articulation points¶
An articulation point is a node whose loss splits its component. fastrdf:cutOff is the number of
nodes no longer connected to the largest remaining part:
print(m.query("""
SELECT ?n ?cut WHERE {
?n fastrdf:articulationPoint [ fastrdf:predicate ex:line ; fastrdf:cutOff ?cut ]
} ORDER BY DESC(?cut)""")) # d 3, c 2, f 2, g 1
Losing c leaves a, b apart from d to h (2 cut off); losing d leaves a, b, c apart
from e to h (3 cut off).
Edges given by a query: fastrdf:edgeSource and fastrdf:edgeTarget¶
Often the edges of the network are not single triples. A power line connects the substations at its
two ends through terminals and connectivity nodes, for instance. fastrdf:edgeSource ?a ; fastrdf:edgeTarget ?b make one edge of every distinct solution of the patterns that bind ?a and
?b, so derived edges need no materialization. Put those patterns in a subquery:
m.reads(f"""
@prefix ex: <{EX}> .
ex:l1 ex:from ex:p ; ex:to ex:q .
ex:l2 ex:from ex:q ; ex:to ex:r .
ex:l3 ex:from ex:q ; ex:to ex:r .
""", format="turtle")
print(m.query("""
SELECT ?line ?a ?b ?cut WHERE {
{ SELECT ?line ?a ?b WHERE { ?line ex:from ?a ; ex:to ?b } }
?a fastrdf:bridge ?o .
?o fastrdf:object ?b ; fastrdf:edgeSource ?a ; fastrdf:edgeTarget ?b ; fastrdf:cutOff ?cut .
}""")) # l1 from p to q, cutting off 1; l2 and l3 are parallel, so neither is a bridge
The rows keep the other variables of the subquery (?line above), so a bridge comes back with the
line that makes it. A CIM grid’s substation graph, with each line between the substations of its
two terminals:
PREFIX cim: <http://iec.ch/TC57/CIM100#>
PREFIX fastrdf: <https://datatreehouse.github.io/fastrdf/vocab#>
SELECT ?line ?s1 ?s2 ?cut WHERE {
{ SELECT DISTINCT ?line ?s1 ?s2 WHERE {
?line a cim:ACLineSegment .
?t1 cim:Terminal.ConductingEquipment ?line ; cim:Terminal.ConnectivityNode ?n1 .
?t2 cim:Terminal.ConductingEquipment ?line ; cim:Terminal.ConnectivityNode ?n2 .
?n1 cim:ConnectivityNode.ConnectivityNodeContainer/cim:VoltageLevel.Substation ?s1 .
?n2 cim:ConnectivityNode.ConnectivityNodeContainer/cim:VoltageLevel.Substation ?s2 .
FILTER(STR(?s1) < STR(?s2)) # each line once
} }
?s1 fastrdf:bridge ?o .
?o fastrdf:object ?s2 ; fastrdf:edgeSource ?s1 ; fastrdf:edgeTarget ?s2 ; fastrdf:cutOff ?cut .
} ORDER BY DESC(?cut)
Every row is an edge, and two rows between the same nodes are parallel edges, which are never
bridges. A pattern that is symmetric in ?a and ?b (like the terminals above) gives each line
twice, once in each direction, so keep one direction with a filter such as
FILTER(STR(?s1) < STR(?s2)); two different lines between the same substations then stay
parallel, as they should. On the Nordic44 test grid this query gives 18 bridges.
The algorithms know nothing of CIM: the grid is only in the query, and the same predicates work on rail nets, pipelines or call graphs.
Counting only some nodes, restricting the rows, and strong components¶
fastrdf:countNodestakes nodes (a variable bound by the group, or constants) and makes only them count incomponentSizeandcutOff, e.g. the customers or substations cut off rather than every node of the graph.A subject bound by other patterns of the same block restricts the rows to those nodes. Nodes among them without edges are then components of their own.
fastrdf:strong truegives the strongly connected components of the directed edges, which is what a cycle check or a dependency analysis needs.
Predicate |
Rows |
Outputs |
|---|---|---|
|
one per node |
|
|
one per bridge (an edge whose loss splits its component), |
|
|
one per node whose loss splits its component |
|
The edge options are those of fastrdf:shortestPath (fastrdf:predicate, fastrdf:inversePredicate,
fastrdf:anyPredicate, fastrdf:excludePredicate) or fastrdf:edgeSource/fastrdf:edgeTarget;
fastrdf:avoid and fastrdf:countNodes take a variable bound by the group (or a subquery before
it) or constants.
Speed and pitfalls¶
The algorithms run on the cached integer graph of fastrdf:shortestPath: union-find for
components, Tarjan’s algorithms for strong components, bridges and articulation points, all
without recursion, so deep graphs do not overflow the stack. A grid of ten million triples answers
in well under a second.
Write the patterns that restrict the rows in the same block as the predicate, after a subquery of avoided nodes. A separate block before the subquery is joined with it first, which is a cross product.
Standards and compliance¶
No W3C or ISO standard defines these algorithms in a query language. SPARQL 1.1 and 1.2 have no graph
algorithms, and ISO GQL and SQL/PGQ leave them to vendor procedures. Other RDF stores also use their
own extensions, such as AnzoGraph’s connected components SERVICE. fastrdf therefore follows the textbook
definitions (a bridge or an articulation point is an edge or a node whose removal increases the
number of connected components) and is checked against them. The tests in
py_fastrdf/tests/test_graph_algorithms.py cover the cases above, and
py_fastrdf/tests/test_graph_algorithm_definitions.py checks fastrdf on random graphs against the
definitions themselves, by removing every edge and every node in turn. Connected components are also
checked against the validation graphs of the LDBC Graphalytics
benchmark, which defines weakly connected components with reference outputs
(py_fastrdf/tests/test_ldbc_graphalytics_wcc.py).
Full-text search: fastrdf:fts¶
Enable the index with IndexingOptions(fts=True) (or create_index), then search with the magic
predicate fastrdf:fts. Matching is case insensitive, with score 1.0 for a match of the whole
value and 0.75 for a substring match.
m = Model(indexing_options=IndexingOptions(fts=True))
m.read("data.ttl")
df = m.query("""
PREFIX fastrdf: <https://datatreehouse.github.io/fastrdf/vocab#>
SELECT ?subj ?p ?object ?score WHERE {
?subj fastrdf:fts ?fts .
?fts fastrdf:ftsQuery "breaker" ;
fastrdf:ftsLimit 10 ;
fastrdf:ftsObject ?object ;
fastrdf:ftsPredicate ?p ;
fastrdf:ftsScore ?score .
}""")
fastrdf:ftsUniqueSubject true returns each subject once. IndexingOptions(fts_predicates=[...])
limits the index to some predicates. fts_local_names=True also indexes the local names of
subject IRIs, matched with the predicate fastrdf:ftsLocalName, and fts_iris=True indexes IRIs in the
object position.
GeoSPARQL¶
With IndexingOptions(geo=True), geometry literals (geo:wktLiteral, geo:wkbLiteral,
geo:geoJSONLiteral) are indexed spatially, and the GeoSPARQL functions are available: the simple
features, Egenhofer and RCC8 relations, measurements with units, constructions and serializations,
across coordinate reference systems. Spatial filters and joins use the index. geof:relate, the
query rewrite extension and the aggregates are not supported yet.
m = Model(indexing_options=IndexingOptions(geo=True))
m.read("features.ttl")
df = m.query("""
PREFIX geo: <http://www.opengis.net/ont/geosparql#>
PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?l WHERE {
?f rdfs:label ?l ; geo:hasGeometry/geo:asWKT ?g .
FILTER(geof:sfWithin(?g, "POLYGON((1 1, 6 1, 6 6, 1 6, 1 1))"^^geo:wktLiteral))
}""")
10. Insert, update and federation¶
insert¶
insert(construct, ...) runs a CONSTRUCT query and adds the triples. It returns the newly added
triples (those not already there) as a dict from predicate IRI to DataFrame. Run the same string
with query first to see what would be added:
m = Model()
m.add_prefixes({"ex": EX})
m.reads(f"<{EX}hawaiian> <{EX}hasIngredient> <{EX}pineapple> .", format="ntriples")
controversial = "CONSTRUCT { ?p a ex:ControversialPizza } WHERE { ?p ex:hasIngredient ex:pineapple }"
print(m.query(controversial)[0]) # inspect
new = m.insert(controversial) # commit
print(list(new)) # ['http://www.w3.org/1999/02/22-rdf-syntax-ns#type']
print(m.insert(controversial)) # {}: nothing new
source_graph= is the graph the query reads, and target_graph= the graph the triples go to,
e.g. TRANSIENT_GRAPH. Triples from GRAPH blocks in the template go to their own graphs instead (see
CONSTRUCT with quads). solution_mappings=True returns SolutionMappings. include_graphs,
parameters, max_rows and debug work as for query.
update¶
update(sparql_update, ...) runs SPARQL 1.1 Update: INSERT DATA, DELETE DATA,
INSERT/DELETE ... WHERE, DELETE WHERE, CLEAR, DROP, ADD/COPY/MOVE and LOAD.
m.update("""
DELETE { ?p ex:hasIngredient ex:pineapple }
INSERT { ?p ex:hasIngredient ex:mango }
WHERE { ?p ex:hasIngredient ex:pineapple }
""")
m.update("INSERT DATA { GRAPH <urn:g> { ex:margherita a ex:Pizza } }")
m.update("INSERT { GRAPH ?g { ?p ex:inGraph true } } WHERE { GRAPH ?g { ?p a ex:Pizza } }")
print(m.query("SELECT ?p ?i WHERE { ?p ex:hasIngredient ?i }"))
graph=, include_graphs, parameters, max_rows and debug work as for query.
Federation: SERVICE and LOAD¶
set_federation(...) enables SPARQL 1.1 Federated Query (SERVICE) and LOAD for the queries and
updates of the model, and replaces earlier settings:
m.set_federation(
allowed_endpoints=["https://query.wikidata.org/sparql", "http://localhost:7878"], # by URL prefix
headers={"https://query.wikidata.org": {"User-Agent": "my-app/1.0"}},
timeout=60.0,
)
df = m.query("""
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
SELECT ?item ?label WHERE {
VALUES ?item { <http://www.wikidata.org/entity/Q20> }
SERVICE <https://query.wikidata.org/sparql> {
?item <http://www.w3.org/2000/01/rdf-schema#label> ?label FILTER(LANG(?label) = "en")
}
}""")
A SERVICE pattern runs after the local patterns of its group. The distinct values that the
local patterns bind for the shared variables are sent with it, as VALUES blocks of batch_size rows
(a bind join), so the endpoint only returns matching solutions. SERVICE SILENT gives an empty solution
when the endpoint fails, and SERVICE ?endpoint queries the endpoints the variable is bound to.
With allowed_endpoints=None (the default) any http(s) URL is allowed, and [] allows none.
Other settings: max_rows, concurrency, method ("POST" or "GET"), and bind_join=False to
join locally. arrow and arrow_batch_size control the Arrow format used with fastrdf endpoints.
LOAD <url> [INTO GRAPH <g>] reads an RDF file from an http(s) URL, object storage, or a file://
URL listed in allowed_endpoints. It needs allow_load=True:
import pathlib
pathlib.Path("extra.ttl").write_text(f"<{EX}x> <{EX}p> <{EX}y> .")
url = pathlib.Path("extra.ttl").resolve().as_uri()
m.set_federation(allowed_endpoints=[url], allow_load=True)
m.update(f"LOAD <{url}> INTO GRAPH <urn:loaded>")
print(m.size("urn:loaded")) # 1
11. User-defined functions and the query cache¶
add_udf and list_udfs¶
add_udf(iri, func, output_type, input_types=None) registers a Python function that SPARQL can
call by its IRI. The function gets a Polars DataFrame with one column per argument, named "0",
"1" and so on. It returns the DataFrame with an added output column, or a Series. output_type
is an RDFType or a datatype IRI:
from fastrdf import xsd, RDFType
def contains_abc(df: pl.DataFrame) -> pl.DataFrame:
return df.with_columns(pl.col("0").str.contains("abc").alias("out"))
def shout(df: pl.DataFrame) -> pl.Series:
return df["0"].str.to_uppercase() + "!"
m = Model()
m.reads(f'<{EX}a> <{EX}s> "xabcx" .\n<{EX}b> <{EX}s> "xyz" .', format="ntriples")
m.add_udf("urn:fastrdf:containsAbc", contains_abc, xsd.boolean, [xsd.string])
m.add_udf("urn:fastrdf:shout", shout, RDFType.Literal(xsd.string))
print(m.list_udfs())
print(m.query("""
SELECT ?x ?found ?loud WHERE {
?x <http://example.net/ns#s> ?s .
BIND(<urn:fastrdf:containsAbc>(?s) AS ?found)
BIND(<urn:fastrdf:shout>(?s) AS ?loud)
}"""))
The query cache¶
set_query_cache keeps the results of query (and of serve). A result is kept until a write
changes triples it can read: writes are tracked per graph and predicate, so a write elsewhere
keeps it. It is off by default.
from fastrdf import QueryCacheOptions
m.set_query_cache(QueryCacheOptions(max_entries=2048, ttl=None)) # or True for the defaults
q = "SELECT ?x WHERE { ?x <http://example.net/ns#s> ?s }"
m.query(q) # runs the query
m.query(q) # from the cache
print(m.query_cache_stats()["hits"]) # 1
print(m.get_query_cache().max_entries) # 2048
m.query(q, cache=False) # bypass it for one query
m.clear_query_cache() # drop the results, keep the options
m.set_query_cache(False) # turn it off
QueryCacheOptions(enabled=True, max_entries=1024, max_bytes=256 MiB, max_entry_bytes=16 MiB, ttl=None, min_run_time=0.0, cache_virtualized=False). Queries with parameters or debug, and
queries calling NOW(), RAND(), UUID(), STRUUID(), BNODE() or UDFs, are never cached.
Results over virtualized databases are only kept with cache_virtualized=True, and then a ttl
should be set.
12. Reasoning and validation¶
infer_rdfs¶
infer_rdfs(graph=None) applies the RDFS rules 2, 3, 5, 6, 7, 8, 9, 10 and 11 (domain, range,
subproperties and subclasses). The inferred triples go in the transient graph, so they can be
queried but are not written. It returns the number of inferred triples.
m = Model()
m.reads(f"""
@prefix ex: <{EX}> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
ex:Dog rdfs:subClassOf ex:Animal .
ex:owns rdfs:range ex:Thing .
ex:rex a ex:Dog .
ex:alice ex:owns ex:rex .
""", format="turtle")
print(m.infer_rdfs())
print(m.query("SELECT ?t WHERE { <http://example.net/ns#rex> a ?t }")) # Dog, Animal, Thing
Datalog: infer¶
infer(rulesets, graph=None, max_iterations=100_000, include_graphs=None, max_rows=100_000_000, debug=False) runs Datalog rules to a fixpoint and adds the inferred triples. With profile=
instead of rulesets, it runs a built-in reasoning profile, see the next section. A rule is
head :- body ., with triple patterns written [subject, predicate, object]:
rules = """
PREFIX ex: <http://example.net/ns#>
[?a, ex:ancestor, ?b] :- [?a, ex:parent, ?b] .
[?a, ex:ancestor, ?c] :- [?a, ex:parent, ?b], [?b, ex:ancestor, ?c] .
[?p, ex:category, "adult"] :- [?p, ex:age, ?age], FILTER(?age >= 18) .
"""
result = m.infer(rules) # also takes a list of rulesets
Bodies can use FILTER(...), BIND(expr AS ?v) and AGGREGATE(... ON ?group BIND SUM(?x) as ?s).
A ruleset can also consist of SPARQL CONSTRUCT queries, which are run as rules. Prefixes added with
add_prefixes are known in rules. debug=True reports rule bodies that give no triples.
Reasoning profiles: infer(profile=…)¶
infer(profile="owl-rl", graph=None, target_graph=None, include_graphs=None, max_violations=1000, max_rows=100_000_000) materializes the entailments of a built-in reasoning profile with the Datalog
engine. The schema (classes, properties, restrictions and lists) is compiled into rules, which run to
a fixpoint. The profiles are:
"owl-rl": the OWL 2 RL/RDF rules of OWL 2 Profiles: equality, property axioms (inverse, symmetric, transitive, functional, inverse functional, property chains, keys), class expressions (intersection, union, one of, some, all and has value, max (qualified) cardinality 1), class axioms and schema rules. The rules that concludefalseare checked after inference and reported as violations. Not included:x owl:sameAs xfor every term (eq-ref) and the datatype rules dt-type2, dt-eq, dt-diff and dt-not-type."rdfs-plus": a cheaper preset: domain, range, subproperties and subclasses, plusowl:inverseOf, symmetric and transitive properties,owl:equivalentClass,owl:equivalentProperty,owl:sameAsand functional and inverse functional properties. It adds no axiomatic or reflexive triples and checks nothing."rdfs": all the RDFS entailment rules of RDF 1.1 Semantics (rdfD2, rdfs1 to rdfs13) with the RDF and RDFS axiomatic triples, except rdfs4a, rdfs4b and the axiomatic triples that would make every term anrdfs:Resource.
Parameters:
graph: the graph to reason over, the default graph by default.target_graph: where the inferred triples go. By default the transient graph, so they can be queried but are not written. There is one transient graph, shared by all graphs and included in queries by default, so when you reason over several named graphs separately, give each its own target graph. PassDEFAULT_GRAPH(or the graph itself) to add the triples to it. Triples that are already in the graph are not added again.include_graphs: graphs read along with the graph, as with FROM.Noneincludes the transient graph,[]reads only the graph itself and the target graph.max_violations: the most violations reported per rule;0skips the consistency checks.max_rows: the most estimated rows in the result of a rule, to avoid running out of memory.
It returns a ReasoningResult with profile, inferred_triples, consistent, violations (a
list of dicts with rule, message and nodes), violations_truncated, rounds, rules,
rule_executions and seconds.
m = Model()
m.reads("""
@prefix ex: <http://example.org/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
ex:partOf a owl:TransitiveProperty ; owl:inverseOf ex:hasPart .
ex:Breaker owl:disjointWith ex:Transformer .
ex:bay1 ex:partOf ex:substation1 . ex:substation1 ex:partOf ex:region1 .
ex:b1 a ex:Breaker, ex:Transformer .
""", format="turtle")
res = m.infer(profile="owl-rl")
print(res.inferred_triples, res.consistent) # consistent is False
for v in res.violations:
print(v["rule"], v["message"]) # cax-dw: ex:b1 is an instance of the disjoint classes ...
print(m.query("SELECT ?x WHERE { <http://example.org/region1> <http://example.org/hasPart> ?x }"))
# bay1 and substation1, through transitivity and the inverse property
Choosing between them: infer_rdfs runs the RDFS rules once each,
in order, as SPARQL inserts, which is fast and enough for typical class and property hierarchies.
infer(profile="rdfs") computes the complete RDFS closure (for example, types from domains of
subproperties found late), with the axiomatic triples, on the Datalog engine. infer(profile="rdfs-plus")
adds the common OWL property axioms and equality without the cost of axiomatic triples or checks;
use it for inverse and transitive properties in models such as CIM. Use infer(profile="owl-rl") for
class expressions, property chains, keys and consistency checks.
Inferring or asserting owl:sameAs is costly for large groups of equal resources, because the
triples of every member are copied to the others.
SHACL: validate¶
validate(...) validates a graph against SHACL Core and SHACL-SPARQL shapes, evaluating shapes in
parallel, and runs SHACL rules (sh:rule):
m = Model()
m.reads("""
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix ex: <http://example.org/> .
ex:PersonShape a sh:NodeShape ; sh:targetClass ex:Person ;
sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:message "Missing name"@en ] .
""", format="turtle", graph="urn:shapes")
m.reads("@prefix ex: <http://example.org/> . ex:alice a ex:Person .", format="turtle")
report = m.validate(shape_graph="urn:shapes", report_graph="urn:report")
print(report.conforms) # False
print(report.results()) # one row per result; message is a list of strings
print(report.shape_targets) # targets per shape and constraint
print(report.performance)
Options: data_graph, report_graph ("" (the default) writes no report graph, None writes it
to the default graph), inferences_graph (for sh:rule results, otherwise the transient graph),
include_details=True (then report.details()), include_conforms, only_shapes /
deactivate_shapes, dry_run (only find the targets), max_rows, serial, max_iterations and
debug_rules (with report.rule_log).
A rule runs again when a predicate that its WHERE clause or its targets read has new triples,
until no rule infers a new triple. A rule with a blank node in its CONSTRUCT template, or with
BNODE() in its WHERE clause, makes one blank node per solution, and when it runs again only
for the solutions that are new, e.g. the focus nodes that another rule added to its target class.
Such a rule does not reach a fixpoint when it reads what it writes, as in
CONSTRUCT { $this ex:part _:p . _:p a ex:Item } WHERE { $this a ex:Item }: every execution has
new solutions. Give it sh:runOnce true, or it runs until max_iterations (the number of rule
executions, 100,000 by default).
13. Virtualization¶
Virtualization leaves large time series in the database that holds them. The graph describes the time series, and the parts of a SPARQL query that read their data points are translated to the database’s query language. Filters, grouping and ordering are pushed down where possible.
VirtualizedDatabase and add_virtualization¶
Each time series in the graph has fastrdf:hasResource (the name of a resource) and
fastrdf:hasExternalId (its id in the database). A resource has a template describing its
rows, which must have an id parameter:
from fastrdf import Model, VirtualizedDatabase, Template, Parameter, Variable, RDFType, Triple, Prefix, xsd
from fastrdf.virtualization import DuckDBDatabase
vocab = Prefix("https://datatreehouse.github.io/fastrdf/vocab#")
ex = Prefix("http://example.net/ns#")
id_, ts, value, dp = Variable("id"), Variable("timestamp"), Variable("value"), Variable("dp")
readings = Template(
iri=ex.suf("readings"),
parameters=[
Parameter(id_, rdf_type=RDFType.Literal(xsd.string)),
Parameter(ts, rdf_type=RDFType.Literal(xsd.dateTime)),
Parameter(value, rdf_type=RDFType.Literal(xsd.double)),
],
instances=[
Triple(id_, vocab.suf("hasDataPoint"), dp), # name the data point with a variable, not a blank node
Triple(dp, vocab.suf("hasValue"), value),
Triple(dp, vocab.suf("hasTimestamp"), ts),
],
)
vdb = VirtualizedDatabase(
DuckDBDatabase(database="readings.duckdb"),
resource_sql_map={"readings": "SELECT sensor_id AS id, ts AS timestamp, value FROM readings"},
)
m = Model()
m.reads("""
@prefix fastrdf: <https://datatreehouse.github.io/fastrdf/vocab#> .
@prefix ex: <http://example.net/ns#> .
ex:pump1 ex:hasSensor ex:s1 . ex:s1 fastrdf:hasTimeseries ex:ts1 .
ex:ts1 fastrdf:hasResource "readings" ; fastrdf:hasExternalId "sensor-1" .
""", format="turtle")
m.add_virtualization(vdb, resources={"readings": readings})
df = m.query("""
PREFIX fastrdf: <https://datatreehouse.github.io/fastrdf/vocab#>
PREFIX ex: <http://example.net/ns#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
SELECT ?pump (AVG(?v) AS ?avg) WHERE {
?pump ex:hasSensor/fastrdf:hasTimeseries ?t .
?t fastrdf:hasDataPoint ?p . ?p fastrdf:hasTimestamp ?at ; fastrdf:hasValue ?v .
FILTER(?at >= "2024-01-01T00:00:00Z"^^xsd:dateTime)
} GROUP BY ?pump""")
VirtualizedDatabase(database, resource_sql_map=None, sql_dialect=None, pushdowns=None): any object with aquery(sql) -> pl.DataFramemethod works as the database, given asql_dialect("duckdb","postgres","snowflake","bigquery","databricks"or anSQLDialect). The SQL of a resource can be a string, an SQLAlchemyTableorSelect. Withoutresource_sql_map, thequerymethod gets theVirtualizedQueryitself (fastrdf.vq) to translate.pushdownschooses among"value_conditions","group_by"and"ordering".add_virtualizationcan be called several times to query several databases together. Joins between time series are only pushed down within one database.VirtualizedDatabase.Cognite(client, resource_cognite_map=None)reads time series from Cognite Data Fusion.
fastrdf.virtualization¶
Ready-made databases, which know their dialect: DuckDBDatabase, SnowflakeDatabase,
BigQueryDatabase, DatabricksDatabase, TimescaleDatabase, InfluxDBDatabase (InfluxDB 3, SQL),
InfluxDB2Database (InfluxDB 2 / 1.8, Flux; resources are measurements),
FabricLakehouseDatabase, FabricDatabase (Fabric Warehouse, T-SQL) and KustoDatabase (Azure
Data Explorer and Fabric Eventhouses; resources are KQL expressions). SQLDatabase is the base class
for your own. The dialect classes (PostgresDialect, DuckDBDialect, SnowflakeDialect, …),
translate_sql and translate_kql let you customise or inspect the generated queries.
fastrdf.opcua.OPCUAHistoryDatabase(endpoint, ...) reads OPC UA Historical Access, with node ids
such as ns=2;s=ts1 as external ids.
from fastrdf.virtualization import SnowflakeDatabase
from fastrdf.opcua import OPCUAHistoryDatabase
snow = VirtualizedDatabase(
SnowflakeDatabase(account="...", user="...", warehouse="...", database="...", schema="..."),
resource_sql_map={"readings": "SELECT sensor_id AS id, ts AS timestamp, value FROM readings"},
)
opcua = VirtualizedDatabase(database=OPCUAHistoryDatabase("opc.tcp://plant:4840/"))
m.add_virtualization(snow, resources={"readings": readings})
m.add_virtualization(opcua, resources={"history": readings})
CIM time series: m.cim¶
The time series of a CIM grid can stay in the database and be queried with CIM predicates only.
m.cim has the templates that the Model portal’s Connect page uses for CIM:
Template |
Measurement class |
Values (from the measurement, then the value) |
Value datatype |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Every value also has cim:MeasurementValue.timeStamp. The resources (their names, their SQL and
the database) are your deployment’s, so you name them and register them yourself:
Annotate the measurements that have values in the database with
m.cim.add_measurement_timeseries(df, resource=...).dfhas the IRI of each measurement in the columnmeasurement, and its id in the database inexternalId. This addsfastrdf:hasResourceandfastrdf:hasExternalIdto each measurement. Instead ofresource=,dfcan have aresourcecolumn.Make a
VirtualizedDatabasewhoseresource_sql_mapgives, for each resource name, an SQL query with the columnsid(the external id),timestampandvalue.Call
m.add_virtualization(vdb, resources={...})with the template of each resource.
The graph here stands in for your own CIM, e.g. m.read("grid_EQ.xml", format="cim/xml"), and
the DuckDB tables for your own database, e.g. DuckDBDatabase(database="scada.duckdb"):
import duckdb
import polars as pl
from fastrdf import Model, VirtualizedDatabase
from fastrdf.virtualization import DuckDBDatabase
m = Model()
m.reads("""
@prefix cim: <http://iec.ch/TC57/CIM100#> .
@prefix ex: <http://example.org/grid#> .
ex:p1 a cim:Analog ; cim:IdentifiedObject.name "Line 1 P" .
ex:p2 a cim:Analog ; cim:IdentifiedObject.name "Line 2 P" .
ex:b1 a cim:Discrete ; cim:IdentifiedObject.name "Breaker 1 position" .
""", format="turtle")
con = duckdb.connect()
con.execute("""
CREATE TABLE analogs AS SELECT * FROM (VALUES
('P-1', TIMESTAMPTZ '2024-01-01 00:00:00+00', 12.5::DOUBLE), ('P-1', TIMESTAMPTZ '2024-01-01 01:00:00+00', 14.0::DOUBLE),
('P-2', TIMESTAMPTZ '2024-01-01 00:00:00+00', 30.0::DOUBLE), ('P-2', TIMESTAMPTZ '2024-01-01 01:00:00+00', 31.5::DOUBLE)
) AS t(tag, ts, val);
CREATE TABLE switches AS SELECT * FROM (VALUES
('B-1', TIMESTAMPTZ '2024-01-01 00:00:00+00', 1), ('B-1', TIMESTAMPTZ '2024-01-01 00:30:00+00', 0)
) AS t(tag, ts, val);
""")
# 1. which measurement is which time series of which resource
m.cim.add_measurement_timeseries(
pl.DataFrame({"measurement": ["http://example.org/grid#p1", "http://example.org/grid#p2"],
"externalId": ["P-1", "P-2"]}),
resource="scada_analogs",
)
m.cim.add_measurement_timeseries(
pl.DataFrame({"measurement": ["http://example.org/grid#b1"], "externalId": ["B-1"]}),
resource="scada_breakers",
)
# 2. the SQL of each resource, with the columns id, timestamp and value
vdb = VirtualizedDatabase(
DuckDBDatabase(connection=con),
resource_sql_map={
"scada_analogs": 'SELECT tag AS id, ts AS "timestamp", val AS value FROM analogs',
"scada_breakers": 'SELECT tag AS id, ts AS "timestamp", val AS value FROM switches',
},
)
# 3. the template of each resource
m.add_virtualization(vdb, resources={
"scada_analogs": m.cim.measurement_template("analog", "scada_analogs"),
"scada_breakers": m.cim.measurement_template("discrete", "scada_breakers"),
})
df = m.query("""
PREFIX cim: <http://iec.ch/TC57/CIM100#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
SELECT ?name (AVG(?v) AS ?avg) WHERE {
?a a cim:Analog ; cim:IdentifiedObject.name ?name ; cim:Analog.AnalogValues ?p .
?p cim:MeasurementValue.timeStamp ?t ; cim:AnalogValue.value ?v .
FILTER(?t >= "2024-01-01T00:00:00Z"^^xsd:dateTime)
} GROUP BY ?name ORDER BY ?name""")
# Line 1 P: 13.25, Line 2 P: 30.75. The filter and the average run in DuckDB.
When one database holds several kinds, include the class of the measurement in the query
(?a a cim:Analog). Without it, chrontext also asks the other kinds’ resources for the values.
Meter readings (IEC 61968-9 Metering) work the same way:
m.cim.add_meter_reading_timeseries(df, resource=...)adds acim:MeterReadingof each meter, with acim:IntervalBlockof a reading type whose interval readings are in the database. Its columns aremeterReading,meter,intervalBlock,readingTypeandexternalId.m.cim.meter_readings_template(resource)is the template of the resource.m.cim.add_meter_readings_shapes(resource, graph=...)adds SHACL shapes that check the annotations.
add_virtualization can be called again, for example for the meter readings in the same DuckDB:
con.execute("""
CREATE TABLE readings AS SELECT * FROM (VALUES
('M-1/energy', TIMESTAMPTZ '2024-01-01 00:00:00+00', 1.5::DOUBLE), ('M-1/energy', TIMESTAMPTZ '2024-01-01 00:15:00+00', 2.5::DOUBLE)
) AS t(block, ts, kwh);
""")
m.reads("""
@prefix cim: <http://iec.ch/TC57/CIM100#> .
@prefix ex: <http://example.org/grid#> .
ex:meter1 a cim:Meter ; cim:IdentifiedObject.name "M-1" .
ex:energy a cim:ReadingType .
""", format="turtle")
m.cim.add_meter_reading_timeseries(pl.DataFrame({
"meterReading": ["http://example.org/grid#mr1"], "meter": ["http://example.org/grid#meter1"],
"intervalBlock": ["http://example.org/grid#ib1"], "readingType": ["http://example.org/grid#energy"],
"externalId": ["M-1/energy"],
}), resource="ami_readings")
m.add_virtualization(
VirtualizedDatabase(
DuckDBDatabase(connection=con),
resource_sql_map={"ami_readings": 'SELECT block AS id, ts AS "timestamp", kwh AS value FROM readings'},
),
resources={"ami_readings": m.cim.meter_readings_template("ami_readings")},
)
df = m.query("""
PREFIX cim: <http://iec.ch/TC57/CIM100#>
SELECT ?meter (SUM(?v) AS ?kwh) WHERE {
?mr cim:MeterReading.Meter/cim:IdentifiedObject.name ?meter .
?ib a cim:IntervalBlock ; cim:IntervalBlock.MeterReading ?mr ; cim:IntervalBlock.IntervalReadings ?ir .
?ir cim:BaseReading.value ?v .
} GROUP BY ?meter""")
# M-1: 4.0
Events: earth faults, meter events and others¶
Events are virtualized the same way: each row of the SQL is an event of a meter, a line or other
equipment, with a timestamp and fields. m.cim has the templates of the CIM events:
Template |
From the source (the ids) |
Event fields |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
any CIM predicate, e.g. |
any, e.g. |
The SQL of a resource has the columns id, timestamp and one per field, named as the field.
The kind of a fault and the type of a meter event are IRIs, which the SQL gives as strings.
m.cim.add_event_timeseries(df, resource=...) links the sources (the column source) to their
ids in the database (externalId). For example, earth faults followed within a minute by a meter
losing power, in the DuckDB and with the meter from above:
con.execute("""
CREATE TABLE faults AS SELECT * FROM (VALUES
('L-1', TIMESTAMPTZ '2024-01-01 00:09:58+00', 'lineToGround', 1.2::DOUBLE),
('L-1', TIMESTAMPTZ '2024-02-01 10:00:00+00', 'lineToLine', 3.4::DOUBLE)
) AS t(line, ts, kind, km);
CREATE TABLE meter_events AS SELECT * FROM (VALUES
('M-1', TIMESTAMPTZ '2024-01-01 00:10:00+00', '3.26.38.185', 'power off'),
('M-1', TIMESTAMPTZ '2024-01-01 00:40:00+00', '3.26.38.216', 'power restored')
) AS t(meter, ts, code, reason);
""")
m.reads("""
@prefix cim: <http://iec.ch/TC57/CIM100#> .
@prefix ex: <http://example.org/grid#> .
ex:line1 a cim:ACLineSegment ; cim:IdentifiedObject.name "Line 1" .
ex:EndDeviceEventType.3.26.38.185 a cim:EndDeviceEventType ; cim:IdentifiedObject.name "Power off" .
""", format="turtle")
m.cim.add_event_timeseries(pl.DataFrame({"source": ["http://example.org/grid#line1"], "externalId": ["L-1"]}),
resource="scada_faults")
m.cim.add_event_timeseries(pl.DataFrame({"source": ["http://example.org/grid#meter1"], "externalId": ["M-1"]}),
resource="ami_events")
m.add_virtualization(
VirtualizedDatabase(
DuckDBDatabase(connection=con),
resource_sql_map={
"scada_faults": """SELECT line AS id, ts AS "timestamp",
'http://iec.ch/TC57/CIM100#PhaseConnectedFaultKind.' || kind AS kind, km AS distance FROM faults""",
"ami_events": """SELECT meter AS id, ts AS "timestamp",
'http://example.org/grid#EndDeviceEventType.' || code AS event_type, reason FROM meter_events""",
},
),
resources={
"scada_faults": m.cim.fault_template("scada_faults", fields=["kind", "distance"], on="line"),
"ami_events": m.cim.end_device_event_template("ami_events", fields=["event_type", "reason"]),
},
)
df = m.query("""
PREFIX cim: <http://iec.ch/TC57/CIM100#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
SELECT ?line ?km ?meter ?typename WHERE {
?l a cim:ACLineSegment ; cim:IdentifiedObject.name ?line ; cim:ACLineSegment.LineFaults ?f .
?f cim:Fault.occurredDateTime ?tf ; cim:Fault.kind cim:PhaseConnectedFaultKind.lineToGround ;
cim:LineFault.lengthFromTerminal1 ?km .
?m a cim:Meter ; cim:IdentifiedObject.name ?meter ; cim:EndDevice.EndDeviceEvents ?e .
?e cim:ActivityRecord.createdDateTime ?te ; cim:EndDeviceEvent.EndDeviceEventType ?type .
?type cim:IdentifiedObject.name ?typename .
FILTER(?te >= ?tf && ?te <= ?tf + "PT1M"^^xsd:dayTimeDuration)
}""")
# Line 1, 1.2 km, M-1, Power off. The kind of fault is a condition in the SQL, and the name of
# the event type is found in the graph for the type IRIs from the database.
Use xsd:dayTimeDuration for time arithmetic: fastrdf adds no xsd:duration to a date and time.
Industrial sources: map_cdf, map_osipi, map_pi_points, map_insights_hub and fastrdf.ip21¶
These read a source’s own asset model into the graph and virtualize its time series in one call. Their docstrings describe the vocabulary each one produces.
from cognite.client import CogniteClient
m.map_cdf(CogniteClient(), data_models=[("my_space", "MyModel", "v1")]) # Cognite Data Fusion
m.map_osipi("https://myserver/piwebapi", asset_database="\\\\MyAFServer\\MyDatabase",
username="me", password="...") # PI Asset Framework
m.map_pi_points("https://myserver/piwebapi", data_server="MyPIServer", name_filter="FIC*",
username="me", password="...") # PI Data Archive tags
m.map_insights_hub("gateway.eu1.mindsphere.io", "mytenant",
client_id="mytenant-svc", client_secret="...") # Siemens Insights Hub
from fastrdf.ip21 import map_ip21
map_ip21(m, "https://ip21server/ProcessData/AtProcessDataREST.dll", "IP21",
tag_filter="FIC*", default_start_time="2024-01-01T00:00:00Z") # AspenTech IP.21
Their data points are queried like any other virtualized time series:
df = m.query("""
PREFIX osipi: <urn:fastrdf_osipi:>
PREFIX fastrdf: <https://datatreehouse.github.io/fastrdf/vocab#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
SELECT ?tag ?bucket (AVG(?v) AS ?avg) WHERE {
?p a osipi:Point ; osipi:name ?tag ; fastrdf:hasDataPoint ?dp .
?dp fastrdf:hasTimestamp ?t ; fastrdf:hasValue ?v .
BIND(fastrdf:FloorDateTimeToSecondsInterval(?t, 3600) AS ?bucket)
FILTER(?t >= "2024-01-01T00:00:00Z"^^xsd:dateTime && ?t < "2024-01-02T00:00:00Z"^^xsd:dateTime)
} GROUP BY ?tag ?bucket""")
Grouping by fastrdf:FloorDateTimeToSecondsInterval with MIN, MAX, SUM, COUNT or AVG is read
from the source’s own aggregates where it has them. A query without a lower bound on the timestamp
fails unless default_start_time is set.
14. Configuration, serving and model management¶
fastrdf.config¶
fastrdf.config keeps a model’s configuration as triples in its own named graph,
fastrdf.config.CONFIG_GRAPH, so the configuration is written, serialized and served with the model.
apply_config(m) applies it: it creates the indexes, sets the query cache and connects the
virtualizations. Secrets are never stored: a secret names the environment variable that holds it.
CONFIG_GRAPH.md documents the vocabulary.
from fastrdf.config import (
CONFIG_GRAPH, IndexingConfig, QueryCacheConfig,
write_indexing, read_indexing, write_query_cache, read_query_cache, remove_query_cache,
apply_query_cache, apply_config,
)
m = Model()
write_query_cache(m, QueryCacheConfig(max_entries=2048, ttl=300.0))
write_indexing(m, IndexingConfig(object_sort_some=["http://example.net/ns#serialNumber"]))
print(read_query_cache(m), read_indexing(m))
m.write("model.trig", format="trig") # the config graph is in the file
m2 = Model()
m2.read("model.trig")
apply_config(m2) # sets the cache and creates the indexes
print(m2.get_query_cache().max_entries) # 2048
Virtualizations are configured the same way:
from fastrdf.config import VirtualizationConfig, VirtualizationResource, write_virtualization, read_virtualizations
write_virtualization(m, VirtualizationConfig(
iri="urn:fastrdf:config:virtualization:readings",
database="snowflake", # one of fastrdf.config.DATABASES
parameters={"account": "acme", "user": "fastrdf", "warehouse": "wh", "database": "meters", "schema": "public"},
secrets={"password": "SNOWFLAKE_PASSWORD"}, # read from the environment by apply_config
resources=[VirtualizationResource(
name="readings",
sql="SELECT id, ts AS timestamp, value FROM readings",
template=READINGS_TEMPLATE, # a stOTTR document or a template IRI
properties={"http://iec.ch/TC57/2013/CIM-schema-cim16#Measurement.unitSymbol":
"http://iec.ch/TC57/2013/CIM-schema-cim16#UnitSymbol.W"},
)],
))
applied = apply_config(m) # apply_config(m, environ={...}) for other secret sources
Other functions: remove_virtualization, read_virtualizations, apply_virtualization,
apply_properties (writes the static resource properties without connecting) and probe(config),
which checks a configuration against the database without changing a model.
serve¶
serve(...) serves the live model over the SPARQL 1.1 Protocol (/sparql, /query, /update,
/store), the Arrow API over HTTP (/arrow/...) and Arrow Flight, in the background. Queries see
changes made from Python, and the other way round.
import pyarrow.flight
server = m.serve(port=7878, flight_port=7879, allow_update=True, auth_token="secret")
print(server.url) # http://127.0.0.1:7878/sparql
df = Model().query("SELECT * WHERE { ?s ?p ?o } LIMIT 5", endpoint=server.url, endpoint_token="secret")
client = pyarrow.flight.connect(server.flight_url)
server.stop()
with m.serve(port=0, flight_port=None) as server: # stops on exit
...
Options include host (use "0.0.0.0" with auth_token), cors_origins, graph and
include_graphs, max_rows, max_request_bytes, arrow_compression, query_log_size (served at
GET /query-log), static_dir/static_path/static_vars for a web app, query_cache,
service_endpoints and allow_load (SERVICE and LOAD are refused unless listed), and block=True.
explore¶
explore() runs the Model portal, a browser UI for browsing, searching and querying the model.
server = m.explore(port=8000)
print(server.url) # open it in a browser
print(server.sparql_url) # the portal's SPARQL endpoint
server.stop()
The module-level fastrdf.explore(m, ...) is deprecated; use m.explore().
Indexes and compaction¶
from fastrdf import IndexingOptions, IRI
m = Model()
m.reads(f'<{EX}a> <{EX}serialNumber> "123" .', format="ntriples")
m.create_index(IndexingOptions(object_sort_some=[IRI(EX + "serialNumber")]))
m.compact() # merge the segments that accumulate from repeated additions
create_index sets the indexing options and builds the indexes for the triples already in the
model, dropping object indexes that are no longer chosen. Full-text and geo indexes are.
compact merges the stored segments of each predicate into one sorted segment. serialize
also compacts the model.
Introspection¶
print(m.size()) # triples in the default graph
print(m.list_udfs(), len(m.get_templates()))
print(fastrdf.__version__)
The predicates of a graph and their triples are found with SPARQL, or summarised by
describe.
Describing a model: describe¶
describe summarises what is in each graph of a model: its predicates with the types of their
objects and the number of distinct subjects and objects, its classes with their number of
instances, and the namespaces of its predicates and classes. Printing the result gives a report
of tables; the same content is in DataFrames.
m = Model()
m.reads(f"""
@prefix ex: <{EX}> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
ex:p1 a ex:Pump ; rdfs:label "Feed pump"@en, "Matepumpe"@nb ; ex:powerKW 7.5 ; ex:site ex:n1 .
ex:p2 a ex:Pump ; rdfs:label "Booster" ; ex:powerKW 11 ; ex:site ex:n1 .
ex:p3 a ex:Pump ; rdfs:label "Spare" ; ex:site ex:s2 .
ex:n1 a ex:Site ; rdfs:label "North" .
""", format="turtle")
m.reads(f"<{EX}s2> a <{EX}Site> .", format="turtle", graph="urn:graph:sites")
d = m.describe()
print(d)
# 2 graphs, 15 triples
#
# graph triples predicates classes
# ----------------- ------- ---------- -------
# default graph 14 4 2
# <urn:graph:sites> 1 1 1
#
# default graph
# =============
#
# Namespaces (3)
# prefix namespace predicates classes
# ------ ------------------------------------------- ---------- -------
# ns http://example.net/ns# 2 2
# rdf http://www.w3.org/1999/02/22-rdf-syntax-ns# 1
# rdfs http://www.w3.org/2000/01/rdf-schema# 1
#
# Classes (2)
# class instances
# ------- ---------
# ns:Pump 3
# ns:Site 1
#
# Predicates (4)
# predicate triples subjects objects object types notes
# ---------- ------- -------- ------- ---------------------------------- ----------
# rdfs:label 5 ~4 ~5 xsd:string (3), rdf:langString (2)
# rdf:type 4 4 2 IRI functional
# ns:site 3 3 2 IRI functional
# ns:powerKW 2 ~2 ~2 xsd:decimal (1), xsd:integer (1)
#
# <urn:graph:sites>
# =================
# ...
d.graphs # graph, triples, predicates, classes, namespaces, ...
d.predicates # graph, predicate, triples, distinct_subjects, distinct_objects, exact, object_types, ...
d.classes # graph, class, instances
d.namespaces # graph, namespace, prefix, role, terms
In the DataFrames the default graph is None and IRIs are written in full. The report writes
them with prefixes: fastrdf’s well-known ones (well_known_prefixes()), and for the other
namespaces of predicates and classes a prefix made from the namespace (ns above), which the
Namespaces table lists. In the notes, functional is a predicate with at most one object per
subject, and key one that also has at most one subject per object.
This default summary is made from the statistics the model keeps (see analyze) and one count per
class, so it is quick on large models. A predicate whose objects have several types, or whose
subjects are both IRIs and blank nodes, is stored as several tables, and its distinct counts are
then the sum over its tables: an upper bound, marked with ~ in the report and exact = False in
the DataFrame. exact=True counts them, with one query per graph.
graphs=[None, "urn:graph:sites"] describes only those graphs.
sections adds parts that read the triples of the described graphs, so ask for the ones you need,
or for "all":
Section |
Content |
DataFrame |
|---|---|---|
|
distinct subjects per graph, those without a type, blank nodes |
|
|
for each class, the predicates of its instances: the share of instances that have it, the fewest and most objects per instance |
|
|
which classes are linked by which predicates |
|
|
least and greatest value per predicate and datatype, the lengths of strings, the languages of language-tagged strings |
|
|
an example object per predicate |
|
|
per predicate, the IRI objects that are not a subject in the graph, and how many of them are subjects in another graph |
|
|
for pairs of the six largest graphs: shared subjects, predicates and classes, and the IRI objects of one that are subjects in the other |
|
|
whether each predicate and class is declared in some graph of the model ( |
|
|
the namespaces of the IRIs that are subjects and objects |
|
d = m.describe(sections=["subjects", "class_predicates", "links", "literals", "dangling"], exact=True)
print(d.show_class("ns:Pump"))
# ns:Pump in default graph: 3 instances
# =====================================
# predicate coverage per instance
# ---------- -------- ------------
# ns:site 100.0% 1..1
# rdfs:label 100.0% 1..2
# ns:powerKW 66.7% 0..1
#
# Links
# subject class predicate object class triples
# ------------- --------- ------------ -------
# ns:Pump ns:site ns:Site 2
print(d.show_predicate("rdfs:label"))
# rdfs:label in default graph
# ===========================
# predicate triples subjects objects object types
# ---------- ------- -------- ------- ----------------------------------
# rdfs:label 5 4 5 xsd:string (3), rdf:langString (2)
# At most 2 per subject and 1 per object.
#
# Literals
# datatype length languages
# -------------- ------ --------------
# rdf:langString 9..9 nb (1), en (1)
# xsd:string 5..7
#
# Classes with it
# class instances coverage per instance
# ------- --------- -------- ------------
# ns:Pump 3 100.0% 1..2
# ns:Site 1 100.0% 1..1
print(d.to_text(graphs=[None], sections=["literals", "dangling"]))
# 2 graphs, 15 triples
#
# graph triples predicates classes subjects untyped blank
# ----------------- ------- ---------- ------- -------- ------- -----
# default graph 14 4 2 4 0 0
# <urn:graph:sites> 1 1 1 1 0 0
#
# default graph
# =============
#
# Literals (4)
# predicate datatype min max length languages
# ---------- -------------- --- --- ------ --------------
# rdfs:label rdf:langString 9..9 nb (1), en (1)
# rdfs:label xsd:string 5..7
# ns:powerKW xsd:decimal 7.5 7.5
# ns:powerKW xsd:integer 11 11
#
# References out of the graph (1)
# predicate objects not subjects here of them in other graphs
# --------- ------------------------- -----------------------
# ns:site 1 1
In a class profile, 66.7% and 0..1 say that two of the three pumps have a powerKW, and those
that do have one. ex:s2 is the site of a pump in the default graph but only described in
urn:graph:sites, which the last table shows.
to_markdown (or to_text(format="markdown")) gives the same report as Markdown headings and
tables, for a notebook, a document or a language model. In Jupyter a description is shown that
way. show_class and show_predicate take format="markdown" too.
print(d.to_markdown(graphs=[None], sections=["classes", "links"]))
# # 2 graphs, 15 triples
#
# | graph | triples | predicates | classes | subjects | untyped | blank |
# |---|---:|---:|---:|---:|---:|---:|
# | default graph | 14 | 4 | 2 | 4 | 0 | 0 |
# | <urn:graph:sites> | 1 | 1 | 1 | 1 | 0 | 0 |
#
# ## default graph
#
# ### Classes (2)
#
# | class | instances |
# |---|---:|
# | ns:Pump | 3 |
# | ns:Site | 1 |
#
# ### Links between classes (1)
#
# | subject class | predicate | object class | triples |
# |---|---|---|---:|
# | ns:Pump | ns:site | ns:Site | 2 |
The report does not grow with the model. Its first table has the 15 largest graphs, then the 5
largest graphs are detailed with the 15 largest rows of each table, and lines such as
... 26 more predicates with 1,204 triples (0.3%) count what is left out. The lines of the text
report are at most 100 characters (width): a table that is wider has its widest columns cut with
an ellipsis, the names of the rows last, and a column without values is left out. Markdown and
the DataFrames have every cell in full. Graphs with the
same predicates as a graph already detailed are only named (Same predicates in 30 more graphs: ...). print(d) gives at most 20,000 characters. To see more or less:
d.to_text(max_graphs=1, max_rows=5) # None for no limit
d.to_text(max_chars=4000) # halves max_rows, then max_graphs, until it fits
d.to_text(graphs=["urn:graph:sites"]) # these graphs instead of the largest
d.to_text(sections=["classes", "predicates"]) # only these sections
d.to_text(width=140) # longer lines; None for no limit
d.to_dict(max_rows=20, max_graphs=3) # plain dicts and lists, e.g. for json.dumps
show_class and show_predicate take an IRI, <IRI> or a name with a prefix of the report. The
DataFrames always hold everything that was computed; their size follows the number of graphs,
predicates and classes, not the number of triples.
diff compares two descriptions, e.g. before and after a mapping, an update or an inference run:
before = m.describe()
m.update(f"INSERT DATA {{ <{EX}p4> a <{EX}Pump> }}")
print(m.describe().diff(before))
# 1 predicates changed
# ====================
# graph predicate before after change
# ------------- --------- ------ ----- ------
# default graph rdf:type 4 5 +1
#
# 1 classes changed
# =================
# graph class before after change
# ------------- ------- ------ ----- ------
# default graph ns:Pump 3 4 +1
Its predicates and classes are DataFrames with before, after and change.
Threads¶
A Model can be shared between threads. Reads (query, query_external, write, writes,
write_bytes, size, get_templates and list_udfs) run
at the same time. Changes take an exclusive lock and wait for running reads. Queries release the
GIL while they run, so other Python threads keep working.
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(4) as pool:
sizes = list(pool.map(lambda _: m.query("SELECT * WHERE { ?s ?p ?o }").height, range(8)))
print(sizes)
Errors¶
Most errors raise fastrdf.FastrdfException, and invalid arguments raise
fastrdf.FunctionArgumentException. Syntax errors in SPARQL, Datalog and stOTTR show the
offending source with a hint:
from fastrdf import FastrdfException
try:
m.query("SELEC ?x WHERE { ?x ?p ?o }")
except FastrdfException as e:
print(e)
# SPARQL parsing error: SPARQL syntax error at line 1, column 1: unexpected `SELEC`
# |
# 1 | SELEC ?x WHERE { ?x ?p ?o }
# | ^^^^^
# ...
# = help: did you mean `SELECT`?