0
# Entity Classes
1
2
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.
3
4
## Capabilities
5
6
### Base RDF Entity
7
8
The foundational class for all RDF resource representations, providing common functionality for metadata access, relationship traversal, and display formatting.
9
10
```python { .api }
11
class RdfEntity:
12
def __init__(self, uri, rdftype=None, namespaces=None,
13
ext_model=False, is_Bnode=False,
14
pref_title="qname", pref_lang="en"):
15
"""
16
Initialize RDF entity representation.
17
18
Parameters:
19
- uri (str): Full URI of the RDF resource
20
- rdftype (URIRef): RDF type of the resource
21
- namespaces (dict): Namespace prefix mappings
22
- ext_model (bool): Flag for external model entities
23
- is_Bnode (bool): Flag identifying blank nodes
24
- pref_title (str): Display preference ("qname" or "label")
25
- pref_lang (str): Preferred language for text values
26
"""
27
28
def bestLabel(self, prefLanguage="", qname_allowed=True, quotes=False):
29
"""
30
Get the best available label for display.
31
32
Parameters:
33
- prefLanguage (str): Preferred language code
34
- qname_allowed (bool): Allow qualified names as fallback
35
- quotes (bool): Wrap result in quotes
36
37
Returns:
38
str: Best available label or URI local part
39
"""
40
41
def bestDescription(self, prefLanguage="", quotes=False):
42
"""
43
Get the best available description text.
44
45
Parameters:
46
- prefLanguage (str): Preferred language code
47
- quotes (bool): Wrap result in quotes
48
49
Returns:
50
str: Description text or empty string
51
"""
52
53
def rdf_source(self, format="turtle"):
54
"""
55
Serialize entity to RDF format.
56
57
Parameters:
58
- format (str): RDF serialization format
59
60
Returns:
61
str: Serialized RDF representation
62
"""
63
64
def printTriples(self):
65
"""Print all RDF triples for this entity."""
66
67
def printSerialize(self, format="turtle"):
68
"""Print serialized RDF representation."""
69
```
70
71
### Relationship Traversal
72
73
Navigate hierarchical and associative relationships between RDF entities.
74
75
```python { .api }
76
def ancestors(self, cl=None, noduplicates=True):
77
"""
78
Get all ancestor entities in hierarchy.
79
80
Parameters:
81
- cl (class): Filter by specific entity class
82
- noduplicates (bool): Remove duplicate entities
83
84
Returns:
85
list: All ancestor entities (transitive closure)
86
"""
87
88
def descendants(self, cl=None, noduplicates=True):
89
"""
90
Get all descendant entities in hierarchy.
91
92
Parameters:
93
- cl (class): Filter by specific entity class
94
- noduplicates (bool): Remove duplicate entities
95
96
Returns:
97
list: All descendant entities (transitive closure)
98
"""
99
100
def parents(self):
101
"""
102
Get direct parent entities.
103
104
Returns:
105
list: Immediate parent entities
106
"""
107
108
def children(self):
109
"""
110
Get direct child entities.
111
112
Returns:
113
list: Immediate child entities
114
"""
115
116
def getValuesForProperty(self, aPropURIRef):
117
"""
118
Extract values for specific property.
119
120
Parameters:
121
- aPropURIRef (URIRef): Property URI reference
122
123
Returns:
124
list: Property values for this entity
125
"""
126
127
def instance_of(self):
128
"""
129
Get classes this entity is an instance of.
130
131
Returns:
132
list: Class entities this resource instantiates
133
"""
134
```
135
136
### Ontology Entities
137
138
Represent OWL ontology declarations and provide access to contained vocabulary elements.
139
140
```python { .api }
141
class Ontology(RdfEntity):
142
def __init__(self, uri, rdftype=None, namespaces=None,
143
pref_prefix="", ext_model=False,
144
pref_title="qname", pref_lang="en"):
145
"""
146
Initialize ontology entity.
147
148
Parameters:
149
- pref_prefix (str): Preferred namespace prefix for this ontology
150
"""
151
152
def annotations(self, qname=True):
153
"""
154
Get all annotation triples for this ontology.
155
156
Parameters:
157
- qname (bool): Convert URIs to qualified names
158
159
Returns:
160
list: Annotation triples as (subject, predicate, object) tuples
161
"""
162
163
def describe(self):
164
"""Print comprehensive ontology information."""
165
166
def stats(self):
167
"""Print statistical summary of ontology contents."""
168
169
# Properties
170
all_classes: list[OntoClass] # Classes defined in this ontology
171
all_properties: list[OntoProperty] # Properties defined in this ontology
172
all_skos_concepts: list[OntoSKOSConcept] # SKOS concepts in this ontology
173
```
174
175
### Class Entities
176
177
Represent RDFS/OWL classes with specialized methods for analyzing class-specific properties and relationships.
178
179
```python { .api }
180
class OntoClass(RdfEntity):
181
def count(self):
182
"""
183
Count instances of this class.
184
185
Returns:
186
int: Number of individuals that are instances of this class
187
"""
188
189
def describe(self):
190
"""Print detailed class information including hierarchy and properties."""
191
192
def printStats(self):
193
"""Print statistical information about this class."""
194
195
def printGenericTree(self):
196
"""Print hierarchical tree representation of this class."""
197
198
# Properties for class-property relationships
199
domain_of: list[OntoProperty] # Properties with this class in domain
200
range_of: list[OntoProperty] # Properties with this class in range
201
domain_of_inferred: list[OntoProperty] # Domain properties including inheritance
202
range_of_inferred: list[OntoProperty] # Range properties including inheritance
203
204
# SHACL integration
205
shapedProperties: list[OntoProperty] # Properties constrained by SHACL shapes
206
shacl_constraints: list # SHACL constraints targeting this class
207
208
# Instance access
209
instances: list[RdfEntity] # All instances of this class
210
```
211
212
### Property Entities
213
214
Represent RDF/OWL properties including object properties, datatype properties, and annotation properties.
215
216
```python { .api }
217
class OntoProperty(RdfEntity):
218
def describe(self):
219
"""Print detailed property information including domain/range."""
220
221
def printStats(self):
222
"""Print statistical information about this property."""
223
224
def printGenericTree(self):
225
"""Print hierarchical tree representation of this property."""
226
227
# Domain and range relationships
228
domains: list[OntoClass] # Classes in the domain of this property
229
ranges: list[OntoClass] # Classes in the range of this property
230
```
231
232
Usage example:
233
234
```python
235
import ontospy
236
237
# Load ontology
238
g = ontospy.Ontospy("foaf.rdf", build_all=True)
239
240
# Work with classes
241
person_class = g.get_class(match="Person")
242
if person_class:
243
print(f"Class: {person_class.bestLabel()}")
244
print(f"Instances: {person_class.count()}")
245
print(f"Properties in domain: {len(person_class.domain_of)}")
246
247
# Print class hierarchy
248
person_class.printGenericTree()
249
250
# Get all superclasses
251
ancestors = person_class.ancestors()
252
print(f"Ancestor classes: {[cls.bestLabel() for cls in ancestors]}")
253
254
# Work with properties
255
name_prop = g.get_property(match="name")
256
if name_prop:
257
print(f"Property: {name_prop.bestLabel()}")
258
print(f"Domain classes: {[cls.bestLabel() for cls in name_prop.domains]}")
259
print(f"Range classes: {[cls.bestLabel() for cls in name_prop.ranges]}")
260
```
261
262
### SKOS Concept Entities
263
264
Represent SKOS concepts with support for concept schemes, broader/narrower relationships, and multilingual labels.
265
266
```python { .api }
267
class OntoSKOSConcept(RdfEntity):
268
def describe(self):
269
"""Print detailed SKOS concept information."""
270
271
def printStats(self):
272
"""Print statistical information about this concept."""
273
274
def printGenericTree(self):
275
"""Print SKOS concept hierarchy tree."""
276
```
277
278
### SHACL Shape Entities
279
280
Represent SHACL shapes for data validation and constraint specification.
281
282
```python { .api }
283
class OntoShape(RdfEntity):
284
def describe(self):
285
"""Print detailed SHACL shape information."""
286
287
def printStats(self):
288
"""Print statistical information about this shape."""
289
290
# Shape targets
291
targetClasses: list[OntoClass] # Classes targeted by this shape
292
```
293
294
## Common Usage Patterns
295
296
### Entity Inspection
297
298
```python
299
# Load ontology
300
g = ontospy.Ontospy("ontology.owl", build_all=True)
301
302
# Inspect any entity
303
entity = g.get_class(uri="http://example.org/Person")
304
print(f"URI: {entity.uri}")
305
print(f"Label: {entity.bestLabel()}")
306
print(f"Description: {entity.bestDescription()}")
307
308
# Get all triples
309
entity.printTriples()
310
311
# Navigate relationships
312
parents = entity.parents()
313
children = entity.children()
314
```
315
316
### Hierarchy Navigation
317
318
```python
319
# Find top-level classes
320
top_classes = g.toplayer_classes
321
322
# Traverse class hierarchy
323
for cls in top_classes:
324
print(f"Top-level class: {cls.bestLabel()}")
325
descendants = cls.descendants()
326
print(f" Has {len(descendants)} descendant classes")
327
328
# Print full hierarchy
329
cls.printGenericTree()
330
```
331
332
### Property Analysis
333
334
```python
335
# Analyze property usage
336
for prop in g.all_properties:
337
if prop.domains and prop.ranges:
338
print(f"Property: {prop.bestLabel()}")
339
print(f" Domain: {[d.bestLabel() for d in prop.domains]}")
340
print(f" Range: {[r.bestLabel() for r in prop.ranges]}")
341
```
342
343
### Cross-Entity Relationships
344
345
```python
346
# Find all properties applicable to a class
347
person_class = g.get_class(match="Person")
348
if person_class:
349
# Direct domain properties
350
direct_props = person_class.domain_of
351
352
# Including inherited properties
353
inherited_props = person_class.domain_of_inferred
354
355
print(f"Direct properties: {len(direct_props)}")
356
print(f"Total applicable properties: {len(inherited_props)}")
357
```