Skip to content

ontology

A module adding additional functionality to owlready2. The main additions

includes
  • Visualisation of taxonomy and ontology as graphs (using pydot, see ontograph.py).

The class extension is defined within.

If desirable some of this may be moved back into owlready2.

BlankNode

Represents a blank node.

A blank node is a node that is not a literal and has no IRI. Resources represented by blank nodes are also called anonumous resources. Only the subject or object in an RDF triple can be a blank node.

Source code in ontopy/ontology.py
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
class BlankNode:
    """Represents a blank node.

    A blank node is a node that is not a literal and has no IRI.
    Resources represented by blank nodes are also called anonumous resources.
    Only the subject or object in an RDF triple can be a blank node.
    """

    def __init__(self, onto: Union[World, Ontology], storid: int):
        """Initiate a blank node.

        Args:
            onto: Ontology or World instance.
            storid: The storage id of the blank node.
        """
        if storid >= 0:
            raise ValueError(
                f"A BlankNode is supposed to have a negative storid: {storid}"
            )
        self.onto = onto
        self.storid = storid

    def __repr__(self):
        return repr(f"_:b{-self.storid}")

    def __hash__(self):
        return hash((self.onto, self.storid))

    def __eq__(self, other):
        """For now blank nodes always compare true against each other."""
        return isinstance(other, BlankNode)

__eq__(other)

For now blank nodes always compare true against each other.

Source code in ontopy/ontology.py
1519
1520
1521
def __eq__(self, other):
    """For now blank nodes always compare true against each other."""
    return isinstance(other, BlankNode)

__init__(onto, storid)

Initiate a blank node.

Parameters:

Name Type Description Default
onto Union[World, Ontology]

Ontology or World instance.

required
storid int

The storage id of the blank node.

required
Source code in ontopy/ontology.py
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
def __init__(self, onto: Union[World, Ontology], storid: int):
    """Initiate a blank node.

    Args:
        onto: Ontology or World instance.
        storid: The storage id of the blank node.
    """
    if storid >= 0:
        raise ValueError(
            f"A BlankNode is supposed to have a negative storid: {storid}"
        )
    self.onto = onto
    self.storid = storid

Ontology

Bases: owlready2.Ontology, OntoGraph

A generic class extending owlready2.Ontology.

