Query, inspect and visualize ontologies encoded via RDF and OWL.
—
Entity classes provide structured, Pythonic representations of RDF resources including classes, properties, ontologies, SKOS concepts, and SHACL shapes. Each entity type offers specialized methods for accessing metadata, traversing relationships, and analyzing structural properties within ontological contexts.
The foundational class for all RDF resource representations, providing common functionality for metadata access, relationship traversal, and display formatting.
class RdfEntity:
def __init__(self, uri, rdftype=None, namespaces=None,
ext_model=False, is_Bnode=False,
pref_title="qname", pref_lang="en"):
"""
Initialize RDF entity representation.
Parameters:
- uri (str): Full URI of the RDF resource
- rdftype (URIRef): RDF type of the resource
- namespaces (dict): Namespace prefix mappings
- ext_model (bool): Flag for external model entities
- is_Bnode (bool): Flag identifying blank nodes
- pref_title (str): Display preference ("qname" or "label")
- pref_lang (str): Preferred language for text values
"""
def bestLabel(self, prefLanguage="", qname_allowed=True, quotes=False):
"""
Get the best available label for display.
Parameters:
- prefLanguage (str): Preferred language code
- qname_allowed (bool): Allow qualified names as fallback
- quotes (bool): Wrap result in quotes
Returns:
str: Best available label or URI local part
"""
def bestDescription(self, prefLanguage="", quotes=False):
"""
Get the best available description text.
Parameters:
- prefLanguage (str): Preferred language code
- quotes (bool): Wrap result in quotes
Returns:
str: Description text or empty string
"""
def rdf_source(self, format="turtle"):
"""
Serialize entity to RDF format.
Parameters:
- format (str): RDF serialization format
Returns:
str: Serialized RDF representation
"""
def printTriples(self):
"""Print all RDF triples for this entity."""
def printSerialize(self, format="turtle"):
"""Print serialized RDF representation."""Navigate hierarchical and associative relationships between RDF entities.
def ancestors(self, cl=None, noduplicates=True):
"""
Get all ancestor entities in hierarchy.
Parameters:
- cl (class): Filter by specific entity class
- noduplicates (bool): Remove duplicate entities
Returns:
list: All ancestor entities (transitive closure)
"""
def descendants(self, cl=None, noduplicates=True):
"""
Get all descendant entities in hierarchy.
Parameters:
- cl (class): Filter by specific entity class
- noduplicates (bool): Remove duplicate entities
Returns:
list: All descendant entities (transitive closure)
"""
def parents(self):
"""
Get direct parent entities.
Returns:
list: Immediate parent entities
"""
def children(self):
"""
Get direct child entities.
Returns:
list: Immediate child entities
"""
def getValuesForProperty(self, aPropURIRef):
"""
Extract values for specific property.
Parameters:
- aPropURIRef (URIRef): Property URI reference
Returns:
list: Property values for this entity
"""
def instance_of(self):
"""
Get classes this entity is an instance of.
Returns:
list: Class entities this resource instantiates
"""Represent OWL ontology declarations and provide access to contained vocabulary elements.
class Ontology(RdfEntity):
def __init__(self, uri, rdftype=None, namespaces=None,
pref_prefix="", ext_model=False,
pref_title="qname", pref_lang="en"):
"""
Initialize ontology entity.
Parameters:
- pref_prefix (str): Preferred namespace prefix for this ontology
"""
def annotations(self, qname=True):
"""
Get all annotation triples for this ontology.
Parameters:
- qname (bool): Convert URIs to qualified names
Returns:
list: Annotation triples as (subject, predicate, object) tuples
"""
def describe(self):
"""Print comprehensive ontology information."""
def stats(self):
"""Print statistical summary of ontology contents."""
# Properties
all_classes: list[OntoClass] # Classes defined in this ontology
all_properties: list[OntoProperty] # Properties defined in this ontology
all_skos_concepts: list[OntoSKOSConcept] # SKOS concepts in this ontologyRepresent RDFS/OWL classes with specialized methods for analyzing class-specific properties and relationships.
class OntoClass(RdfEntity):
def count(self):
"""
Count instances of this class.
Returns:
int: Number of individuals that are instances of this class
"""
def describe(self):
"""Print detailed class information including hierarchy and properties."""
def printStats(self):
"""Print statistical information about this class."""
def printGenericTree(self):
"""Print hierarchical tree representation of this class."""
# Properties for class-property relationships
domain_of: list[OntoProperty] # Properties with this class in domain
range_of: list[OntoProperty] # Properties with this class in range
domain_of_inferred: list[OntoProperty] # Domain properties including inheritance
range_of_inferred: list[OntoProperty] # Range properties including inheritance
# SHACL integration
shapedProperties: list[OntoProperty] # Properties constrained by SHACL shapes
shacl_constraints: list # SHACL constraints targeting this class
# Instance access
instances: list[RdfEntity] # All instances of this classRepresent RDF/OWL properties including object properties, datatype properties, and annotation properties.
class OntoProperty(RdfEntity):
def describe(self):
"""Print detailed property information including domain/range."""
def printStats(self):
"""Print statistical information about this property."""
def printGenericTree(self):
"""Print hierarchical tree representation of this property."""
# Domain and range relationships
domains: list[OntoClass] # Classes in the domain of this property
ranges: list[OntoClass] # Classes in the range of this propertyUsage example:
import ontospy
# Load ontology
g = ontospy.Ontospy("foaf.rdf", build_all=True)
# Work with classes
person_class = g.get_class(match="Person")
if person_class:
print(f"Class: {person_class.bestLabel()}")
print(f"Instances: {person_class.count()}")
print(f"Properties in domain: {len(person_class.domain_of)}")
# Print class hierarchy
person_class.printGenericTree()
# Get all superclasses
ancestors = person_class.ancestors()
print(f"Ancestor classes: {[cls.bestLabel() for cls in ancestors]}")
# Work with properties
name_prop = g.get_property(match="name")
if name_prop:
print(f"Property: {name_prop.bestLabel()}")
print(f"Domain classes: {[cls.bestLabel() for cls in name_prop.domains]}")
print(f"Range classes: {[cls.bestLabel() for cls in name_prop.ranges]}")Represent SKOS concepts with support for concept schemes, broader/narrower relationships, and multilingual labels.
class OntoSKOSConcept(RdfEntity):
def describe(self):
"""Print detailed SKOS concept information."""
def printStats(self):
"""Print statistical information about this concept."""
def printGenericTree(self):
"""Print SKOS concept hierarchy tree."""Represent SHACL shapes for data validation and constraint specification.
class OntoShape(RdfEntity):
def describe(self):
"""Print detailed SHACL shape information."""
def printStats(self):
"""Print statistical information about this shape."""
# Shape targets
targetClasses: list[OntoClass] # Classes targeted by this shape# Load ontology
g = ontospy.Ontospy("ontology.owl", build_all=True)
# Inspect any entity
entity = g.get_class(uri="http://example.org/Person")
print(f"URI: {entity.uri}")
print(f"Label: {entity.bestLabel()}")
print(f"Description: {entity.bestDescription()}")
# Get all triples
entity.printTriples()
# Navigate relationships
parents = entity.parents()
children = entity.children()# Find top-level classes
top_classes = g.toplayer_classes
# Traverse class hierarchy
for cls in top_classes:
print(f"Top-level class: {cls.bestLabel()}")
descendants = cls.descendants()
print(f" Has {len(descendants)} descendant classes")
# Print full hierarchy
cls.printGenericTree()# Analyze property usage
for prop in g.all_properties:
if prop.domains and prop.ranges:
print(f"Property: {prop.bestLabel()}")
print(f" Domain: {[d.bestLabel() for d in prop.domains]}")
print(f" Range: {[r.bestLabel() for r in prop.ranges]}")# Find all properties applicable to a class
person_class = g.get_class(match="Person")
if person_class:
# Direct domain properties
direct_props = person_class.domain_of
# Including inherited properties
inherited_props = person_class.domain_of_inferred
print(f"Direct properties: {len(direct_props)}")
print(f"Total applicable properties: {len(inherited_props)}")Install with Tessl CLI
npx tessl i tessl/pypi-ontospy