The reader converts the triples of a document into model entities, in two layers that work together. A Python pipeline runs six phases. A declarative mapping, the YAML reader.yaml, says what each class and predicate means, and the pipeline reads it; a reader class implements only what YAML cannot say. The entities end up in artefact.entities.
This notebook inspects both, as they ship with LODE. The imports from lode.reader and lode.profiles below are for people who debug LODE: they are not part of the stable API of the Python API.
Methods to inspect a reader¶
| Method | What it gives |
|---|---|
lode.reader.read_into(artefact, source) | Runs the pipeline and fills the artefact. You do not call it: lode.read and the Artefact classes do. |
artefact.reader | The reader that built the artefact. |
profiles.resolve(profile.reader, profile.package) | The reader class of a profile, without reading anything. |
reader_class.phase1_classify_from_predicates … phase6_create_statements | The six phases. vars(reader_class) tells which ones a reader overrides. |
ConfigManager(profile).config | The merged mapper: base.yaml plus the reader.yaml of the profile. |
config_manager.get_type_mapping() | The entries of the RDF classes, parsed, with the model classes resolved. |
config_manager.get_property_mapping() | The same for the predicates. |
config_manager.get_group_axioms() | The axioms about several entities and the methods that handle them (phase 4). |
config_manager.get_punning_priority() | Which class wins when an IRI has more than one. |
from lode import OwlOntology
ontology = OwlOntology("http://purl.org/spar/cito/") # calls read_into
print(type(ontology.reader).__name__, len(ontology.get_entities()), "entities")OwlReader 488 entities
artefact.reader¶
An artefact keeps the reader that built it.
import tempfile
from pathlib import Path
TURTLE = """
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix ex: <http://example.org/zoo#> .
<http://example.org/zoo> a owl:Ontology .
ex:Animal a owl:Class .
ex:Cat a owl:Class ; rdfs:subClassOf ex:Animal .
"""
path = Path(tempfile.mkdtemp()) / "zoo.ttl"
path.write_text(TURTLE, encoding="utf-8")
onto = OwlOntology(str(path))
print(type(onto.reader).__name__, "extends", type(onto.reader).__bases__[0].__name__)OwlReader extends Reader
profiles.resolve(profile.reader, profile.package)¶
The profile knows where the reader class of each format is.
from lode import profiles
owl = profiles.get("owl")
print("the profile says:", owl.reader)
reader_class = profiles.resolve(owl.reader, owl.package)
reader_classthe profile says: .reader:OwlReader
lode.profiles.owl.reader.OwlReaderThe six phases¶
The reader fills the entities in six phases, one method each, and read_into calls them in order. The table is built from the class itself, so it cannot go out of date.
import html
import inspect
from IPython.display import HTML
from lode.reader.reader import Reader
def phases(cls):
"""Yield (name, first docstring line) of the phase methods defined by `cls`, in order."""
for name, member in vars(cls).items():
if callable(member) and name.startswith("phase"):
yield name, (inspect.getdoc(member) or "").split("\n")[0]
rows = "".join(
f"<tr><td><code>{name}()</code></td><td>{html.escape(summary)}</td></tr>"
for name, summary in phases(Reader)
)
HTML(f"<table><tr><th>Method</th><th>What it does</th></tr>{rows}</table>")A format changes only the phases it overrides:
skos = profiles.get("skos")
skos_class = profiles.resolve(skos.reader, skos.package)
for cls in (reader_class, skos_class):
print(f"{cls.__name__:<12}", [name for name, _ in phases(cls)])OwlReader ['phase1_classify_from_predicates', 'phase2_create_from_types', 'phase5_fallback']
SkosReader ['phase1_classify_from_predicates']
ConfigManager(profile).config¶
ConfigManager holds the mapper of a format: base.yaml, shared by every format, with the reader.yaml of the profile merged on top. The reader asks it what a predicate means and never reads YAML itself. The result is a dictionary:
from lode.reader.config_manager import ConfigManager
config_manager = ConfigManager(owl)
config = config_manager.config
for key, value in config.items():
print(f"{key:<16}", type(value).__name__, f"({len(value)})" if hasattr(value, "__len__") else "")name str (4)
namespaces list (5)
mapper dict (98)
enricher dict (4)
punning_priority list (8)
config_manager.get_type_mapping() and get_property_mapping()¶
mapper is what you will read most: one entry for every RDF class and predicate, which the reader sees parsed, with the model classes already resolved. What each key of an entry means is in Extending LODE, step 1.
types = config_manager.get_type_mapping()
properties = config_manager.get_property_mapping()
print(len(types), "classes,", len(properties), "predicates")37 classes, 61 predicates
An entry says what a predicate means. Follow one triple, ex:Cat rdfs:subClassOf ex:Animal, through the entry of rdfs:subClassOf:
from rdflib.namespace import RDFS
from lode.models import Concept
print("YAML :", config["mapper"]["rdfs:subClassOf"])
print("parsed:", properties[RDFS.subClassOf])
print()
entry = properties[RDFS.subClassOf]
(setter_name, target), = entry["setters"][0].items()
print("phase 1: the subject becomes a", entry["inferred_class"].__name__)
print("phase 3: the object is resolved to a", target.__name__, "and passed to", setter_name)
print()
print(inspect.getdoc(getattr(Concept, setter_name)))YAML : {'is': 'predicate', 'inferred_class': 'Concept', 'target_classes': ['Concept'], 'setters': [{'set_is_sub_concept_of': 'Concept'}]}
parsed: {'is': 'predicate', 'inferred_class': <class 'lode.models.concept.Concept'>, 'target_classes': [<class 'lode.models.concept.Concept'>], 'setters': [{'set_is_sub_concept_of': <class 'lode.models.concept.Concept'>}]}
phase 1: the subject becomes a Concept
phase 3: the object is resolved to a Concept and passed to set_is_sub_concept_of
Add a super concept to is_sub_concept_of and register self as its sub concept.
The inverse link is set only when the target supports it (a Restriction or
TruthFunction may not have the attribute).
The setter is a method of the model class: it fills is_sub_concept_of and registers the subject on the object as well.
When a setter is not enough the entry names a handler, a method of the reader class. The reader calls it instead of the setter. rdfs:domain has one in OWL:
print(config["mapper"]["rdfs:domain"])
print(inspect.getdoc(reader_class.handle_domain)){'is': 'predicate', 'target_classes': ['Property'], 'setters': [{'set_has_domain': 'Concept'}], 'handler': 'handle_domain'}
Handle rdfs:domain: link the property to its domain and the domain back to the property.
A domain that cannot become a Concept (it is cached as something else) is
forced into one, because of OWL punning.
config_manager.get_group_axioms()¶
enricher names the methods for axioms about several entities (phase 4).
for axiom, method in config_manager.get_group_axioms().items():
print(axiom.n3(), "->", method)<http://www.w3.org/2003/11/swrl#Imp> -> handle_swrl_imp
<http://www.w3.org/2002/07/owl#AllDisjointClasses> -> process_all_disjoint_classes
<http://www.w3.org/2002/07/owl#AllDifferent> -> process_all_different
<http://www.w3.org/2002/07/owl#AllDisjointProperties> -> process_all_disjoint_properties
config_manager.get_punning_priority()¶
When an IRI is used for more than one kind of entity (punning), the first class of the list wins.
print([cls.__name__ for cls in config_manager.get_punning_priority()])['Model', 'Individual', 'Concept', 'Relation', 'Attribute', 'Annotation', 'Property', 'Datatype']
How LODE uses it¶
lode.read and the Artefact classes call read_into, which builds the reader that the profile names and runs its phases. The reader stores the entities, instances of the classes of the model, in the artefact.
Writing your own reader¶
This page only inspects the readers that ship with LODE. You do not extend one of them: a new format brings its own mapper and, only where YAML is not enough, its own reader class. To write them, go to Extending LODE: Step 1, write the mapper and Step 2, write the reader class.