Knowledge Graph model¶
Knowledge Graph metamodel.
A lightweight, typed in-memory representation of a knowledge graph used by the Web Modeling Editor’s KG diagram and by OWL-to-KG ingestion. The metamodel distinguishes five node kinds (class, individual, property, literal, blank) and directed edges between them.
KG diagrams are stored as JSON in projects; the typed metamodel backs the JSON
round-trip converters and the KG-to-ClassDiagram / KG-to-ObjectDiagram
transformations. Exporting a project to Python source goes through
besser.utilities.buml_code_builder.kg_model_builder, whose output is read
back by kg_diagram_converter.kg_buml_to_json. Because KG identifiers (IRIs,
blank-node ids, literal values) are not Python-identifier-safe, KGNode inherits
from Element rather than NamedElement; IRIs and labels are preserved
verbatim, and the builder derives variable names separately.
-
class besser.BUML.metamodel.kg.knowledge_graph.KGNode(id: str, label: str =
'', iri: str | None =None, metadata: dict[str, Any] | None =None)[source]¶ Bases:
_KGAnnotatedElement,ABCBase class for every node in a Knowledge Graph.
- Parameters:¶
id – Stable identifier unique within the graph.
label – Human-readable label shown in the editor.
iri – Optional IRI (populated for OWL-sourced nodes).
metadata – Free-form dict of structured annotations attached during import (e.g.,
{"kind": "restriction", "on_property": iri, "restriction_type": "minCardinality", "value": 1}on aKGBlankrepresenting anowl:Restriction). Defaults to an empty dict; never participates in identity / hashing.
-
_abc_impl =
<_abc._abc_data object>¶
-
class besser.BUML.metamodel.kg.knowledge_graph.KGClass(id: str, label: str =
'', iri: str | None =None, metadata: dict[str, Any] | None =None)[source]¶ Bases:
KGNodeA class / concept / type (e.g.
owl:Class).-
_abc_impl =
<_abc._abc_data object>¶
-
_abc_impl =
-
class besser.BUML.metamodel.kg.knowledge_graph.KGIndividual(id: str, label: str =
'', iri: str | None =None, metadata: dict[str, Any] | None =None)[source]¶ Bases:
KGNodeAn individual / instance (e.g.
owl:NamedIndividual).-
_abc_impl =
<_abc._abc_data object>¶
-
_abc_impl =
-
class besser.BUML.metamodel.kg.knowledge_graph.KGProperty(id: str, label: str =
'', iri: str | None =None, metadata: dict[str, Any] | None =None)[source]¶ Bases:
KGNodeA reified property node — a property that is itself the subject or object of further assertions (e.g.
owl:ObjectProperty).-
_abc_impl =
<_abc._abc_data object>¶
-
_abc_impl =
-
class besser.BUML.metamodel.kg.knowledge_graph.KGLiteral(id: str, value: str, datatype: str | None =
None, label: str ='', metadata: dict[str, Any] | None =None)[source]¶ Bases:
KGNodeA literal value (string, number, typed literal, …).
- Parameters:¶
id – Stable identifier.
value – Lexical form of the literal.
datatype – Optional datatype IRI (e.g.
xsd:integer).label – Optional display label; defaults to
valuewhen omitted.metadata – Free-form annotations dict (forwarded to
KGNode).
-
_abc_impl =
<_abc._abc_data object>¶
-
class besser.BUML.metamodel.kg.knowledge_graph.KGBlank(id: str, label: str =
'', iri: str | None =None, metadata: dict[str, Any] | None =None)[source]¶ Bases:
KGNodeAn anonymous resource (RDF blank node).
-
_abc_impl =
<_abc._abc_data object>¶
-
_abc_impl =
-
class besser.BUML.metamodel.kg.knowledge_graph.KGNodeConstraint(id: str, label: str =
'', iri: str | None =None, metadata: dict[str, Any] | None =None)[source]¶ Bases:
_ConstraintNodeMixin,KGNodeA reified constraint that applies to a class.
Materialises an OWL restriction set or a SHACL
sh:NodeShapeas a first-class visual node. The constraint payload lives inmetadata['constraintSpecs']as a list of dicts whose schema is documented inbesser.BUML.metamodel.kg.constraint_specs.Linked to its target class via an edge with iri
http://besser-pearl.org/kg#constraintTargetClass(and, for SHACL NodeShapes, may also carry the standardsh:targetClasspredicate on export).-
_abc_impl =
<_abc._abc_data object>¶
-
_abc_impl =
-
class besser.BUML.metamodel.kg.knowledge_graph.KGPropertyConstraint(id: str, label: str =
'', iri: str | None =None, metadata: dict[str, Any] | None =None)[source]¶ Bases:
_ConstraintNodeMixin,KGNodeA reified constraint that applies to a property.
Materialises an OWL
owl:Restrictionor a SHACLsh:PropertyShapeas a first-class visual node. Linked to aKGPropertyvia theconstraintTargetPropertyedge and/or grouped under aKGNodeConstraintvia thesh:propertyedge.-
_abc_impl =
<_abc._abc_data object>¶
-
_abc_impl =
-
class besser.BUML.metamodel.kg.knowledge_graph.KGEdge(id: str, source: KGNode, target: KGNode, label: str =
'', iri: str | None =None, metadata: dict[str, Any] | None =None)[source]¶ Bases:
_KGAnnotatedElementA directed relationship between two KG nodes.
- Parameters:¶
id – Stable identifier unique within the graph.
source – Source node.
target – Target node.
label – Optional display label (often the predicate’s local name).
iri – Optional predicate IRI.
metadata – Free-form dict of structured annotations attached during import. Defaults to an empty dict; never participates in identity / hashing.
-
_abc_impl =
<_abc._abc_data object>¶
-
class besser.BUML.metamodel.kg.knowledge_graph.KnowledgeGraph(name: str =
'knowledge_graph', nodes: set[KGNode] | None =None, edges: set[KGEdge] | None =None, axioms: list[KGAxiom] | None =None)[source]¶ Bases:
ModelTop-level Knowledge Graph container.
nodesandedgeshand out the graph’s own sets, because the OWL importer edits them in place while it lifts restrictions into constraint nodes;validate()catches what that lets through (a dangling edge, a duplicate id).axiomshands out a copy, since nothing edits the list in place; change it withadd_axiom()or by assignment.- Parameters:¶
name – Python-identifier-safe name for the model (
NamedElement.namerules apply).nodes – Initial set of nodes.
edges – Initial set of edges; their source/target must be in
nodes.axioms – Initial list of decoded OWL axioms (equivalentClass, disjoint, inverseOf, subPropertyOf, …) that don’t naturally belong on a single node or edge. Defaults to an empty list.
-
_abc_impl =
<_abc._abc_data object>¶
- property nodes : set[KGNode]¶
Get the graph’s own node set (not a copy).
Adding to it directly skips
add_node()’s duplicate-id check;validate()reports what that lets through.
- property edges : set[KGEdge]¶
Get the graph’s own edge set (not a copy).
Adding to it directly skips
add_edge()’s endpoint check;validate()reports what that lets through.
- add_edge(edge: KGEdge) None[source]¶
Add one edge.
- Raises:¶
ValueError – If
edgeis not aKGEdge, or an endpoint is not among the graph’s nodes.
- property axioms : list[KGAxiom]¶
Get a copy of the OWL axioms that relate several nodes at once.
Unlike
nodesandedges, the list is a copy: change it withadd_axiom()or by assigning the property.
- add_axiom(axiom: KGAxiom) None[source]¶
Append one axiom.
- Raises:¶
ValueError – If
axiomis not aKGAxiom.
-
validate(raise_exception: bool =
True) dict[source]¶ Validate the graph, collecting every problem rather than the first.
KnowledgeGraphwas the onlyModelwithout this, so a graph assembled by assigningkg.nodes/kg.edgesdirectly (which the setters allow, and which skipsadd_edge’s endpoint check in the order they are assigned) could carry dangling edges unnoticed.
- _validate_constraint_specs(errors: list[str]) None[source]¶
Constraint nodes validate their specs on assignment; this catches state that got around that (an unpickled graph, or one assembled through private attributes).
- _validate_axiom_references(errors: list[str]) None[source]¶
Report every axiom id that names no node of the graph.
An error, like a dangling edge: nothing legitimate produces one. The OWL importer makes a node of every IRI a triple mentions, including an undeclared
rdfs:subPropertyOf foaf:knowstarget, and the editor prunes the axioms of the nodes it deletes.
OWL axiom records attached to a KnowledgeGraph.
Some OWL/OWL2 constructs don’t naturally belong on a single node or edge:
owl:equivalentClass relates sets of classes; owl:disjointUnionOf
relates a class to a list of classes; owl:propertyChainAxiom relates a
property to an ordered list of properties; owl:hasKey relates a class to
a list of properties; etc.
This module reifies those constructs into small classes kept on
KnowledgeGraph.axioms. Each axiom carries node/edge ids (strings),
not direct references — this keeps axioms JSON-friendly and decoupled from
the in-memory node identities, mirroring how the metamodel keeps edge
endpoints by id when serialised.
Like the rest of the metamodel, the fields are private attributes behind
validating setters (see KGEdge): an id must
be a non-empty str (as KGNode.id must) and a list of ids a list of
them, and a bad value fails at the assignment instead of surfacing later in a
converter. The single ids an axiom is about are required constructor
arguments; only the lists, which may be empty, and ImportAxiom’s
source_ontology_iri have defaults.
Each class lists its fields, in constructor order, in FIELDS;
KGAxiom.to_dict() and the serialisers are driven by it. A field a
serialised axiom may leave out is listed in OPTIONAL_FIELDS. Every field
names a node of the graph unless the class lists it in NON_NODE_FIELDS;
NODE_REF_FIELDS is derived from the two when the class is defined, so a new
axiom class gets its references checked by KGAxiom.referenced_ids() and
KnowledgeGraph.validate without having to opt in.
The records are informational: the deterministic KG → BUML class diagram
converter reads them in order to surface preflight issues and to lift
constructs into BUML where appropriate (e.g., owl:FunctionalProperty
becomes max=1 on the corresponding attribute). They never silently
change the BUML output without going through the preflight pipeline.
- class besser.BUML.metamodel.kg.axioms.KGAxiom[source]¶
Bases:
objectBase class for all axiom records.
Subclasses carry the typed payload; this base exists so a single
KnowledgeGraph.axioms: List[KGAxiom]field can hold any of them, and gives them value semantics (==,repr,to_dict).-
FIELDS : ClassVar[Tuple[str, ...]] =
()¶ Field names in constructor order. Declared by each subclass.
-
OPTIONAL_FIELDS : ClassVar[Tuple[str, ...]] =
()¶ The fields a serialised axiom may omit (the constructor has a default for them).
-
NON_NODE_FIELDS : ClassVar[Tuple[str, ...]] =
()¶ The fields that do not name nodes of the graph (e.g. ontology IRIs).
-
NODE_REF_FIELDS : ClassVar[Tuple[str, ...]] =
()¶ The fields whose ids name nodes of the graph (an id, or a list of them):
FIELDSminusNON_NODE_FIELDS. Derived, never declared.
-
FIELDS : ClassVar[Tuple[str, ...]] =
-
class besser.BUML.metamodel.kg.axioms.EquivalentClassesAxiom(class_ids: list[str] | None =
None)[source]¶ Bases:
KGAxiomowl:equivalentClassbetween two or more classes.All listed class ids are semantically equivalent (sameInstances).
-
class besser.BUML.metamodel.kg.axioms.EquivalentPropertiesAxiom(property_ids: list[str] | None =
None)[source]¶ Bases:
KGAxiomowl:equivalentPropertybetween two or more properties.All listed property ids are semantically equivalent and canonicalize onto a single B-UML attribute/association during KG → class-diagram conversion.
-
class besser.BUML.metamodel.kg.axioms.DisjointClassesAxiom(class_ids: list[str] | None =
None)[source]¶ Bases:
KGAxiomowl:disjointWith/owl:AllDisjointClassesaxiom.The listed classes are pairwise disjoint (no shared instances).
-
class besser.BUML.metamodel.kg.axioms.DisjointUnionAxiom(union_class_id: str, part_class_ids: list[str] | None =
None)[source]¶ Bases:
KGAxiomowl:disjointUnionOf: the union class is the disjoint union of its parts.
- class besser.BUML.metamodel.kg.axioms.SubPropertyOfAxiom(sub_property_id: str, super_property_id: str)[source]¶
Bases:
KGAxiomrdfs:subPropertyOfbetween two properties (sub ⊑ super).
- class besser.BUML.metamodel.kg.axioms.InversePropertiesAxiom(property_a_id: str, property_b_id: str)[source]¶
Bases:
KGAxiomowl:inverseOfbetween two object properties.
-
class besser.BUML.metamodel.kg.axioms.PropertyChainAxiom(property_id: str, chain_property_ids: list[str] | None =
None)[source]¶ Bases:
KGAxiomowl:propertyChainAxiom: a property is the composition of an ordered chain.Example:
hasUncle← (hasParent,hasBrother).
-
class besser.BUML.metamodel.kg.axioms.HasKeyAxiom(class_id: str, property_ids: list[str] | None =
None)[source]¶ Bases:
KGAxiomowl:hasKey: the listed properties uniquely identify instances of the class.-
FIELDS : ClassVar[Tuple[str, ...]] =
('class_id', 'property_ids')¶ Field names in constructor order. Declared by each subclass.
-
FIELDS : ClassVar[Tuple[str, ...]] =
-
class besser.BUML.metamodel.kg.axioms.ImportAxiom(target_iri: str, source_ontology_iri: str | None =
None)[source]¶ Bases:
KGAxiomowl:imports: the source ontology imports another by IRI.The importer does not follow these references; this record exists so the UI can surface the dependency to the user.
-
NODE_REF_FIELDS : ClassVar[Tuple[str, ...]] =
()¶ The fields whose ids name nodes of the graph (an id, or a list of them):
FIELDSminusNON_NODE_FIELDS. Derived, never declared.
-
FIELDS : ClassVar[Tuple[str, ...]] =
('target_iri', 'source_ontology_iri')¶ Field names in constructor order. Declared by each subclass.
-
OPTIONAL_FIELDS : ClassVar[Tuple[str, ...]] =
('source_ontology_iri',)¶ The fields a serialised axiom may omit (the constructor has a default for them).
-
NODE_REF_FIELDS : ClassVar[Tuple[str, ...]] =
Normalised constraint specifications for KG NodeConstraint / PropertyConstraint.
A constraint spec captures a single OWL2/SHACL constraint in a vocabulary-
agnostic form. Specs live in KGNodeConstraint.metadata['constraintSpecs']
or KGPropertyConstraint.metadata['constraintSpecs'] as plain dicts (so the
existing JSON round-trip plumbing keeps working); is_valid_spec() is the
structural check. There is deliberately no spec class: nothing needs one, and a
dataclass next to the dicts would be a second schema to keep in step.
A spec dict has these keys:
kindThe discriminator; a key of
CONSTRAINT_VOCAB_MAP.valueIts shape depends on
kind:integer kinds (
minCardinality,maxLength…):intIRI kinds (
datatype,hasValueIRIs):strlist kinds (
oneOf,in,unionOf…):List[Any]nested kinds (
shaclAnd,shaclOr…):List[Dict]of nested specshasValuemay also carry{"value": "x", "datatype": "...", "language": "en"}for literal values
on_classPopulated for qualified cardinality (
owl:onClass/sh:qualifiedValueShape); otherwise absent.vocab_prefAn explicit per-spec vocabulary override. When absent, the exporter picks any vocabulary listed in
CONSTRAINT_VOCAB_MAPthat is compatible with the user’s export-time choice.
The CONSTRAINT_VOCAB_MAP table is the single source of truth that
the importer, exporter, and validation layers consult to decide which
vocabularies a given kind can be serialised in. The frontend mirrors this
table in constraint-catalog.ts.
-
besser.BUML.metamodel.kg.constraint_specs.LOGICAL_KINDS : set =
{'shaclAnd', 'shaclNot', 'shaclOr', 'shaclXone'}¶ The four SHACL Core logical-operator kinds. Their
valueis a list ofKG_NESTED_SHAPEdicts (each either{"ref": <node-id>}or{"specs": [<inline constraint specs>]});shaclNotcarries exactly one entry, the others carry zero or more.
-
besser.BUML.metamodel.kg.constraint_specs.OWL_RESTRICTION_PREDICATES : Dict[str, str] =
{'allValuesFrom': 'http://www.w3.org/2002/07/owl#allValuesFrom', 'exactCardinality': 'http://www.w3.org/2002/07/owl#cardinality', 'exactQualifiedCardinality': 'http://www.w3.org/2002/07/owl#qualifiedCardinality', 'hasSelf': 'http://www.w3.org/2002/07/owl#hasSelf', 'hasValue': 'http://www.w3.org/2002/07/owl#hasValue', 'maxCardinality': 'http://www.w3.org/2002/07/owl#maxCardinality', 'maxQualifiedCardinality': 'http://www.w3.org/2002/07/owl#maxQualifiedCardinality', 'minCardinality': 'http://www.w3.org/2002/07/owl#minCardinality', 'minQualifiedCardinality': 'http://www.w3.org/2002/07/owl#minQualifiedCardinality', 'someValuesFrom': 'http://www.w3.org/2002/07/owl#someValuesFrom'}¶ OWL restriction spec kind -> the predicate carrying its value.
-
besser.BUML.metamodel.kg.constraint_specs.SHACL_PROPERTY_COMPONENTS : Dict[str, str] =
{'http://www.w3.org/ns/shacl#class': 'allValuesFrom', 'http://www.w3.org/ns/shacl#datatype': 'datatype', 'http://www.w3.org/ns/shacl#deactivated': 'shaclDeactivated', 'http://www.w3.org/ns/shacl#description': 'shaclDescription', 'http://www.w3.org/ns/shacl#equals': 'equals', 'http://www.w3.org/ns/shacl#flags': 'flags', 'http://www.w3.org/ns/shacl#group': 'shaclGroup', 'http://www.w3.org/ns/shacl#hasValue': 'hasValue', 'http://www.w3.org/ns/shacl#in': 'in', 'http://www.w3.org/ns/shacl#languageIn': 'languageIn', 'http://www.w3.org/ns/shacl#lessThan': 'lessThan', 'http://www.w3.org/ns/shacl#lessThanOrEquals': 'lessThanOrEquals', 'http://www.w3.org/ns/shacl#maxCount': 'maxCardinality', 'http://www.w3.org/ns/shacl#maxExclusive': 'maxExclusive', 'http://www.w3.org/ns/shacl#maxInclusive': 'maxInclusive', 'http://www.w3.org/ns/shacl#maxLength': 'maxLength', 'http://www.w3.org/ns/shacl#message': 'shaclMessage', 'http://www.w3.org/ns/shacl#minCount': 'minCardinality', 'http://www.w3.org/ns/shacl#minExclusive': 'minExclusive', 'http://www.w3.org/ns/shacl#minInclusive': 'minInclusive', 'http://www.w3.org/ns/shacl#minLength': 'minLength', 'http://www.w3.org/ns/shacl#name': 'shaclName', 'http://www.w3.org/ns/shacl#nodeKind': 'nodeKind', 'http://www.w3.org/ns/shacl#order': 'shaclOrder', 'http://www.w3.org/ns/shacl#pattern': 'pattern', 'http://www.w3.org/ns/shacl#severity': 'shaclSeverity', 'http://www.w3.org/ns/shacl#uniqueLang': 'uniqueLang'}¶ SHACL constraint component a shape of either kind can carry -> its spec kind. The SHACL qualified counts are not here: they stay raw edges.
-
besser.BUML.metamodel.kg.constraint_specs.SHACL_NODE_COMPONENTS : Dict[str, str] =
{'http://www.w3.org/ns/shacl#closed': 'shaclClosed', 'http://www.w3.org/ns/shacl#deactivated': 'shaclDeactivated', 'http://www.w3.org/ns/shacl#description': 'shaclDescription', 'http://www.w3.org/ns/shacl#disjoint': 'shaclDisjoint', 'http://www.w3.org/ns/shacl#ignoredProperties': 'shaclIgnoredProperties', 'http://www.w3.org/ns/shacl#message': 'shaclMessage', 'http://www.w3.org/ns/shacl#name': 'shaclName', 'http://www.w3.org/ns/shacl#severity': 'shaclSeverity'}¶ SHACL component only a node shape carries (closure, plus the shape-level meta it shares with property shapes) -> its spec kind.
- besser.BUML.metamodel.kg.constraint_specs.is_valid_spec(spec: Any) bool[source]¶
Cheap structural validation used by KGNodeConstraint / KGPropertyConstraint setters.
Logical-operator specs (
shaclNot/shaclAnd/shaclOr/shaclXone) additionally require theirvalueto be a list of valid nested shapes;shaclNotis further pinned to a single entry. Other kinds are accepted on the basis of thekinddiscriminator alone — value-shape checks are the UI’s responsibility (catalog-driven) and the exporter’s responsibility (skip unknown shapes safely).
- besser.BUML.metamodel.kg.constraint_specs.spec_folded_predicates(node: Any) frozenset[str][source]¶
The predicates whose value
node’sconstraintSpecshold.For an OWL restriction: its cardinality or filler and the qualified
owl:onClass; for a class expression: its operator (owl:unionOf,owl:intersectionOf,owl:oneOf,owl:complementOf); for a SHACL shape: every component with a spec kind (sh:qualifiedValueShapeand the qualified counts are not folded and stay raw edges). The spec is what the editor edits, so it is the only stored copy: the importer keeps no raw edge (and flattens no list) with these predicates, and the exporter and the projection write them from the spec, ignoring any such edge drawn by hand. Empty for any node that is not a constraint node.