Source code in ontopy/ontology.py
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 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
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
class Ontology(  # pylint: disable=too-many-public-methods
    owlready2.Ontology, OntoGraph
):
    """A generic class extending owlready2.Ontology."""

    # Properties controlling what annotations that are considered by
    # get_by_label()
    _label_annotations = []
    label_annotations = property(
        fget=lambda self: self._label_annotations,
        doc="List of label annotation searched for by get_by_label().",
    )

    # Name of special unlabeled entities, like Thing, Nothing, etc...
    _special_labels = None

    # Some properties for customising dir() listing - useful in
    # interactive sessions...
    _dir_preflabel = isinteractive()
    _dir_label = isinteractive()
    _dir_name = False
    _dir_imported = isinteractive()
    dir_preflabel = property(
        fget=lambda self: self._dir_preflabel,
        fset=lambda self, v: setattr(self, "_dir_preflabel", bool(v)),
        doc="Whether to include entity prefLabel in dir() listing.",
    )
    dir_label = property(
        fget=lambda self: self._dir_label,
        fset=lambda self, v: setattr(self, "_dir_label", bool(v)),
        doc="Whether to include entity label in dir() listing.",
    )
    dir_name = property(
        fget=lambda self: self._dir_name,
        fset=lambda self, v: setattr(self, "_dir_name", bool(v)),
        doc="Whether to include entity name in dir() listing.",
    )
    dir_imported = property(
        fget=lambda self: self._dir_imported,
        fset=lambda self, v: setattr(self, "_dir_imported", bool(v)),
        doc="Whether to include imported ontologies in dir() listing.",
    )

    def __dir__(self):
        set_dir = set(super().__dir__())
        lst = list(self.get_entities(imported=self._dir_imported))
        if self._dir_preflabel:
            set_dir.update(
                _.prefLabel.first() for _ in lst if hasattr(_, "prefLabel")
            )
        if self._dir_label:
            set_dir.update(_.label.first() for _ in lst if hasattr(_, "label"))
        if self._dir_name:
            set_dir.update(_.name for _ in lst if hasattr(_, "name"))

        set_dir.difference_update({None})  # get rid of possible None
        return sorted(set_dir)

    def __getitem__(self, name):
        item = super().__getitem__(name)
        if not item:
            item = self.get_by_label(name)
        return item

    def __getattr__(self, name):
        attr = super().__getattr__(name)
        if not attr:
            attr = self.get_by_label(name)
        return attr

    def __contains__(self, other):
        if self.world[other]:
            return True
        try:
            self.get_by_label(other)
        except NoSuchLabelError:
            return False
        else:
            return True

    def __objclass__(self):
        # Play nice with inspect...
        pass

    def __hash__(self):
        """Returns a hash based on base_iri.
        This is done to keep Ontology hashable when defining __eq__.
        """
        return hash(self.base_iri)

    def __eq__(self, other):
        """Checks if this ontology is equal to `other`.

        This function compares the result of
        ``set(self.get_unabbreviated_triples(label='_:b'))``,
        i.e. blank nodes are not distinguished, but relations to blank
        nodes are included.
        """
        return set(self.get_unabbreviated_triples(label="_:b")) == set(
            other.get_unabbreviated_triples(label="_:b")
        )

    def get_unabbreviated_triples(self, label=None):
        """Returns all triples unabbreviated.

        If `label` is given, it will be used to represent blank nodes.
        """
        return World.get_unabbreviated_triples(self, label)

    def get_by_label(
        self, label, label_annotations=None, namespace=None
    ):  # pylint: disable=too-many-arguments,too-many-branches
        """Returns entity with label annotation `label`.

        `label_annotations` is a sequence of label annotation names to look up.
        Defaults to the `label_annotations` property.

        If `namespace` is provided, it should be the last component of
        the base iri of an ontology (with trailing slash (/) or hash
        (#) stripped off).  The search for a matching label will be
        limited to this namespace.

        If several entities have the same label, only the one which is
        found first is returned.Use get_by_label_all() to get all matches.

        A NoSuchLabelError is raised if `label` cannot be found.

        Note
        ----
        The current implementation also supports "*" as a wildcard
        matching any number of characters. This may change in the future.
        """
        if not isinstance(label, str):
            raise TypeError(
                f"Invalid label definition, must be a string: {label!r}"
            )
        if " " in label:
            raise ValueError(
                f"Invalid label definition, {label!r} contains spaces."
            )

        if "namespaces" in self.__dict__:
            if namespace:
                if namespace in self.namespaces:
                    for entity in self.get_by_label_all(
                        label, label_annotations=label_annotations
                    ):
                        if entity.namespace == self.namespaces[namespace]:
                            return entity
                raise NoSuchLabelError(
                    f"No label annotations matches {label!r} in namespace "
                    f"{namespace!r}"
                )
            if label in self.namespaces:
                return self.namespaces[label]

        if label_annotations is None:
            annotations = (a.name for a in self.label_annotations)
        else:
            annotations = (
                a.name if hasattr(a, "storid") else a for a in label_annotations
            )
        for key in annotations:
            entity = self.search_one(**{key: label})
            if entity:
                return entity

        if self._special_labels and label in self._special_labels:
            return self._special_labels[label]

        entity = self.world[self.base_iri + label]
        if entity:
            return entity

        raise NoSuchLabelError(f"No label annotations matches {label!r}")

    def get_by_label_all(self, label, label_annotations=None, namespace=None):
        """Like get_by_label(), but returns a list with all matching labels.

        Returns an empty list if no matches could be found.
        """
        if not isinstance(label, str):
            raise TypeError(
                f"Invalid label definition, " f"must be a string: {label!r}"
            )
        if " " in label:
            raise ValueError(
                f"Invalid label definition, {label!r} contains spaces."
            )

        if label_annotations is None:
            annotations = (_.name for _ in self.label_annotations)
        else:
            annotations = (
                _.name if hasattr(_, "storid") else _ for _ in label_annotations
            )
        entity = self.world.search(**{annotations.__next__(): label})
        for key in annotations:
            entity.extend(self.world.search(**{key: label}))
        if self._special_labels and label in self._special_labels:
            entity.append(self._special_labels[label])
        if namespace:
            return [_ for _ in entity if _.namespace.name == namespace]
        return entity

    def add_label_annotation(self, iri):
        """Adds label annotation used by get_by_label().

        May be provided either as an IRI or as its owlready2 representation.
        """
        label_annotation = iri if hasattr(iri, "storid") else self.world[iri]
        if not label_annotation:
            raise ValueError(f"IRI not in ontology: {iri}")
        if label_annotation not in self._label_annotations:
            self._label_annotations.append(label_annotation)

    def remove_label_annotation(self, iri):
        """Removes label annotation used by get_by_label().

        May be provided either as an IRI or as its owlready2 representation.
        """
        label_annotation = iri if hasattr(iri, "storid") else self.world[iri]
        if not label_annotation:
            raise ValueError(f"IRI not in ontology: {iri}")
        self._label_annotations.remove(label_annotation)

    def load(  # pylint: disable=too-many-arguments,arguments-renamed
        self,
        only_local=False,
        filename=None,
        format=None,  # pylint: disable=redefined-builtin
        reload=None,
        reload_if_newer=False,
        url_from_catalog=None,
        catalog_file="catalog-v001.xml",
        emmo_based=True,
        **kwargs,
    ):
        """Load the ontology.

        Parameters
        ----------
        only_local : bool
            Whether to only read local files.  This requires that you
            have appended the path to the ontology to owlready2.onto_path.
        filename : str
            Path to file to load the ontology from.  Defaults to `base_iri`
            provided to get_ontology().
        format : str
            Format of `filename`.  Default is inferred from `filename`
            extension.
        reload : bool
            Whether to reload the ontology if it is already loaded.
        reload_if_newer : bool
            Whether to reload the ontology if the source has changed since
            last time it was loaded.
        url_from_catalog : bool | None
            Whether to use catalog file to resolve the location of `base_iri`.
            If None, the catalog file is used if it exists in the same
            directory as `filename`.
        catalog_file : str
            Name of Protègè catalog file in the same folder as the
            ontology.  This option is used together with `only_local` and
            defaults to "catalog-v001.xml".
        emmo_based : bool
            Whether this is an EMMO-based ontology or not, default `True`.
        kwargs
            Additional keyword arguments are passed on to
            owlready2.Ontology.load().
        """
        # TODO: make sure that `only_local` argument is respected...

        if self.loaded:
            return self
        self._load(
            only_local=only_local,
            filename=filename,
            format=format,
            reload=reload,
            reload_if_newer=reload_if_newer,
            url_from_catalog=url_from_catalog,
            catalog_file=catalog_file,
            **kwargs,
        )

        # Enable optimised search by get_by_label()
        if self._special_labels is None and emmo_based:
            for iri in DEFAULT_LABEL_ANNOTATIONS:
                self.add_label_annotation(iri)
            top = self.world["http://www.w3.org/2002/07/owl#topObjectProperty"]
            self._special_labels = {
                "Thing": owlready2.Thing,
                "Nothing": owlready2.Nothing,
                "topObjectProperty": top,
                "owl:Thing": owlready2.Thing,
                "owl:Nothing": owlready2.Nothing,
                "owl:topObjectProperty": top,
            }

        return self

    def _load(  # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements
        self,
        only_local=False,
        filename=None,
        format=None,  # pylint: disable=redefined-builtin
        reload=None,
        reload_if_newer=False,
        url_from_catalog=None,
        catalog_file="catalog-v001.xml",
        **kwargs,
    ):
        """Help function for load()."""
        web_protocol = "http://", "https://", "ftp://"

        url = filename if filename else self.base_iri.rstrip("/#")
        if url.startswith(web_protocol):
            baseurl = os.path.dirname(url)
            catalogurl = baseurl + "/" + catalog_file
        else:
            if url.startswith("file://"):
                url = url[7:]
            url = os.path.normpath(os.path.abspath(url))
            baseurl = os.path.dirname(url)
            catalogurl = os.path.join(baseurl, catalog_file)

        def getmtime(path):
            if os.path.exists(path):
                return os.path.getmtime(path)
            return 0.0

        # Resolve url from catalog file
        iris = {}
        dirs = set()
        if url_from_catalog or url_from_catalog is None:
            not_reload = not reload and (
                not reload_if_newer
                or getmtime(catalogurl)
                > self.world._cached_catalogs[catalogurl][0]
            )
            # get iris from catalog already in cached catalogs
            if catalogurl in self.world._cached_catalogs and not_reload:
                _, iris, dirs = self.world._cached_catalogs[catalogurl]
            # do not update cached_catalogs if url already in _iri_mappings
            # and reload not forced
            elif url in self.world._iri_mappings and not_reload:
                pass
            # update iris from current catalogurl
            else:
                try:
                    iris, dirs = read_catalog(
                        uri=catalogurl,
                        recursive=False,
                        return_paths=True,
                        catalog_file=catalog_file,
                    )
                except ReadCatalogError:
                    if url_from_catalog is not None:
                        raise
                    self.world._cached_catalogs[catalogurl] = (0.0, {}, set())
                else:
                    self.world._cached_catalogs[catalogurl] = (
                        getmtime(catalogurl),
                        iris,
                        dirs,
                    )
            self.world._iri_mappings.update(iris)
        resolved_url = self.world._iri_mappings.get(url, url)

        # Append paths from catalog file to onto_path
        for _ in sorted(dirs, reverse=True):
            if _ not in owlready2.onto_path:
                owlready2.onto_path.append(_)

        # Use catalog file to update IRIs of imported ontologies
        # in internal store and try to load again...
        if self.world._iri_mappings:
            for abbrev_iri in self.world._get_obj_triples_sp_o(
                self.storid, owlready2.owl_imports
            ):
                iri = self._unabbreviate(abbrev_iri)
                if iri in self.world._iri_mappings:
                    self._del_obj_triple_spo(
                        self.storid, owlready2.owl_imports, abbrev_iri
                    )
                    self._add_obj_triple_spo(
                        self.storid,
                        owlready2.owl_imports,
                        self._abbreviate(self.world._iri_mappings[iri]),
                    )

        # Load ontology
        try:
            self.loaded = False
            fmt = format if format else guess_format(resolved_url, fmap=FMAP)
            if fmt and fmt not in OWLREADY2_FORMATS:
                # Convert filename to rdfxml before passing it to owlready2
                graph = rdflib.Graph()
                graph.parse(resolved_url, format=fmt)
                with tempfile.NamedTemporaryFile() as handle:
                    graph.serialize(destination=handle, format="xml")
                    handle.seek(0)
                    return super().load(
                        only_local=True,
                        fileobj=handle,
                        reload=reload,
                        reload_if_newer=reload_if_newer,
                        format="rdfxml",
                        **kwargs,
                    )
            elif resolved_url.startswith(web_protocol):
                return super().load(
                    only_local=only_local,
                    reload=reload,
                    reload_if_newer=reload_if_newer,
                    **kwargs,
                )

            else:
                with open(resolved_url, "rb") as handle:
                    return super().load(
                        only_local=only_local,
                        fileobj=handle,
                        reload=reload,
                        reload_if_newer=reload_if_newer,
                        **kwargs,
                    )
        except owlready2.OwlReadyOntologyParsingError:
            # Owlready2 is not able to parse the ontology - most
            # likely because imported ontologies must be resolved
            # using the catalog file.

            # Reraise if we don't want to read from the catalog file
            if not url_from_catalog and url_from_catalog is not None:
                raise

            warnings.warn(
                "Recovering from Owlready2 parsing error... might be deprecated"
            )

            # Copy the ontology into a local folder and try again
            with tempfile.TemporaryDirectory() as handle:
                output = os.path.join(handle, os.path.basename(resolved_url))
                convert_imported(
                    input_ontology=resolved_url,
                    output_ontology=output,
                    input_format=fmt,
                    output_format="xml",
                    url_from_catalog=url_from_catalog,
                    catalog_file=catalog_file,
                )

                self.loaded = False
                with open(output, "rb") as handle:
                    return super().load(
                        only_local=True,
                        fileobj=handle,
                        reload=reload,
                        reload_if_newer=reload_if_newer,
                        format="rdfxml",
                        **kwargs,
                    )

    def save(
        self,
        filename=None,
        format=None,
        dir=".",
        mkdir=False,
        overwrite=False,
        recursive=False,
        squash=False,
        write_catalog_file=False,
        append_catalog=False,
        catalog_file="catalog-v001.xml",
    ):
        """Writes the ontology to file.

        Parameters
        ----------
        filename: None | str | Path
            Name of file to write to.  If None, it defaults to the name
            of the ontology with `format` as file extension.
        format: str
            Output format. The default is to infer it from `filename`.
        dir: str | Path
            If `filename` is a relative path, it is a relative path to `dir`.
        mkdir: bool
            Whether to create output directory if it does not exists.
        owerwrite: bool
            If true and `filename` exists, remove the existing file before
            saving.  The default is to append to an existing ontology.
        recursive: bool
            Whether to save imported ontologies recursively.  This is
            commonly combined with `filename=None`, `dir` and `mkdir`.
        squash: bool
            If true, rdflib will be used to save the current ontology
            together with all its sub-ontologies into `filename`.
            It make no sense to combine this with `recursive`.
        write_catalog_file: bool
            Whether to also write a catalog file to disk.
        append_catalog: bool
            Whether to append to an existing catalog file.
        catalog_file: str | Path
            Name of catalog file.  If not an absolute path, it is prepended
            to `dir`.
        """
        # pylint: disable=redefined-builtin,too-many-arguments
        # pylint: disable=too-many-statements,too-many-branches
        # pylint: disable=too-many-locals,arguments-renamed
        if not _validate_installed_version(
            package="rdflib", min_version="6.0.0"
        ) and format == FMAP.get("ttl", ""):
            from rdflib import (  # pylint: disable=import-outside-toplevel
                __version__ as __rdflib_version__,
            )

            warnings.warn(
                IncompatibleVersion(
                    "To correctly convert to Turtle format, rdflib must be "
                    "version 6.0.0 or greater, however, the detected rdflib "
                    "version used by your Python interpreter is "
                    f"{__rdflib_version__!r}. For more information see the "
                    "'Known issues' section of the README."
                )
            )

        revmap = {value: key for key, value in FMAP.items()}

        if filename is None:
            if format:
                fmt = revmap.get(format, format)
                filename = f"{self.name}.{fmt}"
            else:
                TypeError("`filename` and `format` cannot both be None.")
        filename = os.path.join(dir, filename)
        dir = Path(filename).resolve().parent

        if mkdir:
            outdir = Path(filename).parent.resolve()
            if not outdir.exists():
                outdir.mkdir(parents=True)

        if not format:
            format = guess_format(filename, fmap=FMAP)
        fmt = revmap.get(format, format)

        if overwrite and filename and os.path.exists(filename):
            os.remove(filename)

        EMMO = rdflib.Namespace(  # pylint:disable=invalid-name
            "http://emmo.info/emmo#"
        )

        if recursive:
            if squash:
                raise ValueError(
                    "`recursive` and `squash` should not both be true"
                )
            base = self.base_iri.rstrip("#/")
            for onto in self.imported_ontologies:
                obase = onto.base_iri.rstrip("#/")
                newdir = Path(dir) / os.path.relpath(obase, base)
                onto.save(
                    filename=None,
                    format=format,
                    dir=newdir.resolve(),
                    mkdir=mkdir,
                    overwrite=overwrite,
                    recursive=recursive,
                    squash=squash,
                    write_catalog_file=write_catalog_file,
                    append_catalog=append_catalog,
                    catalog_file=catalog_file,
                )

        if squash:
            from rdflib import (  # pylint:disable=import-outside-toplevel
                URIRef,
                RDF,
                OWL,
            )

            graph = self.world.as_rdflib_graph()
            graph.namespace_manager.bind("emmo", EMMO)

            # Remove anonymous namespace and imports
            graph.remove((URIRef("http://anonymous"), RDF.type, OWL.Ontology))
            imports = list(graph.triples((None, OWL.imports, None)))
            for triple in imports:
                graph.remove(triple)

            graph.serialize(destination=filename, format=format)
        elif format in OWLREADY2_FORMATS:
            super().save(file=filename, format=fmt)
        else:
            # The try-finally clause is needed for cleanup and because
            # we have to provide delete=False to NamedTemporaryFile
            # since Windows does not allow to reopen an already open
            # file.
            try:
                with tempfile.NamedTemporaryFile(
                    suffix=".owl", delete=False
                ) as handle:
                    tmpfile = handle.name
                super().save(tmpfile, format="rdfxml")
                graph = rdflib.Graph()
                graph.parse(tmpfile, format="xml")
                graph.serialize(destination=filename, format=format)
            finally:
                os.remove(tmpfile)

        if write_catalog_file:
            mappings = {}
            base = self.base_iri.rstrip("#/")

            def append(onto):
                obase = onto.base_iri.rstrip("#/")
                newdir = Path(dir) / os.path.relpath(obase, base)
                newpath = newdir.resolve() / f"{onto.name}.{fmt}"
                relpath = os.path.relpath(newpath, dir)
                mappings[onto.get_version(as_iri=True)] = str(relpath)
                for imported in onto.imported_ontologies:
                    append(imported)

            if recursive:
                append(self)
            write_catalog(
                mappings, output=catalog_file, dir=dir, append=append_catalog
            )

    def get_imported_ontologies(self, recursive=False):
        """Return a list with imported ontologies.

        If `recursive` is `True`, ontologies imported by imported ontologies
        are also returned.
        """

        def rec_imported(onto):
            for ontology in onto.imported_ontologies:
                if ontology not in imported:
                    imported.add(ontology)
                    rec_imported(ontology)

        if recursive:
            imported = set()
            rec_imported(self)
            return list(imported)

        return self.imported_ontologies

    def get_entities(  # pylint: disable=too-many-arguments
        self,
        imported=True,
        classes=True,
        individuals=True,
        object_properties=True,
        data_properties=True,
        annotation_properties=True,
    ):
        """Return a generator over (optionally) all classes, individuals,
        object_properties, data_properties and annotation_properties.

        If `imported` is `True`, entities in imported ontologies will also
        be included.
        """
        generator = []
        if classes:
            generator.append(self.classes(imported))
        if individuals:
            generator.append(self.individuals(imported))
        if object_properties:
            generator.append(self.object_properties(imported))
        if data_properties:
            generator.append(self.data_properties(imported))
        if annotation_properties:
            generator.append(self.annotation_properties(imported))
        for entity in itertools.chain(*generator):
            yield entity

    def classes(self, imported=False):
        """Returns an generator over all classes.

        If `imported` is `True`, will imported classes are also returned.
        """
        if imported:
            return self.world.classes()
        return super().classes()

    def individuals(self, imported=False):
        """Returns an generator over all individuals.

        If `imported` is `True`, will imported individuals are also returned.
        """
        if imported:
            return self.world.individuals()
        return super().individuals()

    def object_properties(self, imported=False):
        """Returns an generator over all object properties.

        If `imported` is true, will imported object properties are also
        returned.
        """
        if imported:
            return self.world.object_properties()
        return super().object_properties()

    def data_properties(self, imported=False):
        """Returns an generator over all data properties.

        If `imported` is true, will imported data properties are also
        returned.
        """
        if imported:
            return self.world.data_properties()
        return super().data_properties()

    def annotation_properties(self, imported=False):
        """Returns a generator iterating over all annotation properties
        defined in the current ontology.

        If `imported` is true, annotation properties in imported ontologies
        will also be included.
        """
        if imported:
            return self.world.annotation_properties()
        return super().annotation_properties()

    def get_root_classes(self, imported=False):
        """Returns a list or root classes."""
        return [
            cls
            for cls in self.classes(imported=imported)
            if not cls.ancestors().difference(set([cls, owlready2.Thing]))
        ]

    def get_root_object_properties(self, imported=False):
        """Returns a list of root object properties."""
        props = set(self.object_properties(imported=imported))
        return [p for p in props if not props.intersection(p.is_a)]

    def get_root_data_properties(self, imported=False):
        """Returns a list of root object properties."""
        props = set(self.data_properties(imported=imported))
        return [p for p in props if not props.intersection(p.is_a)]

    def get_roots(self, imported=False):
        """Returns all class, object_property and data_property roots."""
        roots = self.get_root_classes(imported=imported)
        roots.extend(self.get_root_object_properties(imported=imported))
        roots.extend(self.get_root_data_properties(imported=imported))
        return roots

    def sync_python_names(self, annotations=("prefLabel", "label", "altLabel")):
        """Update the `python_name` attribute of all properties.

        The python_name attribute will be set to the first non-empty
        annotation in the sequence of annotations in `annotations` for
        the property.
        """

        def update(gen):
            for prop in gen:
                for annotation in annotations:
                    if hasattr(prop, annotation) and getattr(prop, annotation):
                        prop.python_name = getattr(prop, annotation).first()
                        break

        update(
            self.get_entities(
                classes=False,
                individuals=False,
                object_properties=False,
                data_properties=False,
            )
        )
        update(
            self.get_entities(
                classes=False, individuals=False, annotation_properties=False
            )
        )

    def rename_entities(
        self,
        annotations=("prefLabel", "label", "altLabel"),
    ):
        """Set `name` of all entities to the first non-empty annotation in
        `annotations`.

        Warning, this method changes all IRIs in the ontology.  However,
        it may be useful to make the ontology more readable and to work
        with it together with a triple store.
        """
        for entity in self.get_entities():
            for annotation in annotations:
                if hasattr(entity, annotation):
                    name = getattr(entity, annotation).first()
                    if name:
                        entity.name = name
                        break

    def sync_reasoner(
        self, reasoner="FaCT++", include_imported=False, **kwargs
    ):
        """Update current ontology by running the given reasoner.

        Supported values for `reasoner` are 'Pellet', 'HermiT' and 'FaCT++'.

        If `include_imported` is true, the reasoner will also reason
        over imported ontologies.  Note that this may be **very** slow
        with Pellet and HermiT.

        Keyword arguments are passed to the underlying owlready2 function.
        """
        if reasoner == "FaCT++":
            sync = sync_reasoner_factpp
        elif reasoner == "Pellet":
            sync = owlready2.sync_reasoner_pellet
        elif reasoner == "HermiT":
            sync = owlready2.sync_reasoner_hermit
        else:
            raise ValueError(
                f"unknown reasoner {reasoner!r}. Supported reasoners "
                'are "Pellet", "HermiT" and "FaCT++".'
            )

        # For some reason we must visit all entities once before running
        # the reasoner...
        list(self.get_entities())

        with self:
            if include_imported:
                sync(self.world, **kwargs)
            else:
                sync(self, **kwargs)

    def sync_attributes(  # pylint: disable=too-many-branches
        self,
        name_policy=None,
        name_prefix="",
        class_docstring="comment",
        sync_imported=False,
    ):
        """This method is intended to be called after you have added new
        classes (typically via Python) to make sure that attributes like
        `label` and `comments` are defined.

        If a class, object property, data property or annotation
        property in the current ontology has no label, the name of
        the corresponding Python class will be assigned as label.

        If a class, object property, data property or annotation
        property has no comment, it will be assigned the docstring of
        the corresponding Python class.

        `name_policy` specify wether and how the names in the ontology
        should be updated.  Valid values are:
          None          not changed
          "uuid"        `name_prefix` followed by a global unique id (UUID).
          "sequential"  `name_prefix` followed a sequantial number.
        EMMO conventions imply ``name_policy=='uuid'``.

        If `sync_imported` is true, all imported ontologies are also
        updated.

        The `class_docstring` argument specifies the annotation that
        class docstrings are mapped to.  Defaults to "comment".
        """
        for cls in itertools.chain(
            self.classes(),
            self.object_properties(),
            self.data_properties(),
            self.annotation_properties(),
        ):
            if not hasattr(cls, "prefLabel"):
                # no prefLabel - create new annotation property..
                with self:

                    # pylint: disable=invalid-name,missing-class-docstring
                    # pylint: disable=unused-variable
                    class prefLabel(owlready2.label):
                        pass

                cls.prefLabel = [locstr(cls.__name__, lang="en")]
            elif not cls.prefLabel:
                cls.prefLabel.append(locstr(cls.__name__, lang="en"))
            if class_docstring and hasattr(cls, "__doc__") and cls.__doc__:
                getattr(cls, class_docstring).append(
                    locstr(inspect.cleandoc(cls.__doc__), lang="en")
                )

        for ind in self.individuals():
            if not hasattr(ind, "prefLabel"):
                # no prefLabel - create new annotation property..
                with self:
                    # pylint: disable=invalid-name,missing-class-docstring
                    # pylint: disable=function-redefined
                    class prefLabel(owlready2.label):
                        iri = "http://www.w3.org/2004/02/skos/core#prefLabel"

                ind.prefLabel = [locstr(ind.name, lang="en")]
            elif not ind.prefLabel:
                ind.prefLabel.append(locstr(ind.name, lang="en"))

        chain = itertools.chain(
            self.classes(),
            self.individuals(),
            self.object_properties(),
            self.data_properties(),
            self.annotation_properties(),
        )
        if name_policy == "uuid":
            for obj in chain:
                obj.name = name_prefix + str(
                    uuid.uuid5(uuid.NAMESPACE_DNS, obj.name)
                )
        elif name_policy == "sequential":
            for obj in chain:
                counter = 0
                while f"{self.base_iri}{name_prefix}{counter}" in self:
                    counter += 1
                obj.name = name_prefix + str(counter)
        elif name_policy is not None:
            raise TypeError(f"invalid name_policy: {name_policy!r}")

        if sync_imported:
            for onto in self.imported_ontologies:
                onto.sync_attributes()

    def get_relations(self):
        """Returns a generator for all relations."""
        warnings.warn(
            "Ontology.get_relations() is deprecated. Use "
            "onto.object_properties() instead.",
            DeprecationWarning,
        )
        return self.object_properties()

    def get_annotations(self, entity):
        """Returns a dict with annotations for `entity`.  Entity may be given
        either as a ThingClass object or as a label."""
        warnings.warn(
            "Ontology.get_annotations(entity) is deprecated. Use "
            "entity.get_annotations() instead.",
            DeprecationWarning,
        )

        if isinstance(entity, str):
            entity = self.get_by_label(entity)
        res = {"comment": getattr(entity, "comment", "")}
        for annotation in self.annotation_properties():
            res[annotation.label.first()] = [
                obj.strip('"')
                for _, _, obj in self.get_triples(
                    entity.storid, annotation.storid, None
                )
            ]
        return res

    def get_branch(  # pylint: disable=too-many-arguments
        self,
        root,
        leafs=(),
        include_leafs=True,
        strict_leafs=False,
        exclude=None,
        sort=False,
    ):
        """Returns a set with all direct and indirect subclasses of `root`.
        Any subclass found in the sequence `leafs` will be included in
        the returned list, but its subclasses will not.  The elements
        of `leafs` may be ThingClass objects or labels.

        Subclasses of any subclass found in the sequence `leafs` will
        be excluded from the returned list, where the elements of `leafs`
        may be ThingClass objects or labels.

        If `include_leafs` is true, the leafs are included in the returned
        list, otherwise they are not.

        If `strict_leafs` is true, any descendant of a leaf will be excluded
        in the returned set.

        If given, `exclude` may be a sequence of classes, including
        their subclasses, to exclude from the output.

        If `sort` is True, a list sorted according to depth and label
        will be returned instead of a set.
        """

        def _branch(root, leafs):
            if root not in leafs:
                branch = {
                    root,
                }
                for cls in root.subclasses():
                    # Defining a branch is actually quite tricky.  Consider
                    # the case:
                    #
                    #      L isA R
                    #      A isA L
                    #      A isA R
                    #
                    # where R is the root, L is a leaf and A is a direct
                    # child of both.  Logically, since A is a child of the
                    # leaf we want to skip A.  But a strait forward imple-
                    # mentation will see that A is a child of the root and
                    # include it.  Requireing that the R should be a strict
                    # parent of A solves this.
                    if root in cls.get_parents(strict=True):
                        branch.update(_branch(cls, leafs))
            else:
                branch = (
                    {
                        root,
                    }
                    if include_leafs
                    else set()
                )
            return branch

        if isinstance(root, str):
            root = self.get_by_label(root)

        leafs = set(
            self.get_by_label(leaf) if isinstance(leaf, str) else leaf
            for leaf in leafs
        )
        leafs.discard(root)

        if exclude:
            exclude = set(
                self.get_by_label(e) if isinstance(e, str) else e
                for e in exclude
            )
            leafs.update(exclude)

        branch = _branch(root, leafs)

        # Exclude all descendants of any leaf
        if strict_leafs:
            descendants = root.descendants()
            for leaf in leafs:
                if leaf in descendants:
                    branch.difference_update(
                        leaf.descendants(include_self=False)
                    )

        if exclude:
            branch.difference_update(exclude)

        # Sort according to depth, then by label
        if sort:
            branch = sorted(
                sorted(branch, key=asstring),
                key=lambda x: len(x.mro()),
            )

        return branch

    def is_individual(self, entity):
        """Returns true if entity is an individual."""
        if isinstance(entity, str):
            entity = self.get_by_label(entity)
        return isinstance(entity, owlready2.Thing)

    # FIXME - deprecate this method as soon the ThingClass property
    #         `defined_class` works correct in Owlready2
    def is_defined(self, entity):
        """Returns true if the entity is a defined class."""
        if isinstance(entity, str):
            entity = self.get_by_label(entity)
        return hasattr(entity, "equivalent_to") and bool(entity.equivalent_to)

    def get_version(self, as_iri=False) -> str:
        """Returns the version number of the ontology as inferred from the
        owl:versionIRI tag or, if owl:versionIRI is not found, from
        owl:versionINFO.

        If `as_iri` is True, the full versionIRI is returned.
        """
        version_iri_storid = self.world._abbreviate(
            "http://www.w3.org/2002/07/owl#versionIRI"
        )
        tokens = self.get_triples(s=self.storid, p=version_iri_storid)
        if (not tokens) and (as_iri is True):
            raise TypeError(
                "No owl:versionIRI "
                f"in Ontology {self.base_iri!r}. "
                "Search for owl:versionInfo with as_iri=False"
            )
        if tokens:
            _, _, obj = tokens[0]
            version_iri = self.world._unabbreviate(obj)
            if as_iri:
                return version_iri
            return infer_version(self.base_iri, version_iri)

        version_info_storid = self.world._abbreviate(
            "http://www.w3.org/2002/07/owl#versionInfo"
        )
        tokens = self.get_triples(s=self.storid, p=version_info_storid)
        if not tokens:
            raise TypeError(
                "No versionIRI or versionInfo " f"in Ontology {self.base_iri!r}"
            )
        _, _, version_info = tokens[0]
        return version_info.strip('"').strip("'")

    def set_version(self, version=None, version_iri=None):
        """Assign version to ontology by asigning owl:versionIRI.

        If `version` but not `version_iri` is provided, the version
        IRI will be the combination of `base_iri` and `version`.
        """
        _version_iri = "http://www.w3.org/2002/07/owl#versionIRI"
        version_iri_storid = self.world._abbreviate(_version_iri)
        if self._has_obj_triple_spo(  # pylint: disable=unexpected-keyword-arg
            # For some reason _has_obj_triples_spo exists in both
            # owlready2.namespace.Namespace (with arguments subject/predicate)
            # and in owlready2.triplelite._GraphManager (with arguments s/p)
            # owlready2.Ontology inherits from Namespace directly
            # and pylint checks that.
            # It actually accesses the one in triplelite.
            # subject=self.storid, predicate=version_iri_storid
            s=self.storid,
            p=version_iri_storid,
        ):
            self._del_obj_triple_spo(s=self.storid, p=version_iri_storid)

        if not version_iri:
            if not version:
                raise TypeError(
                    "Either `version` or `version_iri` must be provided"
                )
            head, tail = self.base_iri.rstrip("#/").rsplit("/", 1)
            version_iri = "/".join([head, version, tail])

        self._add_obj_triple_spo(
            s=self.storid,
            p=self.world._abbreviate(_version_iri),
            o=self.world._abbreviate(version_iri),
        )

    def get_graph(self, **kwargs):
        """Returns a new graph object.  See  emmo.graph.OntoGraph.

        Note that this method requires the Python graphviz package.
        """
        # pylint: disable=import-outside-toplevel,cyclic-import
        from ontopy.graph import OntoGraph as NewOntoGraph

        return NewOntoGraph(self, **kwargs)

    @staticmethod
    def common_ancestors(cls1, cls2):
        """Return a list of common ancestors for `cls1` and `cls2`."""
        return set(cls1.ancestors()).intersection(cls2.ancestors())

    def number_of_generations(self, descendant, ancestor):
        """Return shortest distance from ancestor to descendant"""
        if ancestor not in descendant.ancestors():
            raise ValueError("Descendant is not a descendant of ancestor")
        return self._number_of_generations(descendant, ancestor, 0)

    def _number_of_generations(self, descendant, ancestor, counter):
        """Recursive help function to number_of_generations(), return
        distance between a ancestor-descendant pair (counter+1)."""
        if descendant.name == ancestor.name:
            return counter
        try:
            return min(
                self._number_of_generations(parent, ancestor, counter + 1)
                for parent in descendant.get_parents()
                if ancestor in parent.ancestors()
            )
        except ValueError:
            return counter

    def closest_common_ancestors(self, cls1, cls2):
        """Returns a list with closest_common_ancestor for cls1 and cls2"""
        distances = {}
        for ancestor in self.common_ancestors(cls1, cls2):
            distances[ancestor] = self.number_of_generations(
                cls1, ancestor
            ) + self.number_of_generations(cls2, ancestor)
        return [
            ancestor
            for ancestor, distance in distances.items()
            if distance == min(distances.values())
        ]

    @staticmethod
    def closest_common_ancestor(*classes):
        """Returns closest_common_ancestor for the given classes."""
        mros = [cls.mro() for cls in classes]
        track = defaultdict(int)
        while mros:
            for mro in mros:
                cur = mro.pop(0)
                track[cur] += 1
                if track[cur] == len(classes):
                    return cur
                if len(mro) == 0:
                    mros.remove(mro)
        raise Exception("A closest common ancestor should always exist !")

    def get_ancestors(self, classes, include="all", strict=True):
        """Return ancestors of all classes in `classes`.
        classes to be provided as list

        The values of `include` may be:
          - None: ignore this argument
          - "all": Include all ancestors.
          - "closest": Include all ancestors up to the closest common
            ancestor of all classes.
          - int: Include this number of ancestor levels.  Here `include`
            may be an integer or a string that can be converted to int.
        """
        ancestors = set()
        if not classes:
            return ancestors

        def addancestors(entity, counter, subject):
            if counter > 0:
                for parent in entity.get_parents(strict=True):
                    subject.add(parent)
                    addancestors(parent, counter - 1, subject)

        if isinstance(include, str) and include.isdigit():
            include = int(include)

        if include == "all":
            ancestors.update(*(_.ancestors() for _ in classes))
        elif include == "closest":
            closest = self.closest_common_ancestor(*classes)
            for cls in classes:
                ancestors.update(
                    _ for _ in cls.ancestors() if closest in _.ancestors()
                )
        elif isinstance(include, int):
            for entity in classes:
                addancestors(entity, int(include), ancestors)
        elif include not in (None, "None", "none", ""):
            raise ValueError('include must be "all", "closest" or None')

        if strict:
            return ancestors.difference(classes)
        return ancestors

    def get_descendants(
        self,
        classes: "Union[List, ThingClass]",
        common: bool = False,
        generations: int = None,
    ) -> set:
        """Return descendants/subclasses of all classes in `classes`.
        Args:
            classes: to be provided as list.
            common: whether to only return descendants common to all classes.
            generations: Include this number of generations, default is all.
        Returns:
            A set of descendants for given number of generations.
            If 'common'=True, the common descendants are returned
            within the specified number of generations.
            'generations' defaults to all.
        """

        if not isinstance(classes, Sequence):
            classes = [classes]

        descendants = {name: [] for name in classes}

        def _children_recursively(num, newentity, parent, descendants):
            """Helper function to get all children up to generation."""
            for child in self.get_children_of(newentity):
                descendants[parent].append(child)
                if num < generations:
                    _children_recursively(num + 1, child, parent, descendants)

        if generations == 0:
            return set()

        if not generations:
            for entity in classes:
                descendants[entity] = entity.descendants()
                # only include proper descendants
                descendants[entity].remove(entity)
        else:
            for entity in classes:
                _children_recursively(1, entity, entity, descendants)

        results = descendants.values()
        if common is True:
            return set.intersection(*map(set, results))
        return set(flatten(results))

    def get_wu_palmer_measure(self, cls1, cls2):
        """Return Wu-Palmer measure for semantic similarity.

        Returns Wu-Palmer measure for semantic similarity between
        two concepts.
        Wu, Palmer; ACL 94: Proceedings of the 32nd annual meeting on
        Association for Computational Linguistics, June 1994.
        """
        cca = self.closest_common_ancestor(cls1, cls2)
        ccadepth = self.number_of_generations(cca, self.Thing)
        generations1 = self.number_of_generations(cls1, cca)
        generations2 = self.number_of_generations(cls2, cca)
        return 2 * ccadepth / (generations1 + generations2 + 2 * ccadepth)

    def new_entity(
        self, name: str, parent: Union[ThingClass, Iterable]
    ) -> ThingClass:
        """Create and return new entity

        Makes a new entity in the ontology with given parent(s).
        Return the new entity.

        Throws exception if name consists of more than one word.
        """
        if len(name.split(" ")) > 1:
            raise LabelDefinitionError(
                f"Error in label name definition '{name}': "
                f"Label consists of more than one word."
            )
        parents = tuple(parent) if isinstance(parent, Iterable) else (parent,)
        for thing in parents:
            if not isinstance(thing, owlready2.ThingClass):
                raise ThingClassDefinitionError(
                    f"Error in parent definition: "
                    f"'{thing}' is not an owlready2.ThingClass."
                )

        with self:
            entity = types.new_class(name, parents)
        return entity

__eq__(other)

Checks if this ontology is equal to other.

This function compares the result of set(self.get_unabbreviated_triples(label='_:b')), i.e. blank nodes are not distinguished, but relations to blank nodes are included.

Source code in ontopy/ontology.py
241
242
243
244
245
246
247
248
249
250
251
def __eq__(self, other):
    """Checks if this ontology is equal to `other`.

    This function compares the result of
    ``set(self.get_unabbreviated_triples(label='_:b'))``,
    i.e. blank nodes are not distinguished, but relations to blank
    nodes are included.
    """
    return set(self.get_unabbreviated_triples(label="_:b")) == set(
        other.get_unabbreviated_triples(label="_:b")
    )

__hash__()

Returns a hash based on base_iri. This is done to keep Ontology hashable when defining eq.

Source code in ontopy/ontology.py
235
236
237
238
239
def __hash__(self):
    """Returns a hash based on base_iri.
    This is done to keep Ontology hashable when defining __eq__.
    """
    return hash(self.base_iri)

_load(only_local=False, filename=None, format=None, reload=None, reload_if_newer=False, url_from_catalog=None, catalog_file='catalog-v001.xml', **kwargs)

Help function for load().

Source code in ontopy/ontology.py
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
def _load(  # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements
    self,
    only_local=False,
    filename=None,
    format=None,  # pylint: disable=redefined-builtin
    reload=None,
    reload_if_newer=False,
    url_from_catalog=None,
    catalog_file="catalog-v001.xml",
    **kwargs,
):
    """Help function for load()."""
    web_protocol = "http://", "https://", "ftp://"

    url = filename if filename else self.base_iri.rstrip("/#")
    if url.startswith(web_protocol):
        baseurl = os.path.dirname(url)
        catalogurl = baseurl + "/" + catalog_file
    else:
        if url.startswith("file://"):
            url = url[7:]
        url = os.path.normpath(os.path.abspath(url))
        baseurl = os.path.dirname(url)
        catalogurl = os.path.join(baseurl, catalog_file)

    def getmtime(path):
        if os.path.exists(path):
            return os.path.getmtime(path)
        return 0.0

    # Resolve url from catalog file
    iris = {}
    dirs = set()
    if url_from_catalog or url_from_catalog is None:
        not_reload = not reload and (
            not reload_if_newer
            or getmtime(catalogurl)
            > self.world._cached_catalogs[catalogurl][0]
        )
        # get iris from catalog already in cached catalogs
        if catalogurl in self.world._cached_catalogs and not_reload:
            _, iris, dirs = self.world._cached_catalogs[catalogurl]
        # do not update cached_catalogs if url already in _iri_mappings
        # and reload not forced
        elif url in self.world._iri_mappings and not_reload:
            pass
        # update iris from current catalogurl
        else:
            try:
                iris, dirs = read_catalog(
                    uri=catalogurl,
                    recursive=False,
                    return_paths=True,
                    catalog_file=catalog_file,
                )
            except ReadCatalogError:
                if url_from_catalog is not None:
                    raise
                self.world._cached_catalogs[catalogurl] = (0.0, {}, set())
            else:
                self.world._cached_catalogs[catalogurl] = (
                    getmtime(catalogurl),
                    iris,
                    dirs,
                )
        self.world._iri_mappings.update(iris)
    resolved_url = self.world._iri_mappings.get(url, url)

    # Append paths from catalog file to onto_path
    for _ in sorted(dirs, reverse=True):
        if _ not in owlready2.onto_path:
            owlready2.onto_path.append(_)

    # Use catalog file to update IRIs of imported ontologies
    # in internal store and try to load again...
    if self.world._iri_mappings:
        for abbrev_iri in self.world._get_obj_triples_sp_o(
            self.storid, owlready2.owl_imports
        ):
            iri = self._unabbreviate(abbrev_iri)
            if iri in self.world._iri_mappings:
                self._del_obj_triple_spo(
                    self.storid, owlready2.owl_imports, abbrev_iri
                )
                self._add_obj_triple_spo(
                    self.storid,
                    owlready2.owl_imports,
                    self._abbreviate(self.world._iri_mappings[iri]),
                )

    # Load ontology
    try:
        self.loaded = False
        fmt = format if format else guess_format(resolved_url, fmap=FMAP)
        if fmt and fmt not in OWLREADY2_FORMATS:
            # Convert filename to rdfxml before passing it to owlready2
            graph = rdflib.Graph()
            graph.parse(resolved_url, format=fmt)
            with tempfile.NamedTemporaryFile() as handle:
                graph.serialize(destination=handle, format="xml")
                handle.seek(0)
                return super().load(
                    only_local=True,
                    fileobj=handle,
                    reload=reload,
                    reload_if_newer=reload_if_newer,
                    format="rdfxml",
                    **kwargs,
                )
        elif resolved_url.startswith(web_protocol):
            return super().load(
                only_local=only_local,
                reload=reload,
                reload_if_newer=reload_if_newer,
                **kwargs,
            )

        else:
            with open(resolved_url, "rb") as handle:
                return super().load(
                    only_local=only_local,
                    fileobj=handle,
                    reload=reload,
                    reload_if_newer=reload_if_newer,
                    **kwargs,
                )
    except owlready2.OwlReadyOntologyParsingError:
        # Owlready2 is not able to parse the ontology - most
        # likely because imported ontologies must be resolved
        # using the catalog file.

        # Reraise if we don't want to read from the catalog file
        if not url_from_catalog and url_from_catalog is not None:
            raise

        warnings.warn(
            "Recovering from Owlready2 parsing error... might be deprecated"
        )

        # Copy the ontology into a local folder and try again
        with tempfile.TemporaryDirectory() as handle:
            output = os.path.join(handle, os.path.basename(resolved_url))
            convert_imported(
                input_ontology=resolved_url,
                output_ontology=output,
                input_format=fmt,
                output_format="xml",
                url_from_catalog=url_from_catalog,
                catalog_file=catalog_file,
            )

            self.loaded = False
            with open(output, "rb") as handle:
                return super().load(
                    only_local=True,
                    fileobj=handle,
                    reload=reload,
                    reload_if_newer=reload_if_newer,
                    format="rdfxml",
                    **kwargs,
                )

