Query, inspect and visualize ontologies encoded via RDF and OWL.
—
The core analysis functionality centers around the Ontospy class, which provides comprehensive tools for loading, parsing, and analyzing RDF ontologies. This is the primary interface for working with ontological data and extracting structured information from RDF graphs.
Load RDF data from various sources including files, URLs, raw data strings, file objects, and SPARQL endpoints.
class Ontospy:
def __init__(self, uri_or_path=None, data=None, file_obj=None,
rdf_format="", verbose=False, hide_base_schemas=True,
hide_implicit_types=True, hide_implicit_preds=True,
hide_individuals=True, sparql_endpoint=None,
credentials=None, build_all=True, pref_title="qname",
pref_lang="en"):
"""
Initialize Ontospy with optional data loading.
Parameters:
- uri_or_path (str): File path or URL to RDF data
- data (str): Raw RDF data as string
- file_obj: Python file object containing RDF data
- rdf_format (str): RDF format ("turtle", "xml", "n3", "json-ld", etc.)
- verbose (bool): Enable verbose output during processing
- hide_base_schemas (bool): Filter out base schema vocabulary (RDF, RDFS, OWL)
- hide_implicit_types (bool): Filter implicit type declarations
- hide_implicit_preds (bool): Filter implicit predicate declarations
- hide_individuals (bool): Skip extraction of class instances
- sparql_endpoint (str): SPARQL endpoint URL for remote queries
- credentials (tuple): Authentication credentials (username, password)
- build_all (bool): Automatically extract all entities after loading
- pref_title (str): Display preference ("qname" or "label")
- pref_lang (str): Preferred language for labels and descriptions
"""
def load_rdf(self, uri_or_path=None, data=None, file_obj=None,
rdf_format="", verbose=False):
"""
Load RDF data from specified source.
Parameters:
- uri_or_path (str): File path or URL to RDF data
- data (str): Raw RDF data as string
- file_obj: Python file object containing RDF data
- rdf_format (str): RDF format specification
- verbose (bool): Enable verbose loading output
"""
def load_sparql(self, sparql_endpoint, verbose=False, credentials=None):
"""
Connect to SPARQL endpoint for remote ontology access.
Parameters:
- sparql_endpoint (str): SPARQL endpoint URL
- verbose (bool): Enable verbose connection output
- credentials (tuple): Authentication credentials if required
"""Usage example:
import ontospy
# Load from file
g = ontospy.Ontospy("ontology.owl")
# Load from URL with specific format
g = ontospy.Ontospy("http://example.org/ontology.rdf", rdf_format="xml")
# Load raw RDF data
rdf_data = """
@prefix ex: <http://example.org/> .
ex:Person a rdfs:Class .
"""
g = ontospy.Ontospy(data=rdf_data, rdf_format="turtle")
# Connect to SPARQL endpoint
g = ontospy.Ontospy(sparql_endpoint="http://dbpedia.org/sparql")Extract and build structured representations of ontological components from loaded RDF data.
def build_all(self, verbose=False, hide_base_schemas=True,
hide_implicit_types=True, hide_implicit_preds=True,
hide_individuals=True):
"""
Extract all ontological entities from loaded RDF graph.
Parameters:
- verbose (bool): Enable detailed extraction output
- hide_base_schemas (bool): Filter base vocabulary elements
- hide_implicit_types (bool): Filter implicit type declarations
- hide_implicit_preds (bool): Filter implicit predicate declarations
- hide_individuals (bool): Skip individual/instance extraction
"""
def build_classes(self, hide_base_schemas=True, hide_implicit_types=True):
"""Extract RDFS/OWL class definitions."""
def build_properties(self, hide_implicit_preds=True):
"""Extract RDF/OWL property definitions."""
def build_ontologies(self, exclude_BNodes=False, return_string=False):
"""Extract ontology metadata and declarations."""
def build_skos_concepts(self):
"""Extract SKOS concept hierarchy and definitions."""
def build_shapes(self):
"""Extract SHACL shape definitions and constraints."""
def build_individuals(self):
"""Extract class instances and individual resources."""Access extracted ontological entities using various lookup methods.
def get_class(self, id=None, uri=None, match=None):
"""
Retrieve class entity by identifier.
Parameters:
- id (int): Internal entity ID
- uri (str): Full URI of the class
- match (str): Pattern to match against class names
Returns:
OntoClass: Class entity or None if not found
"""
def get_property(self, id=None, uri=None, match=None):
"""
Retrieve property entity by identifier.
Returns:
OntoProperty: Property entity or None if not found
"""
def get_ontology(self, id=None, uri=None, match=None):
"""
Retrieve ontology entity by identifier.
Returns:
Ontology: Ontology entity or None if not found
"""
def get_skos(self, id=None, uri=None, match=None):
"""
Retrieve SKOS concept by identifier.
Returns:
OntoSKOSConcept: SKOS concept or None if not found
"""
def get_shapes(self, id=None, uri=None, match=None):
"""
Retrieve SHACL shape by identifier.
Returns:
OntoShape: Shape entity or None if not found
"""
def get_individual(self, id=None, uri=None, match=None):
"""
Retrieve individual/instance by identifier.
Returns:
RdfEntity: Individual entity or None if not found
"""
def get_any_entity(self, id=None, uri=None, match=None):
"""
Retrieve entity of any type by identifier.
Returns:
RdfEntity: Found entity or None
"""Analyze and extract hierarchical relationships between ontological entities.
def ontologyClassTree(self):
"""
Generate class hierarchy tree structure.
Returns:
TreeStructure: Nested representation of class hierarchy
"""
def ontologyPropTree(self):
"""
Generate property hierarchy tree structure.
Returns:
TreeStructure: Nested representation of property hierarchy
"""
def ontologyConceptTree(self):
"""
Generate SKOS concept hierarchy tree.
Returns:
TreeStructure: Nested SKOS concept relationships
"""
def ontologyShapeTree(self):
"""
Generate SHACL shapes tree structure.
Returns:
TreeStructure: Nested shape hierarchy
"""
def getInferredPropertiesForClass(self, aClass, rel="domain_of"):
"""
Get properties applicable to class including inherited properties.
Parameters:
- aClass (OntoClass): Target class entity
- rel (str): Relationship type ("domain_of" or "range_of")
Returns:
list: Properties applicable to the class
"""Execute SPARQL queries and perform statistical analysis on loaded ontologies.
def query(self, sparql_query):
"""
Execute SPARQL query against loaded RDF graph.
Parameters:
- sparql_query (str): SPARQL query string
Returns:
rdflib.plugins.sparql.processor.SPARQLResult: Query results
"""
def sparql(self, sparql_query):
"""Alias for query() method."""
def stats(self):
"""
Generate comprehensive ontology statistics.
Returns:
StatsResult: List of (category, count) tuples including:
- ('Ontologies', count)
- ('Triples', count)
- ('Classes', count)
- ('Properties', count)
- ('Annotation Properties', count)
- ('Object Properties', count)
- ('Datatype Properties', count)
- ('SKOS Concepts', count)
- ('SHACL Shapes', count)
- ('Data Sources', count)
"""
def triplesCount(self):
"""
Count total triples in loaded graph.
Returns:
int: Number of RDF triples
"""Export ontology data in various RDF formats and generate serialized representations.
def serialize(self, format="turtle"):
"""
Serialize loaded RDF graph to specified format.
Parameters:
- format (str): Output format ("turtle", "xml", "n3", "json-ld", "nt")
Returns:
str: Serialized RDF data
"""
def rdf_source(self, format="turtle"):
"""Alias for serialize() method."""Generate textual representations and hierarchical displays of ontological structures.
def printClassTree(self, element=None, showids=False, labels=False, showtype=False):
"""
Print formatted class hierarchy tree.
Parameters:
- element (OntoClass): Root element for subtree (None for full tree)
- showids (bool): Include entity IDs in output
- labels (bool): Show labels instead of URIs
- showtype (bool): Include RDF type information
"""
def printPropertyTree(self, element=None, showids=False, labels=False, showtype=False):
"""Print formatted property hierarchy tree."""
def printSkosTree(self, element=None, showids=False, labels=False, showtype=False):
"""Print formatted SKOS concept hierarchy tree."""
def printShapesTree(self, element=None, showids=False, labels=False, showtype=False):
"""Print formatted SHACL shapes hierarchy tree."""Navigate through entity collections with helper methods for iteration and traversal.
def nextClass(self, classuri):
"""
Get next class in ordered collection.
Parameters:
- classuri (str): Current class URI
Returns:
OntoClass: Next class entity or None
"""
def nextProperty(self, propuri):
"""Get next property in collection."""
def nextConcept(self, concepturi):
"""Get next SKOS concept in collection."""
def nextShapes(self, shapeuri):
"""Get next SHACL shape in collection."""
def nextOntology(self, ontologyuri):
"""Get next ontology in collection."""# Entity collections (read-only lists)
all_ontologies: list[Ontology] # All extracted ontology instances
all_classes: list[OntoClass] # All extracted class entities
all_properties: list[OntoProperty] # All properties (all types combined)
all_properties_annotation: list[OntoProperty] # Annotation properties only
all_properties_object: list[OntoProperty] # Object properties only
all_properties_datatype: list[OntoProperty] # Datatype properties only
all_skos_concepts: list[OntoSKOSConcept] # All SKOS concepts
all_shapes: list[OntoShape] # All SHACL shapes
all_individuals: list[RdfEntity] # All class instances
# Hierarchy top-level entities
toplayer_classes: list[OntoClass] # Classes with no parent classes
toplayer_properties: list[OntoProperty] # Properties with no parent properties
toplayer_skos: list[OntoSKOSConcept] # Top-level SKOS concepts
toplayer_shapes: list[OntoShape] # Top-level SHACL shapes
# Graph metadata
namespaces: dict # Namespace prefix mappings in the graph
sources: list[str] # Data sources that were loadedUsage example:
import ontospy
# Load and analyze ontology
g = ontospy.Ontospy("foaf.rdf", build_all=True)
# Get statistics
stats = g.stats()
print(f"Found {len(g.all_classes)} classes and {len(g.all_properties)} properties")
# Find specific class
person_class = g.get_class(match="Person")
if person_class:
print(f"Person class: {person_class.uri}")
print(f"Properties in domain: {len(person_class.domain_of)}")
# Query the graph
results = g.query("SELECT ?s ?p ?o WHERE {?s ?p ?o} LIMIT 10")
for row in results:
print(f"{row.s} -> {row.p} -> {row.o}")
# Export to different format
turtle_output = g.serialize("turtle")Install with Tessl CLI
npx tessl i tessl/pypi-ontospy