Skip to content

Schema

knowledgecomplex.schema — SchemaBuilder and vocab/text descriptors.

Public API. Never exposes rdflib, pyshacl, or owlrl objects.

Internal structure mirrors the 2x2 responsibility map: {topological, ontological} x {OWL, SHACL}

The core ontology defines KC:Element as the base class for all simplices, with KC:Vertex (k=0), KC:Edge (k=1), KC:Face (k=2) as subclasses. add_vertex_type / add_edge_type / add_face_type each declare a user type as a subclass of the appropriate simplex class and write to both internal OWL and SHACL graphs.

dump_owl() and dump_shacl() return merged (core + user) Turtle strings.

Codec

Bases: Protocol

Bidirectional bridge between element records and artifacts at URIs.

A codec pairs compile (map → territory) and decompile (territory → map) for a given element type. Registered on KnowledgeComplex instances via register_codec(), and inherited by child types.

Source code in knowledgecomplex/schema.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@runtime_checkable
class Codec(Protocol):
    """
    Bidirectional bridge between element records and artifacts at URIs.

    A codec pairs compile (map → territory) and decompile (territory → map)
    for a given element type. Registered on KnowledgeComplex instances via
    register_codec(), and inherited by child types.
    """

    def compile(self, element: dict) -> None:
        """
        Write an element record to the artifact at its URI.

        Parameters
        ----------
        element : dict
            Keys: id, type, uri, plus all attribute key-value pairs.
        """
        ...

    def decompile(self, uri: str) -> dict:
        """
        Read the artifact at a URI and return an attribute dict.

        Parameters
        ----------
        uri : str
            The URI of the artifact to read.

        Returns
        -------
        dict
            Attribute key-value pairs suitable for add_vertex/add_edge/add_face kwargs.
        """
        ...

compile(element)

Write an element record to the artifact at its URI.

Parameters:

Name Type Description Default
element dict

Keys: id, type, uri, plus all attribute key-value pairs.

required
Source code in knowledgecomplex/schema.py
49
50
51
52
53
54
55
56
57
58
def compile(self, element: dict) -> None:
    """
    Write an element record to the artifact at its URI.

    Parameters
    ----------
    element : dict
        Keys: id, type, uri, plus all attribute key-value pairs.
    """
    ...

decompile(uri)

Read the artifact at a URI and return an attribute dict.

Parameters:

Name Type Description Default
uri str

The URI of the artifact to read.

required

Returns:

Type Description
dict

Attribute key-value pairs suitable for add_vertex/add_edge/add_face kwargs.

Source code in knowledgecomplex/schema.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def decompile(self, uri: str) -> dict:
    """
    Read the artifact at a URI and return an attribute dict.

    Parameters
    ----------
    uri : str
        The URI of the artifact to read.

    Returns
    -------
    dict
        Attribute key-value pairs suitable for add_vertex/add_edge/add_face kwargs.
    """
    ...

VocabDescriptor dataclass

Returned by vocab(). Carries the allowed string values for an attribute. Generates both an OWL rdfs:comment annotation and a SHACL sh:in constraint when passed to add_*_type().

Source code in knowledgecomplex/schema.py
77
78
79
80
81
82
83
84
85
86
87
88
89
@dataclass(frozen=True)
class VocabDescriptor:
    """
    Returned by vocab(). Carries the allowed string values for an attribute.
    Generates both an OWL rdfs:comment annotation and a SHACL sh:in constraint
    when passed to add_*_type().
    """
    values: tuple[str, ...]
    multiple: bool = False

    def __repr__(self) -> str:
        suffix = ", multiple=True" if self.multiple else ""
        return f"vocab({', '.join(repr(v) for v in self.values)}{suffix})"

TextDescriptor dataclass

Returned by text(). Marks an attribute as a free-text string (no controlled vocabulary). Generates an OWL DatatypeProperty with xsd:string range and a SHACL property shape with sh:datatype xsd:string but no sh:in constraint.

Source code in knowledgecomplex/schema.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@dataclass(frozen=True)
class TextDescriptor:
    """
    Returned by text(). Marks an attribute as a free-text string (no controlled vocabulary).
    Generates an OWL DatatypeProperty with xsd:string range and a SHACL property shape
    with sh:datatype xsd:string but no sh:in constraint.
    """
    required: bool = True
    multiple: bool = False

    def __repr__(self) -> str:
        parts = []
        if not self.required:
            parts.append("required=False")
        if self.multiple:
            parts.append("multiple=True")
        return f"text({', '.join(parts)})"

SchemaBuilder

Author a knowledge complex schema: vertex types, edge types, face types.

Each add_*_type call declares a new OWL subclass of the appropriate KC:Element subclass (Vertex, Edge, or Face) and creates a corresponding SHACL node shape. Both OWL and SHACL graphs are maintained internally. dump_owl() / dump_shacl() return the full merged Turtle strings.

Parameters:

Name Type Description Default
namespace str

Short namespace token for user-defined classes and properties. Used to build IRI prefix: https://example.org/{namespace}#

required
Example

sb = SchemaBuilder(namespace="aaa") sb.add_vertex_type("spec") sb.add_edge_type("verification", ... attributes={"status": vocab("passing", "failing", "pending")}) sb.add_face_type("assurance") owl_ttl = sb.dump_owl() shacl_ttl = sb.dump_shacl()

Source code in knowledgecomplex/schema.py
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
class SchemaBuilder:
    """
    Author a knowledge complex schema: vertex types, edge types, face types.

    Each add_*_type call declares a new OWL subclass of the appropriate
    KC:Element subclass (Vertex, Edge, or Face) and creates a corresponding
    SHACL node shape. Both OWL and SHACL graphs are maintained internally.
    dump_owl() / dump_shacl() return the full merged Turtle strings.

    Parameters
    ----------
    namespace : str
        Short namespace token for user-defined classes and properties.
        Used to build IRI prefix: https://example.org/{namespace}#

    Example
    -------
    >>> sb = SchemaBuilder(namespace="aaa")
    >>> sb.add_vertex_type("spec")
    >>> sb.add_edge_type("verification",
    ...     attributes={"status": vocab("passing", "failing", "pending")})
    >>> sb.add_face_type("assurance")
    >>> owl_ttl = sb.dump_owl()
    >>> shacl_ttl = sb.dump_shacl()
    """

    def __init__(self, namespace: str) -> None:
        self._namespace = namespace
        self._base_iri = f"https://example.org/{namespace}#"
        # Internal namespace objects
        self._ns = Namespace(self._base_iri)
        self._nss = Namespace(f"https://example.org/{namespace}/shape#")
        # Internal graphs — never exposed publicly
        self._owl_graph: Any = None   # rdflib.Graph, populated in _init_graphs()
        self._shacl_graph: Any = None # rdflib.Graph, populated in _init_graphs()
        self._types: dict[str, dict] = {}  # registry: name -> {kind, attributes}
        self._attr_domains: dict[str, URIRef | None] = {}  # attr name → first domain or None if shared
        self._queries: dict[str, str] = {}  # name -> SPARQL template string
        self._init_graphs()

    def __repr__(self) -> str:
        return f"SchemaBuilder(namespace={self._namespace!r}, types={len(self._types)})"

    def _init_graphs(self) -> None:
        """Load core OWL and SHACL static resources into internal graphs."""
        self._owl_graph = Graph()
        self._owl_graph.parse(str(_CORE_OWL), format="turtle")

        self._shacl_graph = Graph()
        self._shacl_graph.parse(str(_CORE_SHAPES), format="turtle")

        # Bind prefixes on both graphs
        for g in (self._owl_graph, self._shacl_graph):
            g.bind("kc", _KC)
            g.bind("kcs", _KCS)
            g.bind("sh", _SH)
            g.bind("owl", OWL)
            g.bind("rdfs", RDFS)
            g.bind("rdf", RDF)
            g.bind("xsd", XSD)
            g.bind(self._namespace, self._ns)
            g.bind(f"{self._namespace}s", self._nss)

    def _set_owl_domain(self, attr_iri: URIRef, attr_name: str, type_iri: URIRef) -> None:
        """Set rdfs:domain for a property, removing it if shared across types.

        When a property appears on multiple types, setting multiple rdfs:domain
        values causes RDFS inference to classify any individual with that property
        as a member of ALL domain types — leading to spurious SHACL cross-type
        violations. If the property already has a domain for a different type,
        we remove all domain assertions (SHACL shapes handle per-type enforcement).
        """
        if attr_name not in self._attr_domains:
            # First time seeing this attribute — set domain
            self._attr_domains[attr_name] = type_iri
            self._owl_graph.add((attr_iri, RDFS.domain, type_iri))
        elif self._attr_domains[attr_name] is not None and self._attr_domains[attr_name] != type_iri:
            # Shared across types — remove existing domain
            self._owl_graph.remove((attr_iri, RDFS.domain, None))
            self._attr_domains[attr_name] = None
        # else: already None (shared) or same type — no action needed

    def _add_vocab_attr_to_graphs(
        self,
        type_iri: URIRef,
        shape_iri: URIRef,
        attr_name: str,
        vocab_desc: VocabDescriptor,
        required: bool,
    ) -> None:
        """Add a vocab attribute's OWL property and SHACL property shape (with sh:in)."""
        attr_iri = self._ns[attr_name]

        # OWL: declare data property
        self._owl_graph.add((attr_iri, RDF.type, OWL.DatatypeProperty))
        self._set_owl_domain(attr_iri, attr_name, type_iri)
        self._owl_graph.add((attr_iri, RDFS.range, XSD.string))
        self._owl_graph.add((attr_iri, RDFS.comment,
                             Literal(f"Allowed values: {', '.join(vocab_desc.values)}")))

        # SHACL: create property shape
        prop_shape = BNode()
        self._shacl_graph.add((shape_iri, _SH.property, prop_shape))
        self._shacl_graph.add((prop_shape, _SH.path, attr_iri))
        self._shacl_graph.add((prop_shape, _SH.datatype, XSD.string))
        self._shacl_graph.add((prop_shape, _SH.minCount, Literal(1 if required else 0)))
        if not vocab_desc.multiple:
            self._shacl_graph.add((prop_shape, _SH.maxCount, Literal(1)))

        # sh:in list
        list_node = BNode()
        self._shacl_graph.add((prop_shape, _SH["in"], list_node))
        Collection(self._shacl_graph, list_node,
                   [Literal(v) for v in vocab_desc.values])

    def _add_text_attr_to_graphs(
        self,
        type_iri: URIRef,
        shape_iri: URIRef,
        attr_name: str,
        text_desc: TextDescriptor,
    ) -> None:
        """Add a free-text attribute's OWL property and SHACL property shape (no sh:in)."""
        attr_iri = self._ns[attr_name]

        # OWL: declare data property
        self._owl_graph.add((attr_iri, RDF.type, OWL.DatatypeProperty))
        self._set_owl_domain(attr_iri, attr_name, type_iri)
        self._owl_graph.add((attr_iri, RDFS.range, XSD.string))

        # SHACL: create property shape
        prop_shape = BNode()
        self._shacl_graph.add((shape_iri, _SH.property, prop_shape))
        self._shacl_graph.add((prop_shape, _SH.path, attr_iri))
        self._shacl_graph.add((prop_shape, _SH.datatype, XSD.string))
        self._shacl_graph.add((prop_shape, _SH.minCount,
                               Literal(1 if text_desc.required else 0)))
        if not text_desc.multiple:
            self._shacl_graph.add((prop_shape, _SH.maxCount, Literal(1)))

    def _add_attr_to_graphs(
        self,
        type_iri: URIRef,
        shape_iri: URIRef,
        attr_name: str,
        descriptor: VocabDescriptor | TextDescriptor,
        required: bool | None = None,
    ) -> None:
        """Dispatch to the appropriate attr handler based on descriptor type."""
        if isinstance(descriptor, TextDescriptor):
            self._add_text_attr_to_graphs(type_iri, shape_iri, attr_name, descriptor)
        elif isinstance(descriptor, VocabDescriptor):
            if required is None:
                required = True
            self._add_vocab_attr_to_graphs(type_iri, shape_iri, attr_name, descriptor, required)
        else:
            raise TypeError(f"Unknown attribute descriptor: {type(descriptor)}")

    def _dispatch_attr(
        self,
        type_iri: URIRef,
        shape_iri: URIRef,
        attr_name: str,
        attr_spec: VocabDescriptor | TextDescriptor | dict,
    ) -> None:
        """Route an attribute spec to the correct graph-writing method."""
        if isinstance(attr_spec, (VocabDescriptor, TextDescriptor)):
            self._add_attr_to_graphs(type_iri, shape_iri, attr_name, attr_spec)
        elif isinstance(attr_spec, dict):
            if "vocab" in attr_spec:
                vd = attr_spec["vocab"]
                req = attr_spec.get("required", True)
                self._add_attr_to_graphs(type_iri, shape_iri, attr_name, vd, required=req)
            elif "text" in attr_spec:
                td = attr_spec["text"]
                self._add_attr_to_graphs(type_iri, shape_iri, attr_name, td)
            else:
                raise TypeError(f"Attribute dict must have 'vocab' or 'text' key: {attr_spec}")
        else:
            raise TypeError(f"Unknown attribute spec type: {type(attr_spec)}")

    def _validate_parent(self, parent: str | None, expected_kind: str) -> None:
        """Validate parent type exists and has the correct kind."""
        from knowledgecomplex.exceptions import SchemaError
        if parent is None:
            return
        if parent not in self._types:
            raise SchemaError(f"Parent type '{parent}' is not registered")
        if self._types[parent]["kind"] != expected_kind:
            raise SchemaError(
                f"Parent type '{parent}' is kind '{self._types[parent]['kind']}', "
                f"expected '{expected_kind}'"
            )

    def _collect_inherited_attributes(self, type_name: str) -> dict:
        """Walk the parent chain and collect all inherited attributes."""
        inherited = {}
        current = self._types[type_name].get("parent")
        while current is not None:
            parent_attrs = self._types[current].get("attributes", {})
            # Earlier ancestors are overridden by closer ancestors
            for k, v in parent_attrs.items():
                if k not in inherited:
                    inherited[k] = v
            current = self._types[current].get("parent")
        return inherited

    def _validate_bind(
        self,
        bind: dict[str, str],
        all_attributes: dict,
    ) -> None:
        """Validate that bind keys exist in all_attributes and values are legal."""
        from knowledgecomplex.exceptions import SchemaError
        for attr_name, bound_value in bind.items():
            if attr_name not in all_attributes:
                raise SchemaError(
                    f"Cannot bind '{attr_name}': attribute not found on this type or its ancestors"
                )
            descriptor = all_attributes[attr_name]
            # Unwrap dict-style descriptors
            if isinstance(descriptor, dict):
                descriptor = descriptor.get("vocab") or descriptor.get("text")
            if isinstance(descriptor, VocabDescriptor):
                if bound_value not in descriptor.values:
                    raise SchemaError(
                        f"Cannot bind '{attr_name}' to '{bound_value}': "
                        f"not in allowed values {descriptor.values}"
                    )

    def _apply_bind(self, shape_iri: URIRef, bind: dict[str, str]) -> None:
        """Add sh:hasValue + sh:minCount 1 constraints for bound attributes."""
        for attr_name, bound_value in bind.items():
            attr_iri = self._ns[attr_name]
            prop_shape = BNode()
            self._shacl_graph.add((shape_iri, _SH.property, prop_shape))
            self._shacl_graph.add((prop_shape, _SH.path, attr_iri))
            self._shacl_graph.add((prop_shape, _SH.hasValue, Literal(bound_value)))
            self._shacl_graph.add((prop_shape, _SH.minCount, Literal(1)))

    def add_vertex_type(
        self,
        name: str,
        attributes: dict[str, VocabDescriptor | TextDescriptor | Any] | None = None,
        parent: str | None = None,
        bind: dict[str, str] | None = None,
    ) -> "SchemaBuilder":
        """
        Declare a new vertex type (OWL subclass of KC:Vertex + SHACL node shape).

        Parameters
        ----------
        name : str
            Class name within the user namespace.
        attributes : dict, optional
            Mapping of attribute name to descriptor (VocabDescriptor, TextDescriptor,
            or dict with "vocab"/"text" key and optional "required" flag).
        parent : str, optional
            Name of a registered vertex type to inherit from.
        bind : dict, optional
            Mapping of attribute names to fixed string values (sh:hasValue).

        Returns
        -------
        SchemaBuilder (self, for chaining)
        """
        from knowledgecomplex.exceptions import SchemaError
        if name in self._types:
            raise SchemaError(f"Type '{name}' is already registered")
        self._validate_parent(parent, "vertex")
        attributes = attributes or {}
        bind = bind or {}

        self._types[name] = {
            "kind": "vertex",
            "attributes": dict(attributes),
            "parent": parent,
            "bind": dict(bind),
        }

        # Validate bind against all attributes (own + inherited)
        if bind:
            inherited = self._collect_inherited_attributes(name)
            all_attrs = {**inherited, **attributes}
            self._validate_bind(bind, all_attrs)

        type_iri = self._ns[name]
        shape_iri = self._nss[f"{name}Shape"]

        # OWL
        superclass = self._ns[parent] if parent else _KC.Vertex
        self._owl_graph.add((type_iri, RDF.type, OWL.Class))
        self._owl_graph.add((type_iri, RDFS.subClassOf, superclass))

        # SHACL
        self._shacl_graph.add((shape_iri, RDF.type, _SH.NodeShape))
        self._shacl_graph.add((shape_iri, _SH.targetClass, type_iri))

        for attr_name, attr_spec in attributes.items():
            self._dispatch_attr(type_iri, shape_iri, attr_name, attr_spec)

        if bind:
            self._apply_bind(shape_iri, bind)

        return self

    def add_edge_type(
        self,
        name: str,
        attributes: dict[str, VocabDescriptor | TextDescriptor | Any] | None = None,
        parent: str | None = None,
        bind: dict[str, str] | None = None,
    ) -> "SchemaBuilder":
        """
        Declare a new edge type (OWL subclass of KC:Edge + SHACL property shapes).

        Parameters
        ----------
        name : str
            Class name within the user namespace.
        attributes : dict, optional
            Mapping of attribute name to descriptor (VocabDescriptor, TextDescriptor,
            or dict with "vocab"/"text" key and optional "required" flag).
        parent : str, optional
            Name of a registered edge type to inherit from.
        bind : dict, optional
            Mapping of attribute names to fixed string values (sh:hasValue).

        Returns
        -------
        SchemaBuilder (self, for chaining)
        """
        from knowledgecomplex.exceptions import SchemaError
        if name in self._types:
            raise SchemaError(f"Type '{name}' is already registered")
        self._validate_parent(parent, "edge")
        attributes = attributes or {}
        bind = bind or {}

        self._types[name] = {
            "kind": "edge",
            "attributes": dict(attributes),
            "parent": parent,
            "bind": dict(bind),
        }

        if bind:
            inherited = self._collect_inherited_attributes(name)
            all_attrs = {**inherited, **attributes}
            self._validate_bind(bind, all_attrs)

        type_iri = self._ns[name]
        shape_iri = self._nss[f"{name}Shape"]

        # OWL
        superclass = self._ns[parent] if parent else _KC.Edge
        self._owl_graph.add((type_iri, RDF.type, OWL.Class))
        self._owl_graph.add((type_iri, RDFS.subClassOf, superclass))

        # SHACL
        self._shacl_graph.add((shape_iri, RDF.type, _SH.NodeShape))
        self._shacl_graph.add((shape_iri, _SH.targetClass, type_iri))

        for attr_name, attr_spec in attributes.items():
            self._dispatch_attr(type_iri, shape_iri, attr_name, attr_spec)

        if bind:
            self._apply_bind(shape_iri, bind)

        return self

    def add_face_type(
        self,
        name: str,
        attributes: dict[str, Any] | None = None,
        parent: str | None = None,
        bind: dict[str, str] | None = None,
    ) -> "SchemaBuilder":
        """
        Declare a new face type (OWL subclass of KC:Face + SHACL property shapes).

        Attributes with ``required=False`` generate sh:minCount 0 constraints.

        Parameters
        ----------
        name : str
            Class name within the user namespace.
        attributes : dict, optional
            Mapping of attribute name to descriptor (VocabDescriptor, TextDescriptor,
            or dict with "vocab"/"text" key and optional "required" flag).
        parent : str, optional
            Name of a registered face type to inherit from.
        bind : dict, optional
            Mapping of attribute names to fixed string values (sh:hasValue).

        Returns
        -------
        SchemaBuilder (self, for chaining)
        """
        from knowledgecomplex.exceptions import SchemaError
        if name in self._types:
            raise SchemaError(f"Type '{name}' is already registered")
        self._validate_parent(parent, "face")
        attributes = attributes or {}
        bind = bind or {}

        self._types[name] = {
            "kind": "face",
            "attributes": dict(attributes),
            "parent": parent,
            "bind": dict(bind),
        }

        if bind:
            inherited = self._collect_inherited_attributes(name)
            all_attrs = {**inherited, **attributes}
            self._validate_bind(bind, all_attrs)

        type_iri = self._ns[name]
        shape_iri = self._nss[f"{name}Shape"]

        # OWL
        superclass = self._ns[parent] if parent else _KC.Face
        self._owl_graph.add((type_iri, RDF.type, OWL.Class))
        self._owl_graph.add((type_iri, RDFS.subClassOf, superclass))

        # SHACL
        self._shacl_graph.add((shape_iri, RDF.type, _SH.NodeShape))
        self._shacl_graph.add((shape_iri, _SH.targetClass, type_iri))

        for attr_name, attr_spec in attributes.items():
            self._dispatch_attr(type_iri, shape_iri, attr_name, attr_spec)

        if bind:
            self._apply_bind(shape_iri, bind)

        return self

    def describe_type(self, name: str) -> dict:
        """
        Inspect a registered type's attributes, parent, and bindings.

        Parameters
        ----------
        name : str
            The registered type name.

        Returns
        -------
        dict
            Keys: name, kind, parent, own_attributes, inherited_attributes,
            all_attributes, bound.
        """
        from knowledgecomplex.exceptions import SchemaError
        if name not in self._types:
            raise SchemaError(f"Type '{name}' is not registered")

        info = self._types[name]
        own_attrs = dict(info.get("attributes", {}))
        inherited_attrs = self._collect_inherited_attributes(name)
        # Collect bindings from ancestors
        inherited_bind = {}
        current = info.get("parent")
        while current is not None:
            parent_bind = self._types[current].get("bind", {})
            for k, v in parent_bind.items():
                if k not in inherited_bind:
                    inherited_bind[k] = v
            current = self._types[current].get("parent")
        own_bind = dict(info.get("bind", {}))
        all_bind = {**inherited_bind, **own_bind}

        all_attrs = {**inherited_attrs, **own_attrs}
        return {
            "name": name,
            "kind": info["kind"],
            "parent": info.get("parent"),
            "own_attributes": own_attrs,
            "inherited_attributes": inherited_attrs,
            "all_attributes": all_attrs,
            "bound": all_bind,
        }

    def type_names(self, kind: str | None = None) -> list[str]:
        """
        List registered type names, optionally filtered by kind.

        Parameters
        ----------
        kind : str, optional
            Filter by "vertex", "edge", or "face".

        Returns
        -------
        list[str]
        """
        if kind is None:
            return list(self._types.keys())
        return [n for n, info in self._types.items() if info["kind"] == kind]

    def promote_to_attribute(
        self,
        type: str,
        attribute: str,
        vocab: VocabDescriptor | None = None,
        text: TextDescriptor | None = None,
        required: bool = True,
    ) -> "SchemaBuilder":
        """
        Atomically promote a discovered pattern to a first-class typed attribute.

        Updates both OWL property definition and SHACL shape constraint for the named type.
        After calling this, dump_owl() and dump_shacl() both reflect the updated attribute.

        Parameters
        ----------
        type : str
            The type name (must have been registered via add_*_type).
        attribute : str
            Attribute name to add or upgrade.
        vocab : VocabDescriptor, optional
            Controlled vocabulary for the attribute.
        text : TextDescriptor, optional
            Free-text descriptor for the attribute.
        required : bool
            If True, generates sh:minCount 1. Overrides the descriptor's own required flag.

        Returns
        -------
        SchemaBuilder (self, for chaining)
        """
        from knowledgecomplex.exceptions import SchemaError
        if type not in self._types:
            raise SchemaError(f"Type '{type}' is not registered")
        if vocab is None and text is None:
            raise SchemaError("promote_to_attribute requires either vocab or text descriptor")

        type_iri = self._ns[type]
        shape_iri = self._nss[f"{type}Shape"]
        attr_iri = self._ns[attribute]

        # Remove existing OWL triples for this attribute (if upgrading)
        for p in (RDFS.domain, RDFS.range, RDFS.comment):
            self._owl_graph.remove((attr_iri, p, None))
        self._owl_graph.remove((attr_iri, RDF.type, OWL.DatatypeProperty))

        # Remove existing SHACL property shape for this attribute (if upgrading)
        for prop_node in list(self._shacl_graph.objects(shape_iri, _SH.property)):
            if (prop_node, _SH.path, attr_iri) in self._shacl_graph:
                # Remove the sh:in list
                list_head = self._shacl_graph.value(prop_node, _SH["in"])
                if list_head is not None:
                    Collection(self._shacl_graph, list_head).clear()
                    self._shacl_graph.remove((prop_node, _SH["in"], list_head))
                # Remove all triples about this property shape
                for p, o in list(self._shacl_graph.predicate_objects(prop_node)):
                    self._shacl_graph.remove((prop_node, p, o))
                self._shacl_graph.remove((shape_iri, _SH.property, prop_node))

        # Re-add with new settings
        if vocab is not None:
            self._add_attr_to_graphs(type_iri, shape_iri, attribute, vocab, required=required)
        else:
            # Override the text descriptor's required flag with the promote call's value
            effective = TextDescriptor(required=required, multiple=text.multiple)
            self._add_attr_to_graphs(type_iri, shape_iri, attribute, effective)

        # Update type registry
        if "attributes" not in self._types[type]:
            self._types[type]["attributes"] = {}
        if vocab is not None:
            self._types[type]["attributes"][attribute] = {
                "vocab": vocab, "required": required
            }
        else:
            self._types[type]["attributes"][attribute] = text

        return self

    def add_sparql_constraint(
        self,
        type_name: str,
        sparql: str,
        message: str,
    ) -> "SchemaBuilder":
        """
        Attach a sh:sparql constraint to the SHACL shape for type_name.

        The sparql argument must be a SPARQL SELECT query that returns $this
        for each violating focus node. pyshacl evaluates this and reports the
        message for each returned row.

        Parameters
        ----------
        type_name : str
            The type name (must have been registered via add_*_type).
        sparql : str
            SPARQL SELECT query. Must bind $this to each violating node.
        message : str
            Human-readable message reported when the constraint is violated.

        Returns
        -------
        SchemaBuilder (self, for chaining)
        """
        from knowledgecomplex.exceptions import SchemaError
        if type_name not in self._types:
            raise SchemaError(f"Type '{type_name}' is not registered")
        shape_iri = self._nss[f"{type_name}Shape"]
        constraint = BNode()
        self._shacl_graph.add((shape_iri, _SH.sparql, constraint))
        self._shacl_graph.add((constraint, RDF.type, _SH.SPARQLConstraint))
        self._shacl_graph.add((constraint, _SH.select, Literal(sparql)))
        self._shacl_graph.add((constraint, _SH.message, Literal(message)))
        return self

    # --- Topological query registration and constraint escalation ---

    _TOPO_PATTERNS: dict[str, tuple[str, str]] = {
        # operation -> (graph_pattern_template, result_variable)
        # {simplex_iri} is replaced by the target IRI,
        # {type_filter} by a type constraint or "".
        "boundary": (
            "{simplex_iri} kc:boundedBy ?result . {type_filter}",
            "result",
        ),
        "coboundary": (
            "?result kc:boundedBy {simplex_iri} . {type_filter}",
            "result",
        ),
        "star": (
            "?result kc:boundedBy* {simplex_iri} . {type_filter}",
            "result",
        ),
        "closure": (
            "{simplex_iri} kc:boundedBy* ?result . {type_filter}",
            "result",
        ),
        "link": (
            # closed_star minus star: elements reachable from star's closure
            # but not in the star itself
            "?star_elem kc:boundedBy* {simplex_iri} . "
            "?star_elem kc:boundedBy* ?result . "
            "FILTER NOT EXISTS {{ ?result kc:boundedBy* {simplex_iri} }} "
            "{type_filter}",
            "result",
        ),
        "degree": (
            "?result kc:boundedBy {simplex_iri} .",
            "result",
        ),
    }

    def _build_topo_sparql(
        self,
        operation: str,
        *,
        simplex_iri: str = "{simplex}",
        target_type: str | None = None,
    ) -> str:
        """Build a complete SPARQL SELECT from a topological operation.

        Parameters
        ----------
        operation :
            One of: boundary, coboundary, star, closure, link, degree.
        simplex_iri :
            IRI or placeholder for the focus element.
        target_type :
            Optional type name to filter results.

        Returns
        -------
        str
            A complete SPARQL SELECT query string.
        """
        from knowledgecomplex.exceptions import SchemaError
        if operation not in self._TOPO_PATTERNS:
            raise SchemaError(
                f"Unknown topological operation '{operation}'. "
                f"Valid: {sorted(self._TOPO_PATTERNS)}"
            )
        pattern_tmpl, result_var = self._TOPO_PATTERNS[operation]

        if target_type is not None:
            if target_type not in self._types:
                raise SchemaError(f"Type '{target_type}' is not registered")
            type_iri = self._ns[target_type]
            tf = f"?{result_var} a/rdfs:subClassOf* <{type_iri}> ."
        else:
            tf = ""

        pattern = (
            pattern_tmpl
            .replace("{simplex_iri}", simplex_iri)
            .replace("{type_filter}", tf)
        )

        return (
            f"PREFIX kc: <https://w3id.org/kc#>\n"
            f"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            f"SELECT ?{result_var} WHERE {{\n"
            f"    {pattern}\n"
            f"}}\n"
        )

    def add_query(
        self,
        name: str,
        operation: str,
        *,
        target_type: str | None = None,
    ) -> "SchemaBuilder":
        """Register a named topological query template on this schema.

        The query is generated from a topological operation and optional type
        filter, then stored internally. It is exported as a ``.sparql`` file
        by :meth:`export` and automatically loaded by
        :class:`~knowledgecomplex.graph.KnowledgeComplex` at runtime.

        Parameters
        ----------
        name : str
            Query template name (becomes the filename stem, e.g. ``"spec_coboundary"``
            exports as ``queries/spec_coboundary.sparql``).
        operation : str
            Topological operation: ``"boundary"``, ``"coboundary"``, ``"star"``,
            ``"closure"``, ``"link"``, or ``"degree"``.
        target_type : str, optional
            Filter results to this type (including subtypes via OWL class hierarchy).

        Returns
        -------
        SchemaBuilder (self, for chaining)

        Example
        -------
        >>> sb.add_query("spec_coboundary", "coboundary", target_type="verification")
        """
        sparql = self._build_topo_sparql(
            operation, simplex_iri="{simplex}", target_type=target_type,
        )
        self._queries[name] = sparql
        return self

    def add_topological_constraint(
        self,
        type_name: str,
        operation: str,
        *,
        target_type: str | None = None,
        predicate: str = "min_count",
        min_count: int = 1,
        max_count: int | None = None,
        message: str | None = None,
    ) -> "SchemaBuilder":
        """Escalate a topological query to a SHACL constraint.

        Generates a ``sh:sparql`` constraint that, for each focus node of
        *type_name*, evaluates a topological operation and checks a cardinality
        predicate. Delegates to :meth:`add_sparql_constraint`.

        Parameters
        ----------
        type_name : str
            The type to constrain (must be registered).
        operation : str
            Topological operation: ``"boundary"``, ``"coboundary"``, ``"star"``,
            ``"closure"``, ``"link"``, or ``"degree"``.
        target_type : str, optional
            Filter the topological result to this type.
        predicate : str
            ``"min_count"`` — at least *min_count* results (default).
            ``"max_count"`` — at most *max_count* results.
            ``"exact_count"`` — exactly *min_count* results.
        min_count : int
            Minimum count (used by ``"min_count"`` and ``"exact_count"``).
        max_count : int, optional
            Maximum count (used by ``"max_count"``).
        message : str, optional
            Custom violation message. Auto-generated if not provided.

        Returns
        -------
        SchemaBuilder (self, for chaining)

        Example
        -------
        >>> sb.add_topological_constraint(
        ...     "spec", "coboundary",
        ...     target_type="verification",
        ...     predicate="min_count", min_count=1,
        ...     message="Every spec must have at least one verification edge",
        ... )
        """
        from knowledgecomplex.exceptions import SchemaError
        if type_name not in self._types:
            raise SchemaError(f"Type '{type_name}' is not registered")
        if operation not in self._TOPO_PATTERNS:
            raise SchemaError(
                f"Unknown topological operation '{operation}'. "
                f"Valid: {sorted(self._TOPO_PATTERNS)}"
            )

        pattern_tmpl, result_var = self._TOPO_PATTERNS[operation]

        if target_type is not None:
            if target_type not in self._types:
                raise SchemaError(f"Type '{target_type}' is not registered")
            type_iri = self._ns[target_type]
            tf = f"?{result_var} a/rdfs:subClassOf* <{type_iri}> ."
        else:
            tf = ""

        pattern = (
            pattern_tmpl
            .replace("{simplex_iri}", "$this")
            .replace("{type_filter}", tf)
        )

        # Build the HAVING clause based on predicate
        if predicate == "min_count":
            having = f"HAVING (COUNT(DISTINCT ?{result_var}) < {min_count})"
        elif predicate == "max_count":
            if max_count is None:
                raise SchemaError("max_count predicate requires max_count parameter")
            having = f"HAVING (COUNT(DISTINCT ?{result_var}) > {max_count})"
        elif predicate == "exact_count":
            having = f"HAVING (COUNT(DISTINCT ?{result_var}) != {min_count})"
        else:
            raise SchemaError(
                f"Unknown predicate '{predicate}'. "
                f"Valid: min_count, max_count, exact_count"
            )

        # Wrap pattern in OPTIONAL so GROUP BY produces a row even when
        # there are zero matches (otherwise HAVING never fires for empty results)
        sparql = (
            f"PREFIX kc: <https://w3id.org/kc#>\n"
            f"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            f"SELECT $this WHERE {{\n"
            f"    OPTIONAL {{ {pattern} }}\n"
            f"}}\n"
            f"GROUP BY $this\n"
            f"{having}\n"
        )

        if message is None:
            target_desc = f" of type '{target_type}'" if target_type else ""
            message = (
                f"Topological constraint violated: {operation}{target_desc} "
                f"on '{type_name}' failed {predicate} check "
                f"(min={min_count}, max={max_count})"
            )

        return self.add_sparql_constraint(type_name, sparql, message)

    def dump_owl(self) -> str:
        """Return merged OWL graph (core + user schema) as a Turtle string."""
        return self._owl_graph.serialize(format="turtle")

    def dump_shacl(self) -> str:
        """Return merged SHACL graph (core shapes + user shapes) as a Turtle string."""
        return self._shacl_graph.serialize(format="turtle")

    def export(
        self,
        path: str | Path,
        query_dirs: list[Path] | None = None,
    ) -> Path:
        """
        Export the schema to a directory as standard semantic web files.

        Writes ontology.ttl (OWL) and shapes.ttl (SHACL). If query_dirs are
        provided, copies all .sparql files into a queries/ subdirectory.

        Parameters
        ----------
        path : str | Path
            Target directory. Created if it does not exist.
        query_dirs : list[Path], optional
            Directories containing .sparql query templates to include.

        Returns
        -------
        Path
            The export directory.
        """
        p = Path(path)
        p.mkdir(parents=True, exist_ok=True)
        (p / "ontology.ttl").write_text(self.dump_owl())
        (p / "shapes.ttl").write_text(self.dump_shacl())
        # Write schema-generated query templates and copy external query dirs
        if self._queries or query_dirs:
            qdir = p / "queries"
            qdir.mkdir(exist_ok=True)
            for name, sparql_text in self._queries.items():
                (qdir / f"{name}.sparql").write_text(sparql_text)
            if query_dirs:
                for d in query_dirs:
                    for sparql_file in d.glob("*.sparql"):
                        shutil.copy2(sparql_file, qdir / sparql_file.name)
        return p

    @classmethod
    def load(cls, path: str | Path) -> "SchemaBuilder":
        """
        Load a schema from a directory containing ontology.ttl and shapes.ttl.

        Reconstructs the type registry by inspecting OWL subclass triples.

        Parameters
        ----------
        path : str | Path
            Directory containing ontology.ttl and shapes.ttl.

        Returns
        -------
        SchemaBuilder
        """
        p = Path(path)

        owl_graph = Graph()
        owl_graph.parse(str(p / "ontology.ttl"), format="turtle")

        shacl_graph = Graph()
        shacl_graph.parse(str(p / "shapes.ttl"), format="turtle")

        # Discover model namespace: find a namespace binding that is not
        # one of the well-known prefixes (kc, kcs, sh, owl, rdfs, rdf, xsd)
        # Discover model namespace: find types that are subclasses of
        # kc:Vertex, kc:Edge, or kc:Face, then resolve their namespace.
        kc_bases = {_KC.Vertex, _KC.Edge, _KC.Face}
        candidate_iris: set[URIRef] = set()
        for kc_class in kc_bases:
            for subj in owl_graph.subjects(RDFS.subClassOf, kc_class):
                if subj not in kc_bases and subj != _KC.Element:
                    candidate_iris.add(subj)

        # Also find types that subclass the candidates (inheritance)
        changed = True
        while changed:
            changed = False
            for parent in list(candidate_iris):
                for child in owl_graph.subjects(RDFS.subClassOf, parent):
                    if child not in candidate_iris and child not in kc_bases:
                        candidate_iris.add(child)
                        changed = True

        # Resolve namespace from the first candidate IRI
        namespace = None
        ns_obj = None
        if candidate_iris:
            sample_iri = str(next(iter(candidate_iris)))
            # IRI is like https://example.org/test#document → namespace is "test"
            for prefix, uri in owl_graph.namespaces():
                uri_str = str(uri)
                if sample_iri.startswith(uri_str) and prefix:
                    namespace = prefix
                    ns_obj = Namespace(uri_str)
                    break

        if namespace is None:
            raise ValueError(
                f"Could not detect model namespace in {p / 'ontology.ttl'}. "
                "No user-defined types (subclasses of kc:Vertex/Edge/Face) found."
            )

        # Derive shape namespace from model namespace
        # e.g. https://example.org/ex# → https://example.org/ex/shape#
        base_iri = str(ns_obj)
        shape_base = base_iri.rstrip("#") + "/shape#"

        # Build instance without calling __init__
        sb = object.__new__(cls)
        sb._namespace = namespace
        sb._base_iri = base_iri
        sb._ns = ns_obj
        sb._nss = Namespace(shape_base)
        sb._owl_graph = owl_graph
        sb._shacl_graph = shacl_graph
        sb._attr_domains = {}
        sb._queries = {}

        # Reconstruct _types registry from OWL subclass triples
        # Two passes: first find direct subclasses of kc:Vertex/Edge/Face,
        # then find user types that subclass other user types (inheritance).
        sb._types = {}
        kind_map = {
            _KC.Vertex: "vertex",
            _KC.Edge: "edge",
            _KC.Face: "face",
        }
        kc_base_iris = set(kind_map.keys()) | {_KC.Element, _KC.Complex}
        user_type_iris: dict[str, URIRef] = {}  # local_name → IRI

        # Pass 1: direct subclasses of kc base types
        for kc_class, kind in kind_map.items():
            for type_iri in owl_graph.subjects(RDFS.subClassOf, kc_class):
                if type_iri in kc_base_iris:
                    continue
                local_name = str(type_iri).replace(sb._base_iri, "")
                if local_name and not local_name.startswith("http"):
                    sb._types[local_name] = {
                        "kind": kind,
                        "attributes": {},
                        "parent": None,
                        "bind": {},
                    }
                    user_type_iris[local_name] = type_iri

        # Pass 2: find user types that subclass other user types (inheritance)
        # Keep discovering until no new types are found
        iri_to_name = {v: k for k, v in user_type_iris.items()}
        changed = True
        while changed:
            changed = False
            for parent_iri, parent_name in list(iri_to_name.items()):
                for child_iri in owl_graph.subjects(RDFS.subClassOf, parent_iri):
                    if child_iri in kc_base_iris:
                        continue
                    child_name = str(child_iri).replace(sb._base_iri, "")
                    if child_name and not child_name.startswith("http") and child_name not in sb._types:
                        sb._types[child_name] = {
                            "kind": sb._types[parent_name]["kind"],
                            "attributes": {},
                            "parent": parent_name,
                            "bind": {},
                        }
                        user_type_iris[child_name] = child_iri
                        iri_to_name[child_iri] = child_name
                        changed = True

        # Recover attributes from SHACL property shapes
        for name, type_iri in user_type_iris.items():
            shape_iri = sb._nss[f"{name}Shape"]
            attrs = {}
            bind = {}

            for _, _, prop_node in shacl_graph.triples((shape_iri, _SH.property, None)):
                path = shacl_graph.value(prop_node, _SH.path)
                if path is None:
                    continue
                path_str = str(path)
                if not path_str.startswith(sb._base_iri):
                    continue
                attr_name = path_str[len(sb._base_iri):]

                # Check for sh:hasValue → bind
                has_value = shacl_graph.value(prop_node, _SH.hasValue)
                if has_value is not None:
                    bind[attr_name] = str(has_value)
                    continue

                # Check for sh:in → VocabDescriptor
                in_list = shacl_graph.value(prop_node, _SH["in"])
                if in_list is not None:
                    values = list(Collection(shacl_graph, in_list))
                    vocab_values = tuple(str(v) for v in values)
                    max_count = shacl_graph.value(prop_node, _SH.maxCount)
                    multiple = max_count is None
                    attrs[attr_name] = VocabDescriptor(
                        values=vocab_values, multiple=multiple
                    )
                else:
                    # TextDescriptor
                    min_count = shacl_graph.value(prop_node, _SH.minCount)
                    max_count = shacl_graph.value(prop_node, _SH.maxCount)
                    required = min_count is not None and int(min_count) >= 1
                    multiple = max_count is None
                    attrs[attr_name] = TextDescriptor(
                        required=required, multiple=multiple
                    )

            sb._types[name]["attributes"] = attrs
            sb._types[name]["bind"] = bind

        return sb

add_vertex_type(name, attributes=None, parent=None, bind=None)

Declare a new vertex type (OWL subclass of KC:Vertex + SHACL node shape).

Parameters:

Name Type Description Default
name str

Class name within the user namespace.

required
attributes dict

Mapping of attribute name to descriptor (VocabDescriptor, TextDescriptor, or dict with "vocab"/"text" key and optional "required" flag).

None
parent str

Name of a registered vertex type to inherit from.

None
bind dict

Mapping of attribute names to fixed string values (sh:hasValue).

None

Returns:

Type Description
SchemaBuilder (self, for chaining)
Source code in knowledgecomplex/schema.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
def add_vertex_type(
    self,
    name: str,
    attributes: dict[str, VocabDescriptor | TextDescriptor | Any] | None = None,
    parent: str | None = None,
    bind: dict[str, str] | None = None,
) -> "SchemaBuilder":
    """
    Declare a new vertex type (OWL subclass of KC:Vertex + SHACL node shape).

    Parameters
    ----------
    name : str
        Class name within the user namespace.
    attributes : dict, optional
        Mapping of attribute name to descriptor (VocabDescriptor, TextDescriptor,
        or dict with "vocab"/"text" key and optional "required" flag).
    parent : str, optional
        Name of a registered vertex type to inherit from.
    bind : dict, optional
        Mapping of attribute names to fixed string values (sh:hasValue).

    Returns
    -------
    SchemaBuilder (self, for chaining)
    """
    from knowledgecomplex.exceptions import SchemaError
    if name in self._types:
        raise SchemaError(f"Type '{name}' is already registered")
    self._validate_parent(parent, "vertex")
    attributes = attributes or {}
    bind = bind or {}

    self._types[name] = {
        "kind": "vertex",
        "attributes": dict(attributes),
        "parent": parent,
        "bind": dict(bind),
    }

    # Validate bind against all attributes (own + inherited)
    if bind:
        inherited = self._collect_inherited_attributes(name)
        all_attrs = {**inherited, **attributes}
        self._validate_bind(bind, all_attrs)

    type_iri = self._ns[name]
    shape_iri = self._nss[f"{name}Shape"]

    # OWL
    superclass = self._ns[parent] if parent else _KC.Vertex
    self._owl_graph.add((type_iri, RDF.type, OWL.Class))
    self._owl_graph.add((type_iri, RDFS.subClassOf, superclass))

    # SHACL
    self._shacl_graph.add((shape_iri, RDF.type, _SH.NodeShape))
    self._shacl_graph.add((shape_iri, _SH.targetClass, type_iri))

    for attr_name, attr_spec in attributes.items():
        self._dispatch_attr(type_iri, shape_iri, attr_name, attr_spec)

    if bind:
        self._apply_bind(shape_iri, bind)

    return self

add_edge_type(name, attributes=None, parent=None, bind=None)

Declare a new edge type (OWL subclass of KC:Edge + SHACL property shapes).

Parameters:

Name Type Description Default
name str

Class name within the user namespace.

required
attributes dict

Mapping of attribute name to descriptor (VocabDescriptor, TextDescriptor, or dict with "vocab"/"text" key and optional "required" flag).

None
parent str

Name of a registered edge type to inherit from.

None
bind dict

Mapping of attribute names to fixed string values (sh:hasValue).

None

Returns:

Type Description
SchemaBuilder (self, for chaining)
Source code in knowledgecomplex/schema.py
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
def add_edge_type(
    self,
    name: str,
    attributes: dict[str, VocabDescriptor | TextDescriptor | Any] | None = None,
    parent: str | None = None,
    bind: dict[str, str] | None = None,
) -> "SchemaBuilder":
    """
    Declare a new edge type (OWL subclass of KC:Edge + SHACL property shapes).

    Parameters
    ----------
    name : str
        Class name within the user namespace.
    attributes : dict, optional
        Mapping of attribute name to descriptor (VocabDescriptor, TextDescriptor,
        or dict with "vocab"/"text" key and optional "required" flag).
    parent : str, optional
        Name of a registered edge type to inherit from.
    bind : dict, optional
        Mapping of attribute names to fixed string values (sh:hasValue).

    Returns
    -------
    SchemaBuilder (self, for chaining)
    """
    from knowledgecomplex.exceptions import SchemaError
    if name in self._types:
        raise SchemaError(f"Type '{name}' is already registered")
    self._validate_parent(parent, "edge")
    attributes = attributes or {}
    bind = bind or {}

    self._types[name] = {
        "kind": "edge",
        "attributes": dict(attributes),
        "parent": parent,
        "bind": dict(bind),
    }

    if bind:
        inherited = self._collect_inherited_attributes(name)
        all_attrs = {**inherited, **attributes}
        self._validate_bind(bind, all_attrs)

    type_iri = self._ns[name]
    shape_iri = self._nss[f"{name}Shape"]

    # OWL
    superclass = self._ns[parent] if parent else _KC.Edge
    self._owl_graph.add((type_iri, RDF.type, OWL.Class))
    self._owl_graph.add((type_iri, RDFS.subClassOf, superclass))

    # SHACL
    self._shacl_graph.add((shape_iri, RDF.type, _SH.NodeShape))
    self._shacl_graph.add((shape_iri, _SH.targetClass, type_iri))

    for attr_name, attr_spec in attributes.items():
        self._dispatch_attr(type_iri, shape_iri, attr_name, attr_spec)

    if bind:
        self._apply_bind(shape_iri, bind)

    return self

add_face_type(name, attributes=None, parent=None, bind=None)

Declare a new face type (OWL subclass of KC:Face + SHACL property shapes).

Attributes with required=False generate sh:minCount 0 constraints.

Parameters:

Name Type Description Default
name str

Class name within the user namespace.

required
attributes dict

Mapping of attribute name to descriptor (VocabDescriptor, TextDescriptor, or dict with "vocab"/"text" key and optional "required" flag).

None
parent str

Name of a registered face type to inherit from.

None
bind dict

Mapping of attribute names to fixed string values (sh:hasValue).

None

Returns:

Type Description
SchemaBuilder (self, for chaining)
Source code in knowledgecomplex/schema.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
def add_face_type(
    self,
    name: str,
    attributes: dict[str, Any] | None = None,
    parent: str | None = None,
    bind: dict[str, str] | None = None,
) -> "SchemaBuilder":
    """
    Declare a new face type (OWL subclass of KC:Face + SHACL property shapes).

    Attributes with ``required=False`` generate sh:minCount 0 constraints.

    Parameters
    ----------
    name : str
        Class name within the user namespace.
    attributes : dict, optional
        Mapping of attribute name to descriptor (VocabDescriptor, TextDescriptor,
        or dict with "vocab"/"text" key and optional "required" flag).
    parent : str, optional
        Name of a registered face type to inherit from.
    bind : dict, optional
        Mapping of attribute names to fixed string values (sh:hasValue).

    Returns
    -------
    SchemaBuilder (self, for chaining)
    """
    from knowledgecomplex.exceptions import SchemaError
    if name in self._types:
        raise SchemaError(f"Type '{name}' is already registered")
    self._validate_parent(parent, "face")
    attributes = attributes or {}
    bind = bind or {}

    self._types[name] = {
        "kind": "face",
        "attributes": dict(attributes),
        "parent": parent,
        "bind": dict(bind),
    }

    if bind:
        inherited = self._collect_inherited_attributes(name)
        all_attrs = {**inherited, **attributes}
        self._validate_bind(bind, all_attrs)

    type_iri = self._ns[name]
    shape_iri = self._nss[f"{name}Shape"]

    # OWL
    superclass = self._ns[parent] if parent else _KC.Face
    self._owl_graph.add((type_iri, RDF.type, OWL.Class))
    self._owl_graph.add((type_iri, RDFS.subClassOf, superclass))

    # SHACL
    self._shacl_graph.add((shape_iri, RDF.type, _SH.NodeShape))
    self._shacl_graph.add((shape_iri, _SH.targetClass, type_iri))

    for attr_name, attr_spec in attributes.items():
        self._dispatch_attr(type_iri, shape_iri, attr_name, attr_spec)

    if bind:
        self._apply_bind(shape_iri, bind)

    return self

describe_type(name)

Inspect a registered type's attributes, parent, and bindings.

Parameters:

Name Type Description Default
name str

The registered type name.

required

Returns:

Type Description
dict

Keys: name, kind, parent, own_attributes, inherited_attributes, all_attributes, bound.

Source code in knowledgecomplex/schema.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def describe_type(self, name: str) -> dict:
    """
    Inspect a registered type's attributes, parent, and bindings.

    Parameters
    ----------
    name : str
        The registered type name.

    Returns
    -------
    dict
        Keys: name, kind, parent, own_attributes, inherited_attributes,
        all_attributes, bound.
    """
    from knowledgecomplex.exceptions import SchemaError
    if name not in self._types:
        raise SchemaError(f"Type '{name}' is not registered")

    info = self._types[name]
    own_attrs = dict(info.get("attributes", {}))
    inherited_attrs = self._collect_inherited_attributes(name)
    # Collect bindings from ancestors
    inherited_bind = {}
    current = info.get("parent")
    while current is not None:
        parent_bind = self._types[current].get("bind", {})
        for k, v in parent_bind.items():
            if k not in inherited_bind:
                inherited_bind[k] = v
        current = self._types[current].get("parent")
    own_bind = dict(info.get("bind", {}))
    all_bind = {**inherited_bind, **own_bind}

    all_attrs = {**inherited_attrs, **own_attrs}
    return {
        "name": name,
        "kind": info["kind"],
        "parent": info.get("parent"),
        "own_attributes": own_attrs,
        "inherited_attributes": inherited_attrs,
        "all_attributes": all_attrs,
        "bound": all_bind,
    }

type_names(kind=None)

List registered type names, optionally filtered by kind.

Parameters:

Name Type Description Default
kind str

Filter by "vertex", "edge", or "face".

None

Returns:

Type Description
list[str]
Source code in knowledgecomplex/schema.py
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
def type_names(self, kind: str | None = None) -> list[str]:
    """
    List registered type names, optionally filtered by kind.

    Parameters
    ----------
    kind : str, optional
        Filter by "vertex", "edge", or "face".

    Returns
    -------
    list[str]
    """
    if kind is None:
        return list(self._types.keys())
    return [n for n, info in self._types.items() if info["kind"] == kind]

promote_to_attribute(type, attribute, vocab=None, text=None, required=True)

Atomically promote a discovered pattern to a first-class typed attribute.

Updates both OWL property definition and SHACL shape constraint for the named type. After calling this, dump_owl() and dump_shacl() both reflect the updated attribute.

Parameters:

Name Type Description Default
type str

The type name (must have been registered via add_*_type).

required
attribute str

Attribute name to add or upgrade.

required
vocab VocabDescriptor

Controlled vocabulary for the attribute.

None
text TextDescriptor

Free-text descriptor for the attribute.

None
required bool

If True, generates sh:minCount 1. Overrides the descriptor's own required flag.

True

Returns:

Type Description
SchemaBuilder (self, for chaining)
Source code in knowledgecomplex/schema.py
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def promote_to_attribute(
    self,
    type: str,
    attribute: str,
    vocab: VocabDescriptor | None = None,
    text: TextDescriptor | None = None,
    required: bool = True,
) -> "SchemaBuilder":
    """
    Atomically promote a discovered pattern to a first-class typed attribute.

    Updates both OWL property definition and SHACL shape constraint for the named type.
    After calling this, dump_owl() and dump_shacl() both reflect the updated attribute.

    Parameters
    ----------
    type : str
        The type name (must have been registered via add_*_type).
    attribute : str
        Attribute name to add or upgrade.
    vocab : VocabDescriptor, optional
        Controlled vocabulary for the attribute.
    text : TextDescriptor, optional
        Free-text descriptor for the attribute.
    required : bool
        If True, generates sh:minCount 1. Overrides the descriptor's own required flag.

    Returns
    -------
    SchemaBuilder (self, for chaining)
    """
    from knowledgecomplex.exceptions import SchemaError
    if type not in self._types:
        raise SchemaError(f"Type '{type}' is not registered")
    if vocab is None and text is None:
        raise SchemaError("promote_to_attribute requires either vocab or text descriptor")

    type_iri = self._ns[type]
    shape_iri = self._nss[f"{type}Shape"]
    attr_iri = self._ns[attribute]

    # Remove existing OWL triples for this attribute (if upgrading)
    for p in (RDFS.domain, RDFS.range, RDFS.comment):
        self._owl_graph.remove((attr_iri, p, None))
    self._owl_graph.remove((attr_iri, RDF.type, OWL.DatatypeProperty))

    # Remove existing SHACL property shape for this attribute (if upgrading)
    for prop_node in list(self._shacl_graph.objects(shape_iri, _SH.property)):
        if (prop_node, _SH.path, attr_iri) in self._shacl_graph:
            # Remove the sh:in list
            list_head = self._shacl_graph.value(prop_node, _SH["in"])
            if list_head is not None:
                Collection(self._shacl_graph, list_head).clear()
                self._shacl_graph.remove((prop_node, _SH["in"], list_head))
            # Remove all triples about this property shape
            for p, o in list(self._shacl_graph.predicate_objects(prop_node)):
                self._shacl_graph.remove((prop_node, p, o))
            self._shacl_graph.remove((shape_iri, _SH.property, prop_node))

    # Re-add with new settings
    if vocab is not None:
        self._add_attr_to_graphs(type_iri, shape_iri, attribute, vocab, required=required)
    else:
        # Override the text descriptor's required flag with the promote call's value
        effective = TextDescriptor(required=required, multiple=text.multiple)
        self._add_attr_to_graphs(type_iri, shape_iri, attribute, effective)

    # Update type registry
    if "attributes" not in self._types[type]:
        self._types[type]["attributes"] = {}
    if vocab is not None:
        self._types[type]["attributes"][attribute] = {
            "vocab": vocab, "required": required
        }
    else:
        self._types[type]["attributes"][attribute] = text

    return self

add_sparql_constraint(type_name, sparql, message)

Attach a sh:sparql constraint to the SHACL shape for type_name.

The sparql argument must be a SPARQL SELECT query that returns $this for each violating focus node. pyshacl evaluates this and reports the message for each returned row.

Parameters:

Name Type Description Default
type_name str

The type name (must have been registered via add_*_type).

required
sparql str

SPARQL SELECT query. Must bind $this to each violating node.

required
message str

Human-readable message reported when the constraint is violated.

required

Returns:

Type Description
SchemaBuilder (self, for chaining)
Source code in knowledgecomplex/schema.py
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
def add_sparql_constraint(
    self,
    type_name: str,
    sparql: str,
    message: str,
) -> "SchemaBuilder":
    """
    Attach a sh:sparql constraint to the SHACL shape for type_name.

    The sparql argument must be a SPARQL SELECT query that returns $this
    for each violating focus node. pyshacl evaluates this and reports the
    message for each returned row.

    Parameters
    ----------
    type_name : str
        The type name (must have been registered via add_*_type).
    sparql : str
        SPARQL SELECT query. Must bind $this to each violating node.
    message : str
        Human-readable message reported when the constraint is violated.

    Returns
    -------
    SchemaBuilder (self, for chaining)
    """
    from knowledgecomplex.exceptions import SchemaError
    if type_name not in self._types:
        raise SchemaError(f"Type '{type_name}' is not registered")
    shape_iri = self._nss[f"{type_name}Shape"]
    constraint = BNode()
    self._shacl_graph.add((shape_iri, _SH.sparql, constraint))
    self._shacl_graph.add((constraint, RDF.type, _SH.SPARQLConstraint))
    self._shacl_graph.add((constraint, _SH.select, Literal(sparql)))
    self._shacl_graph.add((constraint, _SH.message, Literal(message)))
    return self

add_query(name, operation, *, target_type=None)

Register a named topological query template on this schema.

The query is generated from a topological operation and optional type filter, then stored internally. It is exported as a .sparql file by :meth:export and automatically loaded by :class:~knowledgecomplex.graph.KnowledgeComplex at runtime.

Parameters:

Name Type Description Default
name str

Query template name (becomes the filename stem, e.g. "spec_coboundary" exports as queries/spec_coboundary.sparql).

required
operation str

Topological operation: "boundary", "coboundary", "star", "closure", "link", or "degree".

required
target_type str

Filter results to this type (including subtypes via OWL class hierarchy).

None

Returns:

Type Description
SchemaBuilder (self, for chaining)
Example

sb.add_query("spec_coboundary", "coboundary", target_type="verification")

Source code in knowledgecomplex/schema.py
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
def add_query(
    self,
    name: str,
    operation: str,
    *,
    target_type: str | None = None,
) -> "SchemaBuilder":
    """Register a named topological query template on this schema.

    The query is generated from a topological operation and optional type
    filter, then stored internally. It is exported as a ``.sparql`` file
    by :meth:`export` and automatically loaded by
    :class:`~knowledgecomplex.graph.KnowledgeComplex` at runtime.

    Parameters
    ----------
    name : str
        Query template name (becomes the filename stem, e.g. ``"spec_coboundary"``
        exports as ``queries/spec_coboundary.sparql``).
    operation : str
        Topological operation: ``"boundary"``, ``"coboundary"``, ``"star"``,
        ``"closure"``, ``"link"``, or ``"degree"``.
    target_type : str, optional
        Filter results to this type (including subtypes via OWL class hierarchy).

    Returns
    -------
    SchemaBuilder (self, for chaining)

    Example
    -------
    >>> sb.add_query("spec_coboundary", "coboundary", target_type="verification")
    """
    sparql = self._build_topo_sparql(
        operation, simplex_iri="{simplex}", target_type=target_type,
    )
    self._queries[name] = sparql
    return self

add_topological_constraint(type_name, operation, *, target_type=None, predicate='min_count', min_count=1, max_count=None, message=None)

Escalate a topological query to a SHACL constraint.

Generates a sh:sparql constraint that, for each focus node of type_name, evaluates a topological operation and checks a cardinality predicate. Delegates to :meth:add_sparql_constraint.

Parameters:

Name Type Description Default
type_name str

The type to constrain (must be registered).

required
operation str

Topological operation: "boundary", "coboundary", "star", "closure", "link", or "degree".

required
target_type str

Filter the topological result to this type.

None
predicate str

"min_count" — at least min_count results (default). "max_count" — at most max_count results. "exact_count" — exactly min_count results.

'min_count'
min_count int

Minimum count (used by "min_count" and "exact_count").

1
max_count int

Maximum count (used by "max_count").

None
message str

Custom violation message. Auto-generated if not provided.

None

Returns:

Type Description
SchemaBuilder (self, for chaining)
Example

sb.add_topological_constraint( ... "spec", "coboundary", ... target_type="verification", ... predicate="min_count", min_count=1, ... message="Every spec must have at least one verification edge", ... )

Source code in knowledgecomplex/schema.py
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
def add_topological_constraint(
    self,
    type_name: str,
    operation: str,
    *,
    target_type: str | None = None,
    predicate: str = "min_count",
    min_count: int = 1,
    max_count: int | None = None,
    message: str | None = None,
) -> "SchemaBuilder":
    """Escalate a topological query to a SHACL constraint.

    Generates a ``sh:sparql`` constraint that, for each focus node of
    *type_name*, evaluates a topological operation and checks a cardinality
    predicate. Delegates to :meth:`add_sparql_constraint`.

    Parameters
    ----------
    type_name : str
        The type to constrain (must be registered).
    operation : str
        Topological operation: ``"boundary"``, ``"coboundary"``, ``"star"``,
        ``"closure"``, ``"link"``, or ``"degree"``.
    target_type : str, optional
        Filter the topological result to this type.
    predicate : str
        ``"min_count"`` — at least *min_count* results (default).
        ``"max_count"`` — at most *max_count* results.
        ``"exact_count"`` — exactly *min_count* results.
    min_count : int
        Minimum count (used by ``"min_count"`` and ``"exact_count"``).
    max_count : int, optional
        Maximum count (used by ``"max_count"``).
    message : str, optional
        Custom violation message. Auto-generated if not provided.

    Returns
    -------
    SchemaBuilder (self, for chaining)

    Example
    -------
    >>> sb.add_topological_constraint(
    ...     "spec", "coboundary",
    ...     target_type="verification",
    ...     predicate="min_count", min_count=1,
    ...     message="Every spec must have at least one verification edge",
    ... )
    """
    from knowledgecomplex.exceptions import SchemaError
    if type_name not in self._types:
        raise SchemaError(f"Type '{type_name}' is not registered")
    if operation not in self._TOPO_PATTERNS:
        raise SchemaError(
            f"Unknown topological operation '{operation}'. "
            f"Valid: {sorted(self._TOPO_PATTERNS)}"
        )

    pattern_tmpl, result_var = self._TOPO_PATTERNS[operation]

    if target_type is not None:
        if target_type not in self._types:
            raise SchemaError(f"Type '{target_type}' is not registered")
        type_iri = self._ns[target_type]
        tf = f"?{result_var} a/rdfs:subClassOf* <{type_iri}> ."
    else:
        tf = ""

    pattern = (
        pattern_tmpl
        .replace("{simplex_iri}", "$this")
        .replace("{type_filter}", tf)
    )

    # Build the HAVING clause based on predicate
    if predicate == "min_count":
        having = f"HAVING (COUNT(DISTINCT ?{result_var}) < {min_count})"
    elif predicate == "max_count":
        if max_count is None:
            raise SchemaError("max_count predicate requires max_count parameter")
        having = f"HAVING (COUNT(DISTINCT ?{result_var}) > {max_count})"
    elif predicate == "exact_count":
        having = f"HAVING (COUNT(DISTINCT ?{result_var}) != {min_count})"
    else:
        raise SchemaError(
            f"Unknown predicate '{predicate}'. "
            f"Valid: min_count, max_count, exact_count"
        )

    # Wrap pattern in OPTIONAL so GROUP BY produces a row even when
    # there are zero matches (otherwise HAVING never fires for empty results)
    sparql = (
        f"PREFIX kc: <https://w3id.org/kc#>\n"
        f"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
        f"SELECT $this WHERE {{\n"
        f"    OPTIONAL {{ {pattern} }}\n"
        f"}}\n"
        f"GROUP BY $this\n"
        f"{having}\n"
    )

    if message is None:
        target_desc = f" of type '{target_type}'" if target_type else ""
        message = (
            f"Topological constraint violated: {operation}{target_desc} "
            f"on '{type_name}' failed {predicate} check "
            f"(min={min_count}, max={max_count})"
        )

    return self.add_sparql_constraint(type_name, sparql, message)

dump_owl()

Return merged OWL graph (core + user schema) as a Turtle string.

Source code in knowledgecomplex/schema.py
1022
1023
1024
def dump_owl(self) -> str:
    """Return merged OWL graph (core + user schema) as a Turtle string."""
    return self._owl_graph.serialize(format="turtle")

dump_shacl()

Return merged SHACL graph (core shapes + user shapes) as a Turtle string.

Source code in knowledgecomplex/schema.py
1026
1027
1028
def dump_shacl(self) -> str:
    """Return merged SHACL graph (core shapes + user shapes) as a Turtle string."""
    return self._shacl_graph.serialize(format="turtle")

export(path, query_dirs=None)

Export the schema to a directory as standard semantic web files.

Writes ontology.ttl (OWL) and shapes.ttl (SHACL). If query_dirs are provided, copies all .sparql files into a queries/ subdirectory.

Parameters:

Name Type Description Default
path str | Path

Target directory. Created if it does not exist.

required
query_dirs list[Path]

Directories containing .sparql query templates to include.

None

Returns:

Type Description
Path

The export directory.

Source code in knowledgecomplex/schema.py
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
def export(
    self,
    path: str | Path,
    query_dirs: list[Path] | None = None,
) -> Path:
    """
    Export the schema to a directory as standard semantic web files.

    Writes ontology.ttl (OWL) and shapes.ttl (SHACL). If query_dirs are
    provided, copies all .sparql files into a queries/ subdirectory.

    Parameters
    ----------
    path : str | Path
        Target directory. Created if it does not exist.
    query_dirs : list[Path], optional
        Directories containing .sparql query templates to include.

    Returns
    -------
    Path
        The export directory.
    """
    p = Path(path)
    p.mkdir(parents=True, exist_ok=True)
    (p / "ontology.ttl").write_text(self.dump_owl())
    (p / "shapes.ttl").write_text(self.dump_shacl())
    # Write schema-generated query templates and copy external query dirs
    if self._queries or query_dirs:
        qdir = p / "queries"
        qdir.mkdir(exist_ok=True)
        for name, sparql_text in self._queries.items():
            (qdir / f"{name}.sparql").write_text(sparql_text)
        if query_dirs:
            for d in query_dirs:
                for sparql_file in d.glob("*.sparql"):
                    shutil.copy2(sparql_file, qdir / sparql_file.name)
    return p

load(path) classmethod

Load a schema from a directory containing ontology.ttl and shapes.ttl.

Reconstructs the type registry by inspecting OWL subclass triples.

Parameters:

Name Type Description Default
path str | Path

Directory containing ontology.ttl and shapes.ttl.

required

Returns:

Type Description
SchemaBuilder
Source code in knowledgecomplex/schema.py
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
@classmethod
def load(cls, path: str | Path) -> "SchemaBuilder":
    """
    Load a schema from a directory containing ontology.ttl and shapes.ttl.

    Reconstructs the type registry by inspecting OWL subclass triples.

    Parameters
    ----------
    path : str | Path
        Directory containing ontology.ttl and shapes.ttl.

    Returns
    -------
    SchemaBuilder
    """
    p = Path(path)

    owl_graph = Graph()
    owl_graph.parse(str(p / "ontology.ttl"), format="turtle")

    shacl_graph = Graph()
    shacl_graph.parse(str(p / "shapes.ttl"), format="turtle")

    # Discover model namespace: find a namespace binding that is not
    # one of the well-known prefixes (kc, kcs, sh, owl, rdfs, rdf, xsd)
    # Discover model namespace: find types that are subclasses of
    # kc:Vertex, kc:Edge, or kc:Face, then resolve their namespace.
    kc_bases = {_KC.Vertex, _KC.Edge, _KC.Face}
    candidate_iris: set[URIRef] = set()
    for kc_class in kc_bases:
        for subj in owl_graph.subjects(RDFS.subClassOf, kc_class):
            if subj not in kc_bases and subj != _KC.Element:
                candidate_iris.add(subj)

    # Also find types that subclass the candidates (inheritance)
    changed = True
    while changed:
        changed = False
        for parent in list(candidate_iris):
            for child in owl_graph.subjects(RDFS.subClassOf, parent):
                if child not in candidate_iris and child not in kc_bases:
                    candidate_iris.add(child)
                    changed = True

    # Resolve namespace from the first candidate IRI
    namespace = None
    ns_obj = None
    if candidate_iris:
        sample_iri = str(next(iter(candidate_iris)))
        # IRI is like https://example.org/test#document → namespace is "test"
        for prefix, uri in owl_graph.namespaces():
            uri_str = str(uri)
            if sample_iri.startswith(uri_str) and prefix:
                namespace = prefix
                ns_obj = Namespace(uri_str)
                break

    if namespace is None:
        raise ValueError(
            f"Could not detect model namespace in {p / 'ontology.ttl'}. "
            "No user-defined types (subclasses of kc:Vertex/Edge/Face) found."
        )

    # Derive shape namespace from model namespace
    # e.g. https://example.org/ex# → https://example.org/ex/shape#
    base_iri = str(ns_obj)
    shape_base = base_iri.rstrip("#") + "/shape#"

    # Build instance without calling __init__
    sb = object.__new__(cls)
    sb._namespace = namespace
    sb._base_iri = base_iri
    sb._ns = ns_obj
    sb._nss = Namespace(shape_base)
    sb._owl_graph = owl_graph
    sb._shacl_graph = shacl_graph
    sb._attr_domains = {}
    sb._queries = {}

    # Reconstruct _types registry from OWL subclass triples
    # Two passes: first find direct subclasses of kc:Vertex/Edge/Face,
    # then find user types that subclass other user types (inheritance).
    sb._types = {}
    kind_map = {
        _KC.Vertex: "vertex",
        _KC.Edge: "edge",
        _KC.Face: "face",
    }
    kc_base_iris = set(kind_map.keys()) | {_KC.Element, _KC.Complex}
    user_type_iris: dict[str, URIRef] = {}  # local_name → IRI

    # Pass 1: direct subclasses of kc base types
    for kc_class, kind in kind_map.items():
        for type_iri in owl_graph.subjects(RDFS.subClassOf, kc_class):
            if type_iri in kc_base_iris:
                continue
            local_name = str(type_iri).replace(sb._base_iri, "")
            if local_name and not local_name.startswith("http"):
                sb._types[local_name] = {
                    "kind": kind,
                    "attributes": {},
                    "parent": None,
                    "bind": {},
                }
                user_type_iris[local_name] = type_iri

    # Pass 2: find user types that subclass other user types (inheritance)
    # Keep discovering until no new types are found
    iri_to_name = {v: k for k, v in user_type_iris.items()}
    changed = True
    while changed:
        changed = False
        for parent_iri, parent_name in list(iri_to_name.items()):
            for child_iri in owl_graph.subjects(RDFS.subClassOf, parent_iri):
                if child_iri in kc_base_iris:
                    continue
                child_name = str(child_iri).replace(sb._base_iri, "")
                if child_name and not child_name.startswith("http") and child_name not in sb._types:
                    sb._types[child_name] = {
                        "kind": sb._types[parent_name]["kind"],
                        "attributes": {},
                        "parent": parent_name,
                        "bind": {},
                    }
                    user_type_iris[child_name] = child_iri
                    iri_to_name[child_iri] = child_name
                    changed = True

    # Recover attributes from SHACL property shapes
    for name, type_iri in user_type_iris.items():
        shape_iri = sb._nss[f"{name}Shape"]
        attrs = {}
        bind = {}

        for _, _, prop_node in shacl_graph.triples((shape_iri, _SH.property, None)):
            path = shacl_graph.value(prop_node, _SH.path)
            if path is None:
                continue
            path_str = str(path)
            if not path_str.startswith(sb._base_iri):
                continue
            attr_name = path_str[len(sb._base_iri):]

            # Check for sh:hasValue → bind
            has_value = shacl_graph.value(prop_node, _SH.hasValue)
            if has_value is not None:
                bind[attr_name] = str(has_value)
                continue

            # Check for sh:in → VocabDescriptor
            in_list = shacl_graph.value(prop_node, _SH["in"])
            if in_list is not None:
                values = list(Collection(shacl_graph, in_list))
                vocab_values = tuple(str(v) for v in values)
                max_count = shacl_graph.value(prop_node, _SH.maxCount)
                multiple = max_count is None
                attrs[attr_name] = VocabDescriptor(
                    values=vocab_values, multiple=multiple
                )
            else:
                # TextDescriptor
                min_count = shacl_graph.value(prop_node, _SH.minCount)
                max_count = shacl_graph.value(prop_node, _SH.maxCount)
                required = min_count is not None and int(min_count) >= 1
                multiple = max_count is None
                attrs[attr_name] = TextDescriptor(
                    required=required, multiple=multiple
                )

        sb._types[name]["attributes"] = attrs
        sb._types[name]["bind"] = bind

    return sb

vocab(*values, multiple=False)

Declare a controlled vocabulary for an attribute.

Parameters:

Name Type Description Default
*values str

The allowed string values.

()
multiple bool

If True, allows multiple values (no sh:maxCount). If False (default), generates sh:maxCount 1.

False

Returns:

Type Description
VocabDescriptor
Example

vocab("adjacent", "opposite") vocab('adjacent', 'opposite') vocab("a", "b", "c", multiple=True) vocab('a', 'b', 'c', multiple=True)

Source code in knowledgecomplex/schema.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def vocab(*values: str, multiple: bool = False) -> VocabDescriptor:
    """
    Declare a controlled vocabulary for an attribute.

    Parameters
    ----------
    *values : str
        The allowed string values.
    multiple : bool
        If True, allows multiple values (no sh:maxCount).
        If False (default), generates sh:maxCount 1.

    Returns
    -------
    VocabDescriptor

    Example
    -------
    >>> vocab("adjacent", "opposite")
    vocab('adjacent', 'opposite')
    >>> vocab("a", "b", "c", multiple=True)
    vocab('a', 'b', 'c', multiple=True)
    """
    if not values:
        raise ValueError("vocab() requires at least one value")
    return VocabDescriptor(values=tuple(values), multiple=multiple)

text(*, required=True, multiple=False)

Declare a free-text string attribute.

Parameters:

Name Type Description Default
required bool

If True (default), generates sh:minCount 1.

True
multiple bool

If True, allows multiple values (no sh:maxCount). If False (default), generates sh:maxCount 1.

False

Returns:

Type Description
TextDescriptor
Example

text() text() text(required=False, multiple=True) text(required=False, multiple=True)

Source code in knowledgecomplex/schema.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def text(*, required: bool = True, multiple: bool = False) -> TextDescriptor:
    """
    Declare a free-text string attribute.

    Parameters
    ----------
    required : bool
        If True (default), generates sh:minCount 1.
    multiple : bool
        If True, allows multiple values (no sh:maxCount).
        If False (default), generates sh:maxCount 1.

    Returns
    -------
    TextDescriptor

    Example
    -------
    >>> text()
    text()
    >>> text(required=False, multiple=True)
    text(required=False, multiple=True)
    """
    return TextDescriptor(required=required, multiple=multiple)