_number_of_generations(descendant, ancestor, counter)

Recursive help function to number_of_generations(), return distance between a ancestor-descendant pair (counter+1).

Source code in ontopy/ontology.py
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
def _number_of_generations(self, descendant, ancestor, counter):
    """Recursive help function to number_of_generations(), return
    distance between a ancestor-descendant pair (counter+1)."""
    if descendant.name == ancestor.name:
        return counter
    try:
        return min(
            self._number_of_generations(parent, ancestor, counter + 1)
            for parent in descendant.get_parents()
            if ancestor in parent.ancestors()
        )
    except ValueError:
        return counter

add_label_annotation(iri)

Adds label annotation used by get_by_label().

May be provided either as an IRI or as its owlready2 representation.

Source code in ontopy/ontology.py
356
357
358
359
360
361
362
363
364
365
def add_label_annotation(self, iri):
    """Adds label annotation used by get_by_label().

    May be provided either as an IRI or as its owlready2 representation.
    """
    label_annotation = iri if hasattr(iri, "storid") else self.world[iri]
    if not label_annotation:
        raise ValueError(f"IRI not in ontology: {iri}")
    if label_annotation not in self._label_annotations:
        self._label_annotations.append(label_annotation)

annotation_properties(imported=False)

Returns a generator iterating over all annotation properties defined in the current ontology.

If imported is true, annotation properties in imported ontologies will also be included.

Source code in ontopy/ontology.py
869
870
871
872
873
874
875
876
877
878
def annotation_properties(self, imported=False):
    """Returns a generator iterating over all annotation properties
    defined in the current ontology.

    If `imported` is true, annotation properties in imported ontologies
    will also be included.
    """
    if imported:
        return self.world.annotation_properties()
    return super().annotation_properties()

classes(imported=False)

Returns an generator over all classes.

If imported is True, will imported classes are also returned.

Source code in ontopy/ontology.py
831
832
833
834
835
836
837
838
def classes(self, imported=False):
    """Returns an generator over all classes.

    If `imported` is `True`, will imported classes are also returned.
    """
    if imported:
        return self.world.classes()
    return super().classes()

closest_common_ancestor(*classes) staticmethod

Returns closest_common_ancestor for the given classes.

Source code in ontopy/ontology.py
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
@staticmethod
def closest_common_ancestor(*classes):
    """Returns closest_common_ancestor for the given classes."""
    mros = [cls.mro() for cls in classes]
    track = defaultdict(int)
    while mros:
        for mro in mros:
            cur = mro.pop(0)
            track[cur] += 1
            if track[cur] == len(classes):
                return cur
            if len(mro) == 0:
                mros.remove(mro)
    raise Exception("A closest common ancestor should always exist !")

closest_common_ancestors(cls1, cls2)

Returns a list with closest_common_ancestor for cls1 and cls2

Source code in ontopy/ontology.py
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
def closest_common_ancestors(self, cls1, cls2):
    """Returns a list with closest_common_ancestor for cls1 and cls2"""
    distances = {}
    for ancestor in self.common_ancestors(cls1, cls2):
        distances[ancestor] = self.number_of_generations(
            cls1, ancestor
        ) + self.number_of_generations(cls2, ancestor)
    return [
        ancestor
        for ancestor, distance in distances.items()
        if distance == min(distances.values())
    ]

common_ancestors(cls1, cls2) staticmethod

Return a list of common ancestors for cls1 and cls2.

Source code in ontopy/ontology.py
1306
1307
1308
1309
@staticmethod
def common_ancestors(cls1, cls2):
    """Return a list of common ancestors for `cls1` and `cls2`."""
    return set(cls1.ancestors()).intersection(cls2.ancestors())

data_properties(imported=False)

Returns an generator over all data properties.

If imported is true, will imported data properties are also returned.

Source code in ontopy/ontology.py
859
860
861
862
863
864
865
866
867
def data_properties(self, imported=False):
    """Returns an generator over all data properties.

    If `imported` is true, will imported data properties are also
    returned.
    """
    if imported:
        return self.world.data_properties()
    return super().data_properties()

get_ancestors(classes, include='all', strict=True)

Return ancestors of all classes in classes. classes to be provided as list

The values of include may be: - None: ignore this argument - "all": Include all ancestors. - "closest": Include all ancestors up to the closest common ancestor of all classes. - int: Include this number of ancestor levels. Here include may be an integer or a string that can be converted to int.

Source code in ontopy/ontology.py
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
def get_ancestors(self, classes, include="all", strict=True):
    """Return ancestors of all classes in `classes`.
    classes to be provided as list

    The values of `include` may be:
      - None: ignore this argument
      - "all": Include all ancestors.
      - "closest": Include all ancestors up to the closest common
        ancestor of all classes.
      - int: Include this number of ancestor levels.  Here `include`
        may be an integer or a string that can be converted to int.
    """
    ancestors = set()
    if not classes:
        return ancestors

    def addancestors(entity, counter, subject):
        if counter > 0:
            for parent in entity.get_parents(strict=True):
                subject.add(parent)
                addancestors(parent, counter - 1, subject)

    if isinstance(include, str) and include.isdigit():
        include = int(include)

    if include == "all":
        ancestors.update(*(_.ancestors() for _ in classes))
    elif include == "closest":
        closest = self.closest_common_ancestor(*classes)
        for cls in classes:
            ancestors.update(
                _ for _ in cls.ancestors() if closest in _.ancestors()
            )
    elif isinstance(include, int):
        for entity in classes:
            addancestors(entity, int(include), ancestors)
    elif include not in (None, "None", "none", ""):
        raise ValueError('include must be "all", "closest" or None')

    if strict:
        return ancestors.difference(classes)
    return ancestors

get_annotations(entity)

Returns a dict with annotations for entity. Entity may be given either as a ThingClass object or as a label.

Source code in ontopy/ontology.py
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
def get_annotations(self, entity):
    """Returns a dict with annotations for `entity`.  Entity may be given
    either as a ThingClass object or as a label."""
    warnings.warn(
        "Ontology.get_annotations(entity) is deprecated. Use "
        "entity.get_annotations() instead.",
        DeprecationWarning,
    )

    if isinstance(entity, str):
        entity = self.get_by_label(entity)
    res = {"comment": getattr(entity, "comment", "")}
    for annotation in self.annotation_properties():
        res[annotation.label.first()] = [
            obj.strip('"')
            for _, _, obj in self.get_triples(
                entity.storid, annotation.storid, None
            )
        ]
    return res

get_branch(root, leafs=(), include_leafs=True, strict_leafs=False, exclude=None, sort=False)

Returns a set with all direct and indirect subclasses of root. Any subclass found in the sequence leafs will be included in the returned list, but its subclasses will not. The elements of leafs may be ThingClass objects or labels.

Subclasses of any subclass found in the sequence leafs will be excluded from the returned list, where the elements of leafs may be ThingClass objects or labels.

If include_leafs is true, the leafs are included in the returned list, otherwise they are not.

If strict_leafs is true, any descendant of a leaf will be excluded in the returned set.

If given, exclude may be a sequence of classes, including their subclasses, to exclude from the output.

If sort is True, a list sorted according to depth and label will be returned instead of a set.

Source code in ontopy/ontology.py
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
def get_branch(  # pylint: disable=too-many-arguments
    self,
    root,
    leafs=(),
    include_leafs=True,
    strict_leafs=False,
    exclude=None,
    sort=False,
):
    """Returns a set with all direct and indirect subclasses of `root`.
    Any subclass found in the sequence `leafs` will be included in
    the returned list, but its subclasses will not.  The elements
    of `leafs` may be ThingClass objects or labels.

    Subclasses of any subclass found in the sequence `leafs` will
    be excluded from the returned list, where the elements of `leafs`
    may be ThingClass objects or labels.

    If `include_leafs` is true, the leafs are included in the returned
    list, otherwise they are not.

    If `strict_leafs` is true, any descendant of a leaf will be excluded
    in the returned set.

    If given, `exclude` may be a sequence of classes, including
    their subclasses, to exclude from the output.

    If `sort` is True, a list sorted according to depth and label
    will be returned instead of a set.
    """

    def _branch(root, leafs):
        if root not in leafs:
            branch = {
                root,
            }
            for cls in root.subclasses():
                # Defining a branch is actually quite tricky.  Consider
                # the case:
                #
                #      L isA R
                #      A isA L
                #      A isA R
                #
                # where R is the root, L is a leaf and A is a direct
                # child of both.  Logically, since A is a child of the
                # leaf we want to skip A.  But a strait forward imple-
                # mentation will see that A is a child of the root and
                # include it.  Requireing that the R should be a strict
                # parent of A solves this.
                if root in cls.get_parents(strict=True):
                    branch.update(_branch(cls, leafs))
        else:
            branch = (
                {
                    root,
                }
                if include_leafs
                else set()
            )
        return branch

    if isinstance(root, str):
        root = self.get_by_label(root)

    leafs = set(
        self.get_by_label(leaf) if isinstance(leaf, str) else leaf
        for leaf in leafs
    )
    leafs.discard(root)

    if exclude:
        exclude = set(
            self.get_by_label(e) if isinstance(e, str) else e
            for e in exclude
        )
        leafs.update(exclude)

    branch = _branch(root, leafs)

    # Exclude all descendants of any leaf
    if strict_leafs:
        descendants = root.descendants()
        for leaf in leafs:
            if leaf in descendants:
                branch.difference_update(
                    leaf.descendants(include_self=False)
                )

    if exclude:
        branch.difference_update(exclude)

    # Sort according to depth, then by label
    if sort:
        branch = sorted(
            sorted(branch, key=asstring),
            key=lambda x: len(x.mro()),
        )

    return branch

get_by_label(label, label_annotations=None, namespace=None)

Returns entity with label annotation label.

label_annotations is a sequence of label annotation names to look up. Defaults to the label_annotations property.

If namespace is provided, it should be the last component of the base iri of an ontology (with trailing slash (/) or hash (#) stripped off). The search for a matching label will be limited to this namespace.

If several entities have the same label, only the one which is found first is returned.Use get_by_label_all() to get all matches.

A NoSuchLabelError is raised if label cannot be found.

Note

The current implementation also supports "*" as a wildcard matching any number of characters. This may change in the future.

Source code in ontopy/ontology.py
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
def get_by_label(
    self, label, label_annotations=None, namespace=None
):  # pylint: disable=too-many-arguments,too-many-branches
    """Returns entity with label annotation `label`.

    `label_annotations` is a sequence of label annotation names to look up.
    Defaults to the `label_annotations` property.

    If `namespace` is provided, it should be the last component of
    the base iri of an ontology (with trailing slash (/) or hash
    (#) stripped off).  The search for a matching label will be
    limited to this namespace.

    If several entities have the same label, only the one which is
    found first is returned.Use get_by_label_all() to get all matches.

    A NoSuchLabelError is raised if `label` cannot be found.

    Note
    ----
    The current implementation also supports "*" as a wildcard
    matching any number of characters. This may change in the future.
    """
    if not isinstance(label, str):
        raise TypeError(
            f"Invalid label definition, must be a string: {label!r}"
        )
    if " " in label:
        raise ValueError(
            f"Invalid label definition, {label!r} contains spaces."
        )

    if "namespaces" in self.__dict__:
        if namespace:
            if namespace in self.namespaces:
                for entity in self.get_by_label_all(
                    label, label_annotations=label_annotations
                ):
                    if entity.namespace == self.namespaces[namespace]:
                        return entity
            raise NoSuchLabelError(
                f"No label annotations matches {label!r} in namespace "
                f"{namespace!r}"
            )
        if label in self.namespaces:
            return self.namespaces[label]

    if label_annotations is None:
        annotations = (a.name for a in self.label_annotations)
    else:
        annotations = (
            a.name if hasattr(a, "storid") else a for a in label_annotations
        )
    for key in annotations:
        entity = self.search_one(**{key: label})
        if entity:
            return entity

    if self._special_labels and label in self._special_labels:
        return self._special_labels[label]

    entity = self.world[self.base_iri + label]
    if entity:
        return entity

    raise NoSuchLabelError(f"No label annotations matches {label!r}")

get_by_label_all(label, label_annotations=None, namespace=None)

Like get_by_label(), but returns a list with all matching labels.

Returns an empty list if no matches could be found.

Source code in ontopy/ontology.py
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
def get_by_label_all(self, label, label_annotations=None, namespace=None):
    """Like get_by_label(), but returns a list with all matching labels.

    Returns an empty list if no matches could be found.
    """
    if not isinstance(label, str):
        raise TypeError(
            f"Invalid label definition, " f"must be a string: {label!r}"
        )
    if " " in label:
        raise ValueError(
            f"Invalid label definition, {label!r} contains spaces."
        )

    if label_annotations is None:
        annotations = (_.name for _ in self.label_annotations)
    else:
        annotations = (
            _.name if hasattr(_, "storid") else _ for _ in label_annotations
        )
    entity = self.world.search(**{annotations.__next__(): label})
    for key in annotations:
        entity.extend(self.world.search(**{key: label}))
    if self._special_labels and label in self._special_labels:
        entity.append(self._special_labels[label])
    if namespace:
        return [_ for _ in entity if _.namespace.name == namespace]
    return entity

get_descendants(classes, common=False, generations=None)

Return descendants/subclasses of all classes in classes.

Parameters:

Name Type Description Default
classes Union[List, ThingClass]

to be provided as list.

required
common bool

whether to only return descendants common to all classes.

False
generations int

Include this number of generations, default is all.

None

Returns:

Type Description
set

A set of descendants for given number of generations.

set

If 'common'=True, the common descendants are returned

set

within the specified number of generations.

set

'generations' defaults to all.

Source code in ontopy/ontology.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
def get_descendants(
    self,
    classes: "Union[List, ThingClass]",
    common: bool = False,
    generations: int = None,
) -> set:
    """Return descendants/subclasses of all classes in `classes`.
    Args:
        classes: to be provided as list.
        common: whether to only return descendants common to all classes.
        generations: Include this number of generations, default is all.
    Returns:
        A set of descendants for given number of generations.
        If 'common'=True, the common descendants are returned
        within the specified number of generations.
        'generations' defaults to all.
    """

    if not isinstance(classes, Sequence):
        classes = [classes]

    descendants = {name: [] for name in classes}

    def _children_recursively(num, newentity, parent, descendants):
        """Helper function to get all children up to generation."""
        for child in self.get_children_of(newentity):
            descendants[parent].append(child)
            if num < generations:
                _children_recursively(num + 1, child, parent, descendants)

    if generations == 0:
        return set()

    if not generations:
        for entity in classes:
            descendants[entity] = entity.descendants()
            # only include proper descendants
            descendants[entity].remove(entity)
    else:
        for entity in classes:
            _children_recursively(1, entity, entity, descendants)

    results = descendants.values()
    if common is True:
        return set.intersection(*map(set, results))
    return set(flatten(results))

get_entities(imported=True, classes=True, individuals=True, object_properties=True, data_properties=True, annotation_properties=True)

Return a generator over (optionally) all classes, individuals, object_properties, data_properties and annotation_properties.

If imported is True, entities in imported ontologies will also be included.

Source code in ontopy/ontology.py
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
def get_entities(  # pylint: disable=too-many-arguments
    self,
    imported=True,
    classes=True,
    individuals=True,
    object_properties=True,
    data_properties=True,
    annotation_properties=True,
):
    """Return a generator over (optionally) all classes, individuals,
    object_properties, data_properties and annotation_properties.

    If `imported` is `True`, entities in imported ontologies will also
    be included.
    """
    generator = []
    if classes:
        generator.append(self.classes(imported))
    if individuals:
        generator.append(self.individuals(imported))
    if object_properties:
        generator.append(self.object_properties(imported))
    if data_properties:
        generator.append(self.data_properties(imported))
    if annotation_properties:
        generator.append(self.annotation_properties(imported))
    for entity in itertools.chain(*generator):
        yield entity

get_graph(**kwargs)

Returns a new graph object. See emmo.graph.OntoGraph.

Note that this method requires the Python graphviz package.

Source code in ontopy/ontology.py
1296
1297
1298
1299
1300
1301
1302
1303
1304
def get_graph(self, **kwargs):
    """Returns a new graph object.  See  emmo.graph.OntoGraph.

    Note that this method requires the Python graphviz package.
    """
    # pylint: disable=import-outside-toplevel,cyclic-import
    from ontopy.graph import OntoGraph as NewOntoGraph

    return NewOntoGraph(self, **kwargs)

get_imported_ontologies(recursive=False)

Return a list with imported ontologies.

If recursive is True, ontologies imported by imported ontologies are also returned.

Source code in ontopy/ontology.py
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
def get_imported_ontologies(self, recursive=False):
    """Return a list with imported ontologies.

    If `recursive` is `True`, ontologies imported by imported ontologies
    are also returned.
    """

    def rec_imported(onto):
        for ontology in onto.imported_ontologies:
            if ontology not in imported:
                imported.add(ontology)
                rec_imported(ontology)

    if recursive:
        imported = set()
        rec_imported(self)
        return list(imported)

    return self.imported_ontologies

get_relations()

Returns a generator for all relations.

Source code in ontopy/ontology.py
1081
1082
1083
1084
1085
1086
1087
1088
def get_relations(self):
    """Returns a generator for all relations."""
    warnings.warn(
        "Ontology.get_relations() is deprecated. Use "
        "onto.object_properties() instead.",
        DeprecationWarning,
    )
    return self.object_properties()

get_root_classes(imported=False)

Returns a list or root classes.

Source code in ontopy/ontology.py
880
881
882
883
884
885
886
def get_root_classes(self, imported=False):
    """Returns a list or root classes."""
    return [
        cls
        for cls in self.classes(imported=imported)
        if not cls.ancestors().difference(set([cls, owlready2.Thing]))
    ]

get_root_data_properties(imported=False)

Returns a list of root object properties.

Source code in ontopy/ontology.py
893
894
895
896
def get_root_data_properties(self, imported=False):
    """Returns a list of root object properties."""
    props = set(self.data_properties(imported=imported))
    return [p for p in props if not props.intersection(p.is_a)]

get_root_object_properties(imported=False)

Returns a list of root object properties.

Source code in ontopy/ontology.py
888
889
890
891
def get_root_object_properties(self, imported=False):
    """Returns a list of root object properties."""
    props = set(self.object_properties(imported=imported))
    return [p for p in props if not props.intersection(p.is_a)]

get_roots(imported=False)

Returns all class, object_property and data_property roots.

Source code in ontopy/ontology.py
898
899
900
901
902
903
def get_roots(self, imported=False):
    """Returns all class, object_property and data_property roots."""
    roots = self.get_root_classes(imported=imported)
    roots.extend(self.get_root_object_properties(imported=imported))
    roots.extend(self.get_root_data_properties(imported=imported))
    return roots

get_unabbreviated_triples(label=None)

Returns all triples unabbreviated.

If label is given, it will be used to represent blank nodes.

Source code in ontopy/ontology.py
253
254
255
256
257
258
def get_unabbreviated_triples(self, label=None):
    """Returns all triples unabbreviated.

    If `label` is given, it will be used to represent blank nodes.
    """
    return World.get_unabbreviated_triples(self, label)

get_version(as_iri=False)

Returns the version number of the ontology as inferred from the owl:versionIRI tag or, if owl:versionIRI is not found, from owl:versionINFO.

If as_iri is True, the full versionIRI is returned.

Source code in ontopy/ontology.py
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
def get_version(self, as_iri=False) -> str:
    """Returns the version number of the ontology as inferred from the
    owl:versionIRI tag or, if owl:versionIRI is not found, from
    owl:versionINFO.

    If `as_iri` is True, the full versionIRI is returned.
    """
    version_iri_storid = self.world._abbreviate(
        "http://www.w3.org/2002/07/owl#versionIRI"
    )
    tokens = self.get_triples(s=self.storid, p=version_iri_storid)
    if (not tokens) and (as_iri is True):
        raise TypeError(
            "No owl:versionIRI "
            f"in Ontology {self.base_iri!r}. "
            "Search for owl:versionInfo with as_iri=False"
        )
    if tokens:
        _, _, obj = tokens[0]
        version_iri = self.world._unabbreviate(obj)
        if as_iri:
            return version_iri
        return infer_version(self.base_iri, version_iri)

    version_info_storid = self.world._abbreviate(
        "http://www.w3.org/2002/07/owl#versionInfo"
    )
    tokens = self.get_triples(s=self.storid, p=version_info_storid)
    if not tokens:
        raise TypeError(
            "No versionIRI or versionInfo " f"in Ontology {self.base_iri!r}"
        )
    _, _, version_info = tokens[0]
    return version_info.strip('"').strip("'")

get_wu_palmer_measure(cls1, cls2)

Return Wu-Palmer measure for semantic similarity.

Returns Wu-Palmer measure for semantic similarity between two concepts. Wu, Palmer; ACL 94: Proceedings of the 32nd annual meeting on Association for Computational Linguistics, June 1994.

Source code in ontopy/ontology.py
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
def get_wu_palmer_measure(self, cls1, cls2):
    """Return Wu-Palmer measure for semantic similarity.

    Returns Wu-Palmer measure for semantic similarity between
    two concepts.
    Wu, Palmer; ACL 94: Proceedings of the 32nd annual meeting on
    Association for Computational Linguistics, June 1994.
    """
    cca = self.closest_common_ancestor(cls1, cls2)
    ccadepth = self.number_of_generations(cca, self.Thing)
    generations1 = self.number_of_generations(cls1, cca)
    generations2 = self.number_of_generations(cls2, cca)
    return 2 * ccadepth / (generations1 + generations2 + 2 * ccadepth)

individuals(imported=False)

Returns an generator over all individuals.

If imported is True, will imported individuals are also returned.

Source code in ontopy/ontology.py
840
841
842
843
844
845
846
847
def individuals(self, imported=False):
    """Returns an generator over all individuals.

    If `imported` is `True`, will imported individuals are also returned.
    """
    if imported:
        return self.world.individuals()
    return super().individuals()

is_defined(entity)

Returns true if the entity is a defined class.

Source code in ontopy/ontology.py
1220
1221
1222
1223
1224
def is_defined(self, entity):
    """Returns true if the entity is a defined class."""
    if isinstance(entity, str):
        entity = self.get_by_label(entity)
    return hasattr(entity, "equivalent_to") and bool(entity.equivalent_to)

is_individual(entity)

Returns true if entity is an individual.

Source code in ontopy/ontology.py
1212
1213
1214
1215
1216
def is_individual(self, entity):
    """Returns true if entity is an individual."""
    if isinstance(entity, str):
        entity = self.get_by_label(entity)
    return isinstance(entity, owlready2.Thing)

load(only_local=False, filename=None, format=None, reload=None, reload_if_newer=False, url_from_catalog=None, catalog_file='catalog-v001.xml', emmo_based=True, **kwargs)

Load the ontology.

Parameters
bool

Whether to only read local files. This requires that you have appended the path to the ontology to owlready2.onto_path.

str

Path to file to load the ontology from. Defaults to base_iri provided to get_ontology().

str

Format of filename. Default is inferred from filename extension.

bool

Whether to reload the ontology if it is already loaded.

bool

Whether to reload the ontology if the source has changed since last time it was loaded.

bool | None

Whether to use catalog file to resolve the location of base_iri. If None, the catalog file is used if it exists in the same directory as filename.

str

Name of Protègè catalog file in the same folder as the ontology. This option is used together with only_local and defaults to "catalog-v001.xml".

bool

Whether this is an EMMO-based ontology or not, default True.

kwargs Additional keyword arguments are passed on to owlready2.Ontology.load().

Source code in ontopy/ontology.py
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
def load(  # pylint: disable=too-many-arguments,arguments-renamed
    self,
    only_local=False,
    filename=None,
    format=None,  # pylint: disable=redefined-builtin
    reload=None,
    reload_if_newer=False,
    url_from_catalog=None,
    catalog_file="catalog-v001.xml",
    emmo_based=True,
    **kwargs,
):
    """Load the ontology.

    Parameters
    ----------
    only_local : bool
        Whether to only read local files.  This requires that you
        have appended the path to the ontology to owlready2.onto_path.
    filename : str
        Path to file to load the ontology from.  Defaults to `base_iri`
        provided to get_ontology().
    format : str
        Format of `filename`.  Default is inferred from `filename`
        extension.
    reload : bool
        Whether to reload the ontology if it is already loaded.
    reload_if_newer : bool
        Whether to reload the ontology if the source has changed since
        last time it was loaded.
    url_from_catalog : bool | None
        Whether to use catalog file to resolve the location of `base_iri`.
        If None, the catalog file is used if it exists in the same
        directory as `filename`.
    catalog_file : str
        Name of Protègè catalog file in the same folder as the
        ontology.  This option is used together with `only_local` and
        defaults to "catalog-v001.xml".
    emmo_based : bool
        Whether this is an EMMO-based ontology or not, default `True`.
    kwargs
        Additional keyword arguments are passed on to
        owlready2.Ontology.load().
    """
    # TODO: make sure that `only_local` argument is respected...

    if self.loaded:
        return self
    self._load(
        only_local=only_local,
        filename=filename,
        format=format,
        reload=reload,
        reload_if_newer=reload_if_newer,
        url_from_catalog=url_from_catalog,
        catalog_file=catalog_file,
        **kwargs,
    )

    # Enable optimised search by get_by_label()
    if self._special_labels is None and emmo_based:
        for iri in DEFAULT_LABEL_ANNOTATIONS:
            self.add_label_annotation(iri)
        top = self.world["http://www.w3.org/2002/07/owl#topObjectProperty"]
        self._special_labels = {
            "Thing": owlready2.Thing,
            "Nothing": owlready2.Nothing,
            "topObjectProperty": top,
            "owl:Thing": owlready2.Thing,
            "owl:Nothing": owlready2.Nothing,
            "owl:topObjectProperty": top,
        }

    return self

new_entity(name, parent)

Create and return new entity

Makes a new entity in the ontology with given parent(s). Return the new entity.

Throws exception if name consists of more than one word.

Source code in ontopy/ontology.py
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
def new_entity(
    self, name: str, parent: Union[ThingClass, Iterable]
) -> ThingClass:
    """Create and return new entity

    Makes a new entity in the ontology with given parent(s).
    Return the new entity.

    Throws exception if name consists of more than one word.
    """
    if len(name.split(" ")) > 1:
        raise LabelDefinitionError(
            f"Error in label name definition '{name}': "
            f"Label consists of more than one word."
        )
    parents = tuple(parent) if isinstance(parent, Iterable) else (parent,)
    for thing in parents:
        if not isinstance(thing, owlready2.ThingClass):
            raise ThingClassDefinitionError(
                f"Error in parent definition: "
                f"'{thing}' is not an owlready2.ThingClass."
            )

    with self:
        entity = types.new_class(name, parents)
    return entity

number_of_generations(descendant, ancestor)

Return shortest distance from ancestor to descendant

Source code in ontopy/ontology.py
1311
1312
1313
1314
1315
def number_of_generations(self, descendant, ancestor):
    """Return shortest distance from ancestor to descendant"""
    if ancestor not in descendant.ancestors():
        raise ValueError("Descendant is not a descendant of ancestor")
    return self._number_of_generations(descendant, ancestor, 0)

object_properties(imported=False)

Returns an generator over all object properties.

If imported is true, will imported object properties are also returned.

Source code in ontopy/ontology.py
849
850
851
852
853
854
855
856
857
def object_properties(self, imported=False):
    """Returns an generator over all object properties.

    If `imported` is true, will imported object properties are also
    returned.
    """
    if imported:
        return self.world.object_properties()
    return super().object_properties()

remove_label_annotation(iri)

Removes label annotation used by get_by_label().

May be provided either as an IRI or as its owlready2 representation.

Source code in ontopy/ontology.py
367
368
369
370
371
372
373
374
375
def remove_label_annotation(self, iri):
    """Removes label annotation used by get_by_label().

    May be provided either as an IRI or as its owlready2 representation.
    """
    label_annotation = iri if hasattr(iri, "storid") else self.world[iri]
    if not label_annotation:
        raise ValueError(f"IRI not in ontology: {iri}")
    self._label_annotations.remove(label_annotation)

rename_entities(annotations=('prefLabel', 'label', 'altLabel'))

Set name of all entities to the first non-empty annotation in annotations.

Warning, this method changes all IRIs in the ontology. However, it may be useful to make the ontology more readable and to work with it together with a triple store.

Source code in ontopy/ontology.py
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
def rename_entities(
    self,
    annotations=("prefLabel", "label", "altLabel"),
):
    """Set `name` of all entities to the first non-empty annotation in
    `annotations`.

    Warning, this method changes all IRIs in the ontology.  However,
    it may be useful to make the ontology more readable and to work
    with it together with a triple store.
    """
    for entity in self.get_entities():
        for annotation in annotations:
            if hasattr(entity, annotation):
                name = getattr(entity, annotation).first()
                if name:
                    entity.name = name
                    break

save(filename=None, format=None, dir='.', mkdir=False, overwrite=False, recursive=False, squash=False, write_catalog_file=False, append_catalog=False, catalog_file='catalog-v001.xml')

Writes the ontology to file.

Parameters
None | str | Path

Name of file to write to. If None, it defaults to the name of the ontology with format as file extension.

str

Output format. The default is to infer it from filename.

str | Path

If filename is a relative path, it is a relative path to dir.

bool

Whether to create output directory if it does not exists.

bool

If true and filename exists, remove the existing file before saving. The default is to append to an existing ontology.

bool

Whether to save imported ontologies recursively. This is commonly combined with filename=None, dir and mkdir.

bool

If true, rdflib will be used to save the current ontology together with all its sub-ontologies into filename. It make no sense to combine this with recursive.

bool

Whether to also write a catalog file to disk.

bool

Whether to append to an existing catalog file.

str | Path

Name of catalog file. If not an absolute path, it is prepended to dir.

Source code in ontopy/ontology.py
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
def save(
    self,
    filename=None,
    format=None,
    dir=".",
    mkdir=False,
    overwrite=False,
    recursive=False,
    squash=False,
    write_catalog_file=False,
    append_catalog=False,
    catalog_file="catalog-v001.xml",
):
    """Writes the ontology to file.

    Parameters
    ----------
    filename: None | str | Path
        Name of file to write to.  If None, it defaults to the name
        of the ontology with `format` as file extension.
    format: str
        Output format. The default is to infer it from `filename`.
    dir: str | Path
        If `filename` is a relative path, it is a relative path to `dir`.
    mkdir: bool
        Whether to create output directory if it does not exists.
    owerwrite: bool
        If true and `filename` exists, remove the existing file before
        saving.  The default is to append to an existing ontology.
    recursive: bool
        Whether to save imported ontologies recursively.  This is
        commonly combined with `filename=None`, `dir` and `mkdir`.
    squash: bool
        If true, rdflib will be used to save the current ontology
        together with all its sub-ontologies into `filename`.
        It make no sense to combine this with `recursive`.
    write_catalog_file: bool
        Whether to also write a catalog file to disk.
    append_catalog: bool
        Whether to append to an existing catalog file.
    catalog_file: str | Path
        Name of catalog file.  If not an absolute path, it is prepended
        to `dir`.
    """
    # pylint: disable=redefined-builtin,too-many-arguments
    # pylint: disable=too-many-statements,too-many-branches
    # pylint: disable=too-many-locals,arguments-renamed
    if not _validate_installed_version(
        package="rdflib", min_version="6.0.0"
    ) and format == FMAP.get("ttl", ""):
        from rdflib import (  # pylint: disable=import-outside-toplevel
            __version__ as __rdflib_version__,
        )

        warnings.warn(
            IncompatibleVersion(
                "To correctly convert to Turtle format, rdflib must be "
                "version 6.0.0 or greater, however, the detected rdflib "
                "version used by your Python interpreter is "
                f"{__rdflib_version__!r}. For more information see the "
                "'Known issues' section of the README."
            )
        )

    revmap = {value: key for key, value in FMAP.items()}

    if filename is None:
        if format:
            fmt = revmap.get(format, format)
            filename = f"{self.name}.{fmt}"
        else:
            TypeError("`filename` and `format` cannot both be None.")
    filename = os.path.join(dir, filename)
    dir = Path(filename).resolve().parent

    if mkdir:
        outdir = Path(filename).parent.resolve()
        if not outdir.exists():
            outdir.mkdir(parents=True)

    if not format:
        format = guess_format(filename, fmap=FMAP)
    fmt = revmap.get(format, format)

    if overwrite and filename and os.path.exists(filename):
        os.remove(filename)

    EMMO = rdflib.Namespace(  # pylint:disable=invalid-name
        "http://emmo.info/emmo#"
    )

    if recursive:
        if squash:
            raise ValueError(
                "`recursive` and `squash` should not both be true"
            )
        base = self.base_iri.rstrip("#/")
        for onto in self.imported_ontologies:
            obase = onto.base_iri.rstrip("#/")
            newdir = Path(dir) / os.path.relpath(obase, base)
            onto.save(
                filename=None,
                format=format,
                dir=newdir.resolve(),
                mkdir=mkdir,
                overwrite=overwrite,
                recursive=recursive,
                squash=squash,
                write_catalog_file=write_catalog_file,
                append_catalog=append_catalog,
                catalog_file=catalog_file,
            )

    if squash:
        from rdflib import (  # pylint:disable=import-outside-toplevel
            URIRef,
            RDF,
            OWL,
        )

        graph = self.world.as_rdflib_graph()
        graph.namespace_manager.bind("emmo", EMMO)

        # Remove anonymous namespace and imports
        graph.remove((URIRef("http://anonymous"), RDF.type, OWL.Ontology))
        imports = list(graph.triples((None, OWL.imports, None)))
        for triple in imports:
            graph.remove(triple)

        graph.serialize(destination=filename, format=format)
    elif format in OWLREADY2_FORMATS:
        super().save(file=filename, format=fmt)
    else:
        # The try-finally clause is needed for cleanup and because
        # we have to provide delete=False to NamedTemporaryFile
        # since Windows does not allow to reopen an already open
        # file.
        try:
            with tempfile.NamedTemporaryFile(
                suffix=".owl", delete=False
            ) as handle:
                tmpfile = handle.name
            super().save(tmpfile, format="rdfxml")
            graph = rdflib.Graph()
            graph.parse(tmpfile, format="xml")
            graph.serialize(destination=filename, format=format)
        finally:
            os.remove(tmpfile)

    if write_catalog_file:
        mappings = {}
        base = self.base_iri.rstrip("#/")

        def append(onto):
            obase = onto.base_iri.rstrip("#/")
            newdir = Path(dir) / os.path.relpath(obase, base)
            newpath = newdir.resolve() / f"{onto.name}.{fmt}"
            relpath = os.path.relpath(newpath, dir)
            mappings[onto.get_version(as_iri=True)] = str(relpath)
            for imported in onto.imported_ontologies:
                append(imported)

        if recursive:
            append(self)
        write_catalog(
            mappings, output=catalog_file, dir=dir, append=append_catalog
        )

set_version(version=None, version_iri=None)

Assign version to ontology by asigning owl:versionIRI.

If version but not version_iri is provided, the version IRI will be the combination of base_iri and version.

Source code in ontopy/ontology.py
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
def set_version(self, version=None, version_iri=None):
    """Assign version to ontology by asigning owl:versionIRI.

    If `version` but not `version_iri` is provided, the version
    IRI will be the combination of `base_iri` and `version`.
    """
    _version_iri = "http://www.w3.org/2002/07/owl#versionIRI"
    version_iri_storid = self.world._abbreviate(_version_iri)
    if self._has_obj_triple_spo(  # pylint: disable=unexpected-keyword-arg
        # For some reason _has_obj_triples_spo exists in both
        # owlready2.namespace.Namespace (with arguments subject/predicate)
        # and in owlready2.triplelite._GraphManager (with arguments s/p)
        # owlready2.Ontology inherits from Namespace directly
        # and pylint checks that.
        # It actually accesses the one in triplelite.
        # subject=self.storid, predicate=version_iri_storid
        s=self.storid,
        p=version_iri_storid,
    ):
        self._del_obj_triple_spo(s=self.storid, p=version_iri_storid)

    if not version_iri:
        if not version:
            raise TypeError(
                "Either `version` or `version_iri` must be provided"
            )
        head, tail = self.base_iri.rstrip("#/").rsplit("/", 1)
        version_iri = "/".join([head, version, tail])

    self._add_obj_triple_spo(
        s=self.storid,
        p=self.world._abbreviate(_version_iri),
        o=self.world._abbreviate(version_iri),
    )

sync_attributes(name_policy=None, name_prefix='', class_docstring='comment', sync_imported=False)

This method is intended to be called after you have added new classes (typically via Python) to make sure that attributes like label and comments are defined.

If a class, object property, data property or annotation property in the current ontology has no label, the name of the corresponding Python class will be assigned as label.

If a class, object property, data property or annotation property has no comment, it will be assigned the docstring of the corresponding Python class.

name_policy specify wether and how the names in the ontology should be updated. Valid values are: None not changed "uuid" name_prefix followed by a global unique id (UUID). "sequential" name_prefix followed a sequantial number. EMMO conventions imply name_policy=='uuid'.

If sync_imported is true, all imported ontologies are also updated.

The class_docstring argument specifies the annotation that class docstrings are mapped to. Defaults to "comment".

Source code in ontopy/ontology.py
 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
def sync_attributes(  # pylint: disable=too-many-branches
    self,
    name_policy=None,
    name_prefix="",
    class_docstring="comment",
    sync_imported=False,
):
    """This method is intended to be called after you have added new
    classes (typically via Python) to make sure that attributes like
    `label` and `comments` are defined.

    If a class, object property, data property or annotation
    property in the current ontology has no label, the name of
    the corresponding Python class will be assigned as label.

    If a class, object property, data property or annotation
    property has no comment, it will be assigned the docstring of
    the corresponding Python class.

    `name_policy` specify wether and how the names in the ontology
    should be updated.  Valid values are:
      None          not changed
      "uuid"        `name_prefix` followed by a global unique id (UUID).
      "sequential"  `name_prefix` followed a sequantial number.
    EMMO conventions imply ``name_policy=='uuid'``.

    If `sync_imported` is true, all imported ontologies are also
    updated.

    The `class_docstring` argument specifies the annotation that
    class docstrings are mapped to.  Defaults to "comment".
    """
    for cls in itertools.chain(
        self.classes(),
        self.object_properties(),
        self.data_properties(),
        self.annotation_properties(),
    ):
        if not hasattr(cls, "prefLabel"):
            # no prefLabel - create new annotation property..
            with self:

                # pylint: disable=invalid-name,missing-class-docstring
                # pylint: disable=unused-variable
                class prefLabel(owlready2.label):
                    pass

            cls.prefLabel = [locstr(cls.__name__, lang="en")]
        elif not cls.prefLabel:
            cls.prefLabel.append(locstr(cls.__name__, lang="en"))
        if class_docstring and hasattr(cls, "__doc__") and cls.__doc__:
            getattr(cls, class_docstring).append(
                locstr(inspect.cleandoc(cls.__doc__), lang="en")
            )

    for ind in self.individuals():
        if not hasattr(ind, "prefLabel"):
            # no prefLabel - create new annotation property..
            with self:
                # pylint: disable=invalid-name,missing-class-docstring
                # pylint: disable=function-redefined
                class prefLabel(owlready2.label):
                    iri = "http://www.w3.org/2004/02/skos/core#prefLabel"

            ind.prefLabel = [locstr(ind.name, lang="en")]
        elif not ind.prefLabel:
            ind.prefLabel.append(locstr(ind.name, lang="en"))

    chain = itertools.chain(
        self.classes(),
        self.individuals(),
        self.object_properties(),
        self.data_properties(),
        self.annotation_properties(),
    )
    if name_policy == "uuid":
        for obj in chain:
            obj.name = name_prefix + str(
                uuid.uuid5(uuid.NAMESPACE_DNS, obj.name)
            )
    elif name_policy == "sequential":
        for obj in chain:
            counter = 0
            while f"{self.base_iri}{name_prefix}{counter}" in self:
                counter += 1
            obj.name = name_prefix + str(counter)
    elif name_policy is not None:
        raise TypeError(f"invalid name_policy: {name_policy!r}")

    if sync_imported:
        for onto in self.imported_ontologies:
            onto.sync_attributes()

sync_python_names(annotations=('prefLabel', 'label', 'altLabel'))

Update the python_name attribute of all properties.

The python_name attribute will be set to the first non-empty annotation in the sequence of annotations in annotations for the property.

Source code in ontopy/ontology.py
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
def sync_python_names(self, annotations=("prefLabel", "label", "altLabel")):
    """Update the `python_name` attribute of all properties.

    The python_name attribute will be set to the first non-empty
    annotation in the sequence of annotations in `annotations` for
    the property.
    """

    def update(gen):
        for prop in gen:
            for annotation in annotations:
                if hasattr(prop, annotation) and getattr(prop, annotation):
                    prop.python_name = getattr(prop, annotation).first()
                    break

    update(
        self.get_entities(
            classes=False,
            individuals=False,
            object_properties=False,
            data_properties=False,
        )
    )
    update(
        self.get_entities(
            classes=False, individuals=False, annotation_properties=False
        )
    )

sync_reasoner(reasoner='FaCT++', include_imported=False, **kwargs)

Update current ontology by running the given reasoner.

Supported values for reasoner are 'Pellet', 'HermiT' and 'FaCT++'.

If include_imported is true, the reasoner will also reason over imported ontologies. Note that this may be very slow with Pellet and HermiT.

Keyword arguments are passed to the underlying owlready2 function.

Source code in ontopy/ontology.py
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
def sync_reasoner(
    self, reasoner="FaCT++", include_imported=False, **kwargs
):
    """Update current ontology by running the given reasoner.

    Supported values for `reasoner` are 'Pellet', 'HermiT' and 'FaCT++'.

    If `include_imported` is true, the reasoner will also reason
    over imported ontologies.  Note that this may be **very** slow
    with Pellet and HermiT.

    Keyword arguments are passed to the underlying owlready2 function.
    """
    if reasoner == "FaCT++":
        sync = sync_reasoner_factpp
    elif reasoner == "Pellet":
        sync = owlready2.sync_reasoner_pellet
    elif reasoner == "HermiT":
        sync = owlready2.sync_reasoner_hermit
    else:
        raise ValueError(
            f"unknown reasoner {reasoner!r}. Supported reasoners "
            'are "Pellet", "HermiT" and "FaCT++".'
        )

    # For some reason we must visit all entities once before running
    # the reasoner...
    list(self.get_entities())

    with self:
        if include_imported:
            sync(self.world, **kwargs)
        else:
            sync(self, **kwargs)

World

Bases: owlready2.World

A subclass of owlready2.World.

Source code in ontopy/ontology.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class World(owlready2.World):
    """A subclass of owlready2.World."""

    def __init__(self, *args, **kwargs):
        # Caches stored in the world
        self._cached_catalogs = {}  # maps url to (mtime, iris, dirs)
        self._iri_mappings = {}  # all iri mappings loaded so far
        super().__init__(*args, **kwargs)

    def get_ontology(self, base_iri="emmo-inferred"):
        """Returns a new Ontology from `base_iri`.

        The `base_iri` argument may be one of:
          - valid URL (possible excluding final .owl or .ttl)
          - file name (possible excluding final .owl or .ttl)
          - "emmo": load latest stable version of asserted EMMO
          - "emmo-inferred": load latest stable version of inferred EMMO
            (default)
          - "emmo-development": load latest inferred development version
            of EMMO
        """
        base_iri = base_iri.as_uri() if isinstance(base_iri, Path) else base_iri

        if base_iri == "emmo":
            base_iri = (
                "https://raw.githubusercontent.com/emmo-repo/"
                "EMMO/master/emmo.ttl"
            )
        elif base_iri == "emmo-inferred":
            base_iri = (
                "https://emmo-repo.github.io/latest-stable/emmo-inferred.ttl"
            )
        elif base_iri == "emmo-development":
            base_iri = (
                "https://emmo-repo.github.io/development/emmo-inferred.ttl"
            )

        if base_iri in self.ontologies:
            onto = self.ontologies[base_iri]
        elif base_iri + "#" in self.ontologies:
            onto = self.ontologies[base_iri + "#"]
        elif base_iri + "/" in self.ontologies:
            onto = self.ontologies[base_iri + "/"]
        else:
            if os.path.exists(base_iri):
                iri = os.path.abspath(base_iri)
            elif os.path.exists(base_iri + ".ttl"):
                iri = os.path.abspath(base_iri + ".ttl")
            elif os.path.exists(base_iri + ".owl"):
                iri = os.path.abspath(base_iri + ".owl")
            else:
                iri = base_iri

            if iri[-1] not in "/#":
                iri += "#"
            onto = Ontology(self, iri)

        return onto

    def get_unabbreviated_triples(self, label=None):
        """Returns all triples unabbreviated.

        If `label` is given, it will be used to represent blank nodes.
        """

        def _unabbreviate(i):
            if isinstance(i, int):
                # negative storid corresponds to blank nodes
                if i >= 0:
                    return self._unabbreviate(i)
                return BlankNode(self, i) if label is None else label
            return i

        for subject, predicate, obj in self.get_triples():
            yield (
                _unabbreviate(subject),
                _unabbreviate(predicate),
                _unabbreviate(obj),
            )

get_ontology(base_iri='emmo-inferred')

Returns a new Ontology from base_iri.

The base_iri argument may be one of: - valid URL (possible excluding final .owl or .ttl) - file name (possible excluding final .owl or .ttl) - "emmo": load latest stable version of asserted EMMO - "emmo-inferred": load latest stable version of inferred EMMO (default) - "emmo-development": load latest inferred development version of EMMO

Source code in ontopy/ontology.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 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
118
119
120
121
122
123
124
125
126
127
def get_ontology(self, base_iri="emmo-inferred"):
    """Returns a new Ontology from `base_iri`.

    The `base_iri` argument may be one of:
      - valid URL (possible excluding final .owl or .ttl)
      - file name (possible excluding final .owl or .ttl)
      - "emmo": load latest stable version of asserted EMMO
      - "emmo-inferred": load latest stable version of inferred EMMO
        (default)
      - "emmo-development": load latest inferred development version
        of EMMO
    """
    base_iri = base_iri.as_uri() if isinstance(base_iri, Path) else base_iri

    if base_iri == "emmo":
        base_iri = (
            "https://raw.githubusercontent.com/emmo-repo/"
            "EMMO/master/emmo.ttl"
        )
    elif base_iri == "emmo-inferred":
        base_iri = (
            "https://emmo-repo.github.io/latest-stable/emmo-inferred.ttl"
        )
    elif base_iri == "emmo-development":
        base_iri = (
            "https://emmo-repo.github.io/development/emmo-inferred.ttl"
        )

    if base_iri in self.ontologies:
        onto = self.ontologies[base_iri]
    elif base_iri + "#" in self.ontologies:
        onto = self.ontologies[base_iri + "#"]
    elif base_iri + "/" in self.ontologies:
        onto = self.ontologies[base_iri + "/"]
    else:
        if os.path.exists(base_iri):
            iri = os.path.abspath(base_iri)
        elif os.path.exists(base_iri + ".ttl"):
            iri = os.path.abspath(base_iri + ".ttl")
        elif os.path.exists(base_iri + ".owl"):
            iri = os.path.abspath(base_iri + ".owl")
        else:
            iri = base_iri

        if iri[-1] not in "/#":
            iri += "#"
        onto = Ontology(self, iri)

    return onto

get_unabbreviated_triples(label=None)

Returns all triples unabbreviated.

If label is given, it will be used to represent blank nodes.

Source code in ontopy/ontology.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def get_unabbreviated_triples(self, label=None):
    """Returns all triples unabbreviated.

    If `label` is given, it will be used to represent blank nodes.
    """

    def _unabbreviate(i):
        if isinstance(i, int):
            # negative storid corresponds to blank nodes
            if i >= 0:
                return self._unabbreviate(i)
            return BlankNode(self, i) if label is None else label
        return i

    for subject, predicate, obj in self.get_triples():
        yield (
            _unabbreviate(subject),
            _unabbreviate(predicate),
            _unabbreviate(obj),
        )

flatten(items)

Yield items from any nested iterable.

Source code in ontopy/ontology.py
1524
1525
1526
1527
1528
1529
1530
1531
def flatten(items):
    """Yield items from any nested iterable."""
    for item in items:
        if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
            for sub_item in flatten(item):
                yield sub_item
        else:
            yield item

get_ontology(*args, **kwargs)

Returns a new Ontology from base_iri.

This is a convenient function for calling World.get_ontology().

Source code in ontopy/ontology.py
63
64
65
66
67
def get_ontology(*args, **kwargs):
    """Returns a new Ontology from `base_iri`.

    This is a convenient function for calling World.get_ontology()."""
    return World().get_ontology(*args, **kwargs)
Back to top