Giter Site home page Giter Site logo

owlready2's Introduction

Owlready2

documentation download stats

Owlready2 is a module for ontology-oriented programming in Python 3, including an optimized RDF quadstore.

Owlready2 can:

  • Import OWL 2.0 ontologies in NTriples, RDF/XML or OWL/XML format
  • Export OWL 2.0 ontologies to NTriples or RDF/XML
  • Manipulates ontology classes, instances and properties transparently, as if they were normal Python objects
  • Add Python methods to ontology classes
  • Perform automatic classification of classes and instances, using the HermiT or Pellet reasoner (included)
  • Load DBpedia or UMLS (for medical terminology, using the integrated PyMedTermino2 submodule)
  • Tested up to 1 billion of RDF triples! (but can potentially support more)
  • In addition, the quadstore is compatible with the RDFlib Python module, which can be used to perform SPARQL queries
  • Finally, Owlready2 can also be used as an ORM (Object-Relational mapper) -- as a graph/object database, it beats Neo4J, MongoDB, SQLObject and SQLAlchemy in terms of performances

Owlready has been created by Jean-Baptiste Lamy at the LIMICS reseach lab. It is available under the GNU LGPL licence v3. If you use Owlready in scientific works, please cite the following article:

Lamy JB. Owlready: Ontology-oriented programming in Python with automatic classification and high level constructs for biomedical ontologies. Artificial Intelligence In Medicine 2017;80:11-28

In case of troubles, questions or comments, please use this Forum/Mailing list: http://owlready.8326.n8.nabble.com

What can I do with Owlready2?

Load an ontology from a local repository, or from Internet:

>>> from owlready2 import *
>>> onto_path.append("/path/to/your/local/ontology/repository")
>>> onto = get_ontology("http://www.lesfleursdunormal.fr/static/_downloads/pizza_onto.owl")
>>> onto.load()

Create new classes in the ontology, possibly mixing OWL constructs and Python methods:

::
>>> with onto:
...     class NonVegetarianPizza(onto.Pizza):
...       equivalent_to = [
...         onto.Pizza
...       & ( onto.has_topping.some(onto.MeatTopping)
...         | onto.has_topping.some(onto.FishTopping)
...         ) ]
...       def eat(self): print("Beurk! I'm vegetarian!")

Access ontology class, and create new instances / individuals:

>>> onto.Pizza
pizza_onto.Pizza
>>> test_pizza = onto.Pizza("test_pizza_owl_identifier")
>>> test_pizza.has_topping = [ onto.CheeseTopping(),
...                            onto.TomatoTopping(),
...                            onto.MeatTopping  () ]

Export to RDF/XML file:

>>> test_onto.save()

Perform reasoning, and classify instances and classes:

>>> test_pizza.__class__
onto.Pizza

>>> # Execute HermiT and reparent instances and classes
>>> sync_reasoner()

>>> test_pizza.__class__
onto.NonVegetarianPizza
>>> test_pizza.eat()
Beurk! I'm vegetarian !

Access to medical terminologies from UMLS:

>>> from owlready2 import *
>>> from owlready2.pymedtermino2.umls import *
>>> default_world.set_backend(filename = "pym.sqlite3")
>>> import_umls("umls-2018AB-full.zip", terminologies = ["ICD10", "SNOMEDCT_US", "CUI"])
>>> default_world.save()

>>> PYM = get_ontology("http://PYM/").load()
>>> ICD10       = PYM["ICD10"]
>>> SNOMEDCT_US = PYM["SNOMEDCT_US"]

>>> SNOMEDCT_US[186675001]
SNOMEDCT_US["186675001"] # Viral pharyngoconjunctivitis

>>> SNOMEDCT_US[186675001] >> ICD10   # Map to ICD10
Concepts([
  ICD10["B30.9"] # Viral conjunctivitis, unspecified
])

For more documentation, look at the doc/ directories in the source.

Changelog

version 1 - 0.2

  • Fix sync_reasonner and Hermit call under windows (thanks Clare Grasso)

version 1 - 0.3

  • Add warnings
  • Accepts ontologies files that do not ends with '.owl'
  • Fix a bug when loading ontologies including concept without a '#' in their IRI

version 2 - 0.1

  • Full rewrite, including an optimized quadstore

version 2 - 0.2

  • Implement RDFXML parser and generator in Python (no longer use rapper or rdflib)
  • Property chain support
  • Add ntriples_diff.py utility
  • Bugfixes: - Fix breaklines in literal when exporting to NTriples

version 2 - 0.3

  • Add destroy_entity() global function
  • Greatly improve performance for individual creation
  • When searching, allow to use "*" as a jocker for any object
  • Bugfixes: - Fix nested intersections and unions - Fix boolean - Fix bug when removing parent properties - Fix parsing of rdf:ID - Fix multiple loading of the same ontology whose IRI is modified by OWL file, using an ontology alias table - Fix ClassConstruct.subclasses() - Check for properties with multiple incompatible classes (e.g. ObjectProperty and Annotation Property)

version 2 - 0.4

  • Add methods for querying the properties defined for a given individuals, the inverse properties and the relation instances (.get_properties(), .get_inverse_properties() and .get_relations())
  • Add .indirect() method to obtain indirect relations (considering subproperties, transivitity, symmetry and reflexibity)
  • search() now takes into account inheritance and inverse properties
  • search() now accepts 'None' for searching for entities without a given relation
  • Optimize ontology loading by recreating SQL index from scratch
  • Optimize SQL query for transitive quadstore queries, using RECURSIVE Sqlite3 statements
  • Optimize SQL query for obtaining the number of RDF triples (ie len(default_world.graph))
  • Add Artificial Intelligence In Medicine scientific article in doc and Readme
  • Bugfixes: - Fix properties loading when reusing an ontology from a disk-stored quadstore - Fix _inherited_property_value_restrictions() when complement (Not) is involved - Fix restrictions with cardinality - Fix doc on AllDisjoint / AllDifferent

version 2 - 0.5

  • Add individual/instance editor (require EditObj3, still largely untested)
  • Add support for hasSelf restriction
  • Optimize XML parsers
  • Check for cyclic subclass of/subproperty of, and show warning
  • PyPy 3 support (devel version of PyPy 3)
  • Bugfixes: - Fix search() for '*' value on properties with inverse - Fix individual.annotation = "..." and property.annotation = "..." - Fix PlainLiteral annotation with no language specified - Fix doc for Creating classes dynamically - Fix loading ontologies with python_name annotations - Fix _inherited_property_value_restrictions when multiple is-a / equivalent-to are present - Align Python floats with xsd:double rather than xsd:decimal - Rename module 'property' as 'prop', to avoid name clash with Python's 'property()' type

version 2 - 0.6

  • Add set_datatype_iri() global function for associating a Python datatype to an IRI
  • Add nquads ontology format (useful for debugging)
  • Add support for dir() on individuals
  • Add support for ontology using https: protocol (thanks Samourkasidis Argyrios)
  • Add observe module (for registering callback when the ontology is modified)
  • Improve docs
  • Bugfixes: - Align Python floats with xsd:decimal rather than xsd:double, finally, because decimal accepts int too - Fix Class.instances() so as it returns instances of subclasses (as indicated in the doc) - Fix direct assignation to Ontology.imported_ontologies - Fix a bug in reasoning, when adding deduced facts between one loaded and one non-loaded entity

version 2 - 0.7

  • Bugfixes: - Restore HermiT compiled with older Java compilator (higher compatibility)

version 2 - 0.8

  • Bugfixes: - REALLY restore HermiT compiled with older Java compilator (higher compatibility) - Fix search(prop = "value") when value is a string and the ontology uses localized string

version 2 - 0.9

  • PostgresQL backend (in addition to SQLite3)
  • Add 'exclusive = False' option for SQLite3 backend (slower, but allows multiple uses)
  • Use unique index in sqlite3 quadstore on resources table
  • Optimize sqlite3 quadstore by caching IRI dict (5% faster)
  • Add == support for class construct
  • Add get_namespace() support on World
  • Add 'existential restrictions as class properties' feature
  • Bugfixes: - Fix imported ontologies - Fix saving ontologies in onto_path - Fix clear() on CallbackList - Fix bug in Class IRI in ontologies whose base IRI ends with a / - Fix imported ontologies in ontologies whose base IRI ends with a /

version 2 - 0.10

  • Add Ontology.metadata for adding/querying ontology metadata
  • Allows multiple individual creations with the same name/IRI, now returning the same individuals
  • Add OwlReadyInconsistentOntologyError and Word.inconsistent_classes()
  • Implement RDF/XML and OWL/XML parsing in Cython (25% speed boost for parsing)
  • Small optimization
  • Extend individual.prop.indirect() to include relations asserted at the class level
  • Add .query_owlready() method to RDF graph
  • Bugfixes: - Fix reasoning when obtaining classes equivalent to nothing - Fix World creation with backend parameters - Fix error when adding property at the class definition level - Fix loading of ontology files with no extension from onto_path - Fix properties defined with type 'RDF Property' and subproperty of 'OWL Data/Object/Annotation Property' - Support old SQLite3 versions that do not accept WITHOUT ROWID - Fix reference to undeclared entities (they were replaced by None, now by their IRI) - Fix loading and saving ontologies whose base IRI ends with / - Fix RDF query using string

version 2 - 0.11

  • Optimized Full-Text Search
  • Support Pellet reasoner in addition to HermiT
  • Support loading of huge OWL files (incremental load)
  • Use Class.property.indirect() for indirect Class property (instead of Class.property)
  • Add reload and reload_if_newer parameters to Ontology.load()
  • search() is now much faster on properties that have inverse
  • Add shortcut for SOME ConstrainedDatatype: e.g. age >= 65
  • Bugfixes: - Fix creation of an individual that already exists in the quadstore - Fix missing import of EntityClass in class_construct.py - Fix World.save() with RDF/XML format - Fix Thing.subclasses() and Thing.descendants() - Fix ontology's update time for ontologies created de novo in Python with Owlready - Fix reasoning when asserting new parents with equivalent classes

version 2 - 0.12

  • New quadstore
  • Numerical search (NumS, e.g. all patients with age > 65)
  • Nested searches
  • Synchronization for multithreading support
  • Add Class.inverse_restrictions() and Class.direct_instances()
  • Drop PostgresQL support (little interest: more complex and slower than Sqlite3)
  • Bugfixes: - Fix call to _get_by_storid2 - Fix rdfs_subclassof in doc - Fix FTS triggers - Fix boolean in RDFlib / SPARQL - Fix bug when destroying an AnnotationProperty

version 2 - 0.13

  • Bugfixes: - Fix performance regression due to suboptimal index in the quadstore - Fix messing up with IRI ending with a / - Fix error in World cloning - Fix the addition of Thing in class's parent when redefining a class with Thing as the only parent - Fix inverse_resctriction() - Add error message when creating an existent quadstore

version 2 - 0.14

  • UMLS support (owlready2.pymedtermino2 package)
  • Can infer object property values when reasoning (thanks W Zimmer)
  • New implementation of property values; use INDIRECT_prop to get indirect values
  • Support several class property types : some, only, some + only, and direct relation
  • Automatically create defined classes via class properties
  • Support anonymous individuals, e.g. Thing(0)
  • Optimize search() when only the number of returned elements is used
  • Optimize FTS search() when using also non-FTS statements
  • Can restrict reasoning to a list of ontologies
  • Union searches (i.e. default_world.search(...) | default_world.search(...))
  • Bugfixes: - Fix functional class properties with inheritance - Fix dupplicated instance list restrictions when calling close_world(ontology) - Fix use of '*' in search - Fix synchronization, using contextvars for global variables

version 2 - 0.15

  • Can infer data property values when reasoning with Pellet
  • Optimize searches with 'type =', 'subclass_of =', or 'is_a =' parameters
  • Add Property.range_iri
  • Add _case_sensitive parameter to search()
  • Add inverse property support in RDFlib support
  • Show Java error message when reasoners crash
  • Bugfixes: - Consider inverse property in get_properties() - Fix parsing bug in reasoning with HermiT and infer_property_values = True - Namespace prefix support in RDFlib binding - Fix dupplicates values when a relation involving a property with inverse is asserted in both directions - Better workaround in case of metaclass conflict - Fix 'sqlite3.OperationalError: too many SQL variables' in searches with 'type =', 'subclass_of =', or 'is_a =' parameters

version 2 - 0.16

  • Optimize nested searches
  • search(sublclass_of = xxx) now returns xxx itself in the results
  • Support "with long_ontology_name as onto" syntax
  • In UMLS import, add optional parameters for preventing extraction of attributes, relations, etc
  • Support SPARQL INSERT queries
  • Optimize Pymedtermino mapping
  • Doc for PyMedTermino2
  • Bugfixes: - Fix 'Cannot release un-acquired lock' error when reasoning on inconsistent ontologies inside a 'with' statement - Fix bug when loading a property that refers to another property from a quadstore stored on disk - Fix RDF triple suppression with RDFlib when object is a datatype

version 2 - 0.17

  • SWRL rule support
  • Allows importing UMLS suppressed terms
  • Uncache entities when relaoding an ontology
  • Bugfixes: - Fix PyMedTermino2 installation - Fix data property value inferrence with debug = 1 - Fix sort() in LazyList (thanks fiveop!) - Fix World.get() and add World.get_if_loaded() - Add appropriate error message when importing UMLS with Python 3.6 - Fix individuals belonging to multiple, equivalent, classes after reasoning

version 2 - 0.18

  • Add UNIQUE constraints for preventing dupplicated RDF triples in the quadstore
  • Add Individual.INDIRECT_is_a / Individual.INDIRECT_is_instance_of
  • Add isinstance_python() (faster than isinstance(), but do not consider equivalent_to relations)
  • Bugfixes: - Force UTF-8 encoding when importing UMLS - Be more tolerant when loading OWL file

version 2 - 0.19

  • Consider symmetric properties as their own inverse properties
  • Update Python objects after basic SPARQL update/delete queries (works on user-defined properties, hierarchical properties (type/subclassof) and equivalence properties)
  • Add individual.INVERSE_property
  • Add Class.INDIRECT_is_a
  • INDIRECT_is_a / INDIRECT_is_instance_of now include class contructs. ancestors() has a 'include_constructs' parameter, which defaults to False.
  • Add more aliases for XMLSchema datatypes
  • Add is_a property to class constructs
  • Add bottomObjectProperty and bottomDataProperty
  • Support ReflexiveProperties in individual.INDIRECT_property
  • Optimize Thing.subclasses()
  • Optimize search() with multiple criteria, including those done by PyMedTermino
  • Add support for destroy_entity(SWRL_rule)
  • Add support for UMLS "metathesaurus" format in addition to "full" format
  • Bugfixes: - After reasoning, keep all equivalent classes as parents of individuals (as they may have methods) - Fix IndividualPropertyAtom when creating SWRL rule - Fix SWRL parser - Fix RDF serialization for nested RDF lists - Fix removing inverse property (i.e. Prop.inverse = None) - Fix datetime parsing for date with time zone or milliseconds

version 2 - 0.20

  • Add support for undoable destroy_entity()
  • Small database optimizations
  • No longer treat properties associated with exactly-1 or max-1 restriction as functional properties, returning single values instead of a list (you can restore the previous behaviour as follows: import owlready2.prop; owlready2.prop.RESTRICTIONS_AS_FUNCTIONAL_PROPERTIES = True)
  • Bugfixes: - Fix performance bug on UMLS mapping in PyMedTermino

version 2 - 0.21

  • Use Pellet 2.3.1 (same version as Protégé) instead of 2.4 (which has a bug in SWRL for many builtin predicates including equals and matches)
  • Much faster mangement of annotations on relations
  • Bugfixes: - Fix bug on blank node in RDFlib/SPARQL support - Fix bug on blank node deletion in RDFlib/SPARQL support - Fix data loss in Restriction modification - Fix 'no query solution' error in search() - Fix literal support in RDF lists, causing "TypeError: '<' not supported between instances of 'NoneType' and 'int'" when saving ontologies - Fix DifferentFrom SWRL builtin - Fix string parsing in SWRL rules - Fix string and boolean literal representation (str/repr) in SWRL rules - Fix the inverse of subproperties having a symmetric superproperty

version 2 - 0.22

  • Add support for disjoint unions (Class.disjoint_unions)
  • Add deepcopy support on class constructs, and automatically deep-copy constructs when needed (i.e. no more OwlReadySharedBlankNodeError)
  • Support the creation of blank nodes with RDFlib

version 2 - 0.23

  • Add get_parents_of(), get_instances_of(), get_children_of() methods to ontology, for querying the hierarchical relations defined in a given ontology
  • Use Thing as default value for restrictions with number, instead of None
  • Add 'filter' parameter to save(), for filtering the entities saved (contributed by Javier de la Rosa)
  • Bugfixes: - Fix value restriction with the false value - Fix blank node loading from different ontologies - Fix constructs reused by several classes - Fix 'Class.is_a = []' was not turning the list into an Owlready list - Fix destroy_entity() - was not destroying the IRI of the entity - Improve setup.py: ignore Cython if Cython installation fails

version 2 - 0.24

  • Support intersection of searches (e.g. World.search(...) & World.search(...))
  • Add owlready2.reasoning.JAVA_MEMORY
  • Move development repository to Git
  • Bugfixes: - Fix parsing of NTriples files that do not end with a new line - Fix KeyError with Prop.python_name when several properties share the same name - Fix get_ontology() calls in Python module imported by ontologies in a World that is not default_world - Fix use of PyMedTermino2 in a World that is not default_world - Fix World.as_rdflib_graph().get_context(onto) for ontology added after the creation of the RDFLIB graph - Fix destroying SWRL rules - Fix disjoint with non-atomic classes

version 2 - 0.25

  • Allow the declaration of custom datatypes with declare_datatype()
  • Support the annotation of annotations (e.g. a comment on a comment)
  • search() now support the "subproperty_of" argument
  • search() now support the "bm25" argument (for full-text searches)
  • Bugfixes: - Fix Concept.descendant_concepts() in PymedTermino2 - Update already loaded properties when new ontologies are loaded - Now accept %xx quoted characters in file:// URL - Improve error message on punned entities - Property.get_relations() now considers inverse properties - Fix "AttributeError: 'mappingproxy' object has no attribute 'pop'" error - Fix Thing.instances()

version 2 - 0.26

  • Module owlready2.dl_render allows rendering entities to Description Logics (contributed by Simon Bin)
  • Bugfixes: - Adjustment in the comparison of strings from SameAs and DiferrentFrom, allowing equal comparison regardless of the case-sensitive (contributed by Thiago Feijó) - Fix transitive equivalent_to relations between classes and OWL constructs - Fix AnnotationProperty[entity] where entity is a predefined OWL entity (e.g. comment or Thing) - Fix entity.AnnotationProperty where entity is a predefined OWL entity (e.g. comment or Thing)

Links

Owlready2 on BitBucket (Git development repository): https://bitbucket.org/jibalamy/owlready2

Owlready2 on PyPI (Python Package Index, stable release): https://pypi.python.org/pypi/Owlready2

Documentation: http://owlready2.readthedocs.io/

Forum/Mailing list: http://owlready.8326.n8.nabble.com

Contact "Jiba" Jean-Baptiste Lamy:

<jean-baptiste.lamy *@* univ-paris13 *.* fr>
LIMICS
University Paris 13, Sorbonne Paris Cite
Bureau 149
74 rue Marcel Cachin
93017 BOBIGNY
FRANCE

owlready2's People

Contributors

alexhenrie avatar argysamo avatar jibalamy avatar pwin avatar versae avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

owlready2's Issues

AttributeError: 'str' object has no attribute 'storid'

This code:

import os
from owlready2 import onto_path
from owlready2 import get_ontology
onto_path.append(os.getcwd())
onto = get_ontology('http://purl.obolibrary.org/obo/bto.owl')
print(onto.search(subclass_of = 'obo.BTO_0000042'))

Gives this error:
AttributeError: 'str' object has no attribute 'storid'

It seems like a bug to me.

inherit ontology and python class

Hi, i'm trying to let a ontology class inherit from a standard python class and also the Thing class. I want this to work, because the python class stores some function i use in a lot of other classes and i dont want to copy them all the time. If i transform my python class into an ontology class, almost every class is connected with them (which doesnt make sems imo).

I'm trying something like this:

class MvdXml(Thing, IdentityObject):

    namespace = onto

    def __init__(self, file: str = None, doc: str = None, validation=None) -> etree._Element:
        super().__init__()

where Thing is the ontology class and IdentityObject is the python class.

My errormessage is

line 162, in _add_is_a_triple
    Class.namespace.ontology._add_obj_triple_spo(Class.storid, Class._rdfs_is_a, base.storid)
AttributeError: type object 'IdentityObject' has no attribute 'storid'

so i guess owlready2 wants the pythonclass to also be an ontologyclass.
Is there a workaround?

Crashing trying to get INDIRECT_get_classes_properties() of entities with Inverse relations

Error:

    if   r.property._class_property_some and ((r.type == VALUE) or (r.type == SOME) or ((r.type == EXACTLY) and r.cardinality >= 1) or ((r.type == MIN) and r.cardinality >= 1)):
AttributeError: 'Inverse' object has no attribute '_class_property_some'

The following code doesn't treat the case of Inverse property, which has no _class_property_some nor _class_property_only property.

def INDIRECT_get_class_properties(Class):
    l = set()
    for r in _inherited_properties_value_restrictions(Class, None, set()):
      if   r.property._class_property_some and ((r.type == VALUE) or (r.type == SOME) or ((r.type == EXACTLY) and r.cardinality >= 1) or ((r.type == MIN) and r.cardinality >= 1)):
        l.add(r.property)
      elif r.property._class_property_only and  (r.type == ONLY):
        l.add(r.property)
        
    for storid in Class.namespace.world._get_triples_s_p(Class.storid):
      Prop = Class.namespace.world._get_by_storid(storid)
      if not Prop is None: # None is is-a,...
        l.add(Prop)
    return l

Output of Inverse attributes (_class_property_only and _class_property_some are NOT here):

['__and__', '__class__', '__deepcopy__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__invert__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_create_triples', '_destroy_triples', '_set_ontology', '_set_ontology_copy_if_needed', 'ancestors', 'destroy', 'exactly', 'is_a', 'max', 'min', 'only', 'ontology', 'property', 'some', 'storid', 'subclasses', 'value']

Output of other property attributes (_class_property_only and _class_property_some ARE here):

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_class_property_only', '_class_property_relation', '_class_property_some', '_class_property_type', '_domain', '_equivalent_to', '_inverse_property', '_inverse_storid', '_name', '_property_chain', '_python_name', '_range', 'get_relations', 'is_a', 'is_functional_for', 'namespace', 'storid']

Problem installing Owlready2

Hi everyone,
I am having a problem installing Owlready2. I have tried to use "pip3 install owlready2" as well as downloading the source code and using "python3 setup.py build" but either way I ended up with the same error as shown in the following output:

$ python3 setup.py build
running build
running build_py
creating build
creating build/lib
creating build/lib/owlready2
copying ./annotation.py -> build/lib/owlready2
copying ./disjoint.py -> build/lib/owlready2
copying ./reasoning.py -> build/lib/owlready2
copying ./driver.py -> build/lib/owlready2
copying ./observe.py -> build/lib/owlready2
copying ./close.py -> build/lib/owlready2
copying ./entity.py -> build/lib/owlready2
copying ./rply.py -> build/lib/owlready2
copying ./owlxml_2_ntriples.py -> build/lib/owlready2
copying ./rule.py -> build/lib/owlready2
copying ./rdfxml_2_ntriples.py -> build/lib/owlready2
copying ./triplelite.py -> build/lib/owlready2
copying ./individual.py -> build/lib/owlready2
copying ./instance_editor.py -> build/lib/owlready2
copying ./base.py -> build/lib/owlready2
copying ./init.py -> build/lib/owlready2
copying ./instance_editor_qt.py -> build/lib/owlready2
copying ./prop.py -> build/lib/owlready2
copying ./ntriples_diff.py -> build/lib/owlready2
copying ./class_construct.py -> build/lib/owlready2
copying ./editor.py -> build/lib/owlready2
copying ./util.py -> build/lib/owlready2
copying ./rdflib_store.py -> build/lib/owlready2
copying ./namespace.py -> build/lib/owlready2
creating build/lib/owlready2/pymedtermino2
copying ./pymedtermino2/model.py -> build/lib/owlready2/pymedtermino2
copying ./pymedtermino2/init.py -> build/lib/owlready2/pymedtermino2
copying ./pymedtermino2/icd10_french.py -> build/lib/owlready2/pymedtermino2
copying ./pymedtermino2/umls.py -> build/lib/owlready2/pymedtermino2
copying ./owlready_ontology.owl -> build/lib/owlready2
creating build/lib/owlready2/hermit
copying ./hermit/HermiT.jar -> build/lib/owlready2/hermit
copying ./hermit/readme.txt -> build/lib/owlready2/hermit
creating build/lib/owlready2/hermit/org
creating build/lib/owlready2/hermit/org/semanticweb
creating build/lib/owlready2/hermit/org/semanticweb/HermiT
copying ./hermit/org/semanticweb/HermiT/Reasoner$ReasonerFactory.class -> build/lib/owlready2/hermit/org/semanticweb/HermiT
copying ./hermit/org/semanticweb/HermiT/Reasoner$2.class -> build/lib/owlready2/hermit/org/semanticweb/HermiT
copying ./hermit/org/semanticweb/HermiT/Reasoner$11.class -> build/lib/owlready2/hermit/org/semanticweb/HermiT
error: can't copy './hermit/org/semanticweb/HermiT/hierarchy': doesn't exist or not a regular file

How can I solve this problem?

Thanks in advance for the help

Edit:
I am using Ubuntu 16.04 with Python 3.7.9

"AttributeError: 'SubGraph' object has no attribute 'create_parse_func'" when installing PyMedTermino2

When following the installation guide for PyMedTermino2 (https://owlready2.readthedocs.io/en/latest/pymedtermino2.html), Python gives me the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[7], line 1
----> 1 import_umls("umls-2022AB-metathesaurus-full.zip", terminologies=["ICD10", "SNOMEDCT_US"])

File /opt/conda/lib/python3.10/site-packages/owlready2/pymedtermino2/umls.py:647, in import_umls(umls_zip_filename, terminologies, langs, fts_index, extract_groups, extract_attributes, extract_relations, extract_definitions, remove_suppressed)
    643 default_world.save()
    645 #default_world.graph.set_indexed(False)
--> 647 importer = _Importer(PYM, terminologies, langs, extract_groups, extract_attributes, extract_relations, extract_definitions, remove_suppressed)
    649 parsers = [
    650   ("MRRANK",  parse_mrrank),
    651   ("MRCONSO", parse_mrconso),
    652 ]
    653 if extract_definitions: parsers.append(("MRDEF", parse_mrdef))

File /opt/conda/lib/python3.10/site-packages/owlready2/pymedtermino2/umls.py:531, in _Importer.__init__(self, PYM, terminologies, langs, extract_groups, extract_attributes, extract_relations, extract_definitions, remove_suppressed)
    528 self.indirect_props = Counter()
    529 self.direct_props   = Counter()
--> 531 self.objs, self.datas, self.on_prepare_obj, self.on_prepare_data, self.insert_objs, self.insert_datas, self.new_blank_node, self._abbreviate, self.on_finish = PYM.graph.create_parse_func(delete_existing_triples = False)
    533 if self.extract_cui:
    534   self.CUI = self._abbreviate("http://pym/SRC/CUI")

AttributeError: 'SubGraph' object has no attribute 'create_parse_func'

I am using owlready2-0.41, Python 3.10.8 and the umls-2022AB-metathesaurus-full.zip UMLS data.

Issue using .label with rdfs:label, but functions with rdf:label

Hello!

This issue concerns version 0.26 of owlready2, so please feel free to ignore if this is fixed in more recent systems, I just wanted to note (I'm unfortunately currently restricted to using 0.26 and I'll have to build a work-around, but just wasn't finding much online and wanted to create a record for others).

Essentially, I have a singular entity in which I'm trying to call for the label using "entity.label" (and several of its variants). None of these appeared to be returning any "rdfs:label" attributes of any entities, except for those which had been mislabeled as "rdf:label" (without the "s"). Because of this, it appeared that most entities had no label, when this was not the case.

For a second, I thought I had made a mistake and that "rdf:label" was the canonical form. However, this is not true, and "rdfs:label" is indeed correct (re: RDF Schema 1.1 documentation).

I believe the correct way to fix this issue in 0.26 is to do some form of custom rendering, but I haven't quite worked out the particulars. If I do find a solution, I'll come back and post it here.

Thank you so much for your time!

Access domain and range of an object property inferred by reasoner from an inverse property

Hello, can you please help me with the following situation:
I create an object property A (domainA, rangeA) and an inverse property B in Protege. Run a reasoner and get the domain and range of property B to be (rangeA, domainA).
Then I would like to access the domain and range of property B in owlready2. But propertyB.domain returns an empty list.
Running a reasoner in owlready2 using
with onto:
sync_reasoner(infer_property_values = True)
does not help neither :(
Is it possible at all to infer domain and range of an inverse property in owlready2?
Thanks a lot for your answer!

Test in _is_valid_language_code(s) is not complete

Valid language tags lik3 "en-GB", "de-AT" are not recognized.

The test for valid language tags is buggy. IETF BCP 47 says that language tags consist of a country component (the first two chars) and a region component (the fourth and fifth chars) separated by a hyphen ('-'), not underscore ('_').

https://www.w3.org/TR/ltli/ says that "Specifications for the Web that require language identification MUST refer to [BCP47] ". Since ontologies and rdf are specifications for the web, the function needs to be corrected.

I think this bug is caused by the pythonian way you like to access ontologies. I.e. concept.label.en Clearly, concept.label.en-GB wouldn't work, since - is not a valid char in python names. On the other hand ontologies and rdf may contain label following with the BCP47 spec. So the test needs to be augmented for handling both cases.

How to add java exe path to google colab

So I was trying to install owlready in google colabs and it worked totally fine. But when I went on to run the reasoner I had no idea how to include the JVM and java.exe in google colabs.
Would appreciate your suggestions

Parsing error in Turtle/N3 ontology

The ontology file here https://github.com/rpgoldman/container-ontology/blob/80a1a88d056bcdeac0eda77698348ff9f41acb82/owl/strateos-catalog-individuals.ttl causes a parsing error in Owlready 2. When I look at the source line in question, it's near the bottom:

#################################################################
#    General axioms
#################################################################

[ rdf:type owl:AllDisjointClasses ;
  owl:members ( cont:CatalogEntry
                cont:CoatingMaterial
                cont:Color
                cont:LabEquipment
                cont:VendorFirm
                cont:WellShape
              )
] .

The error message and backtrace is as follows:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

~/.virtualenvs/container-ontology/lib/python3.9/site-packages/owlready2/driver.py in parse(self, f, format, delete_existing_triples, default_base)
    153               if not line.endswith("\n"): line = "%s\n" % line
--> 154               s,p,o = splitter.split(line[:-3], 2)
    155 

ValueError: not enough values to unpack (expected 3, got 1)


The above exception was the direct cause of the following exception:

OwlReadyOntologyParsingError              Traceback (most recent call last)

/var/folders/5s/cx04gv9j1mq4gvcv2lw70s400000gn/T/ipykernel_79391/2588599199.py in <module>
----> 1 container_onto: owl.Ontology = owl.get_ontology("https://www.dropbox.com/s/s1e2dzw64m01f9n/container-ontology.ttl").load()

~/.virtualenvs/container-ontology/lib/python3.9/site-packages/owlready2/namespace.py in load(self, only_local, fileobj, reload, reload_if_newer, url, **args)
    909         if _LOG_LEVEL: print("* Owlready2 *     ...loading ontology %s from %s..." % (self.name, f), file = sys.stderr)
    910         fileobj = open(f, "rb")
--> 911         try:     new_base_iri = self.graph.parse(fileobj, default_base = self.base_iri, **args)
    912         finally: fileobj.close()
    913       else:

~/.virtualenvs/container-ontology/lib/python3.9/site-packages/owlready2/driver.py in parse(self, f, format, delete_existing_triples, default_base)
    186           self._add_obj_triple_raw_spo(self.onto.storid, rdf_type, owl_ontology)
    187         if current_line:
--> 188           raise OwlReadyOntologyParsingError("NTriples parsing error (or unrecognized file format) in %s, line %s." % (getattr(f, "name", getattr(f, "url", "???")), current_line)) from e
    189         else:
    190           raise OwlReadyOntologyParsingError("NTriples parsing error (or unrecognized file format) in %s." % getattr(f, "name", getattr(f, "url", "???"))) from e

OwlReadyOntologyParsingError: NTriples parsing error (or unrecognized file format) in ../owl/container-ontology.ttl, line 1209.

It looks like it is trying to break the line up into three components and is not finding three, perhaps because there is a top level block that (IIUC) corresponds to a blank node?

I had a cursory look at driver.py and I don't see anything in there that checks for the possibility of a line starting with a [, so maybe that is the problem?

Both Protege and RDFLib read this file successfully.

Problem in loading the ontology

Hi,

I often encounter the problem when loading the ontology either from website or local disk when using the owlready2. They said something happening/parsing error in some lines of my ontology, but when i load the ontology with protege and rdflib, they work perfectly.

I dont know what is happening with the load method. Maybe you guys could give me a hint?

Thanks.

Feature: Import turtle flies

Many ontologies are now appearing in the much more readable turtle format.

Owlready2 could support reading turtle files directly, e.g. through rdflib.

(maybe it is a good idea to let all the rdf I/O be done by rdflib ?)

`.min` does not return expected values for cardinality >1

I'm trying to use the min method to count the number of properties (of a particular type) on an object, but I find that counting fails silently for all cardinalities >1. ("silently" = gives unexpected results with no python or java error).

Example:

import owlready2 as owl

for n in [1, 2, 3]:
    onto = owl.get_ontology(f"file://mwe{n}.owl")

    with onto:
        class MyThing(owl.Thing): pass
        class MyProperty(owl.Thing): pass

        class has_for_property(MyThing >> MyProperty):
            class_property_type = "some"
            python_name = "properties"

        class HasAtLeastNProperties(MyThing):
            defined_class = True
            equivalent_to = [MyThing & has_for_property.min(n, MyProperty)]


    has_none = MyThing("none", properties=[])
    has_one = MyThing("one", properties=[MyProperty()])
    has_two = MyThing("two", properties=[MyProperty(), MyProperty()])
    has_three = MyThing("three", properties=[MyProperty(), MyProperty(), MyProperty()])

    owl.close_world(onto.MyThing)
    owl.sync_reasoner_pellet(
        infer_property_values=True, infer_data_property_values=True, debug=0
    )

    print(f"THING, HAS AT LEAST {n} PROPERTIES")
    for thing in [has_none, has_one, has_two, has_three]:
        print('\t', thing.name, HasAtLeastNProperties in thing.INDIRECT_is_a)

Actual output:

THING, HAS AT LEAST 1 PROPERTIES
	 none False
	 one True
	 two True
	 three True
THING, HAS AT LEAST 2 PROPERTIES
	 none False
	 one False
	 two False
	 three False
THING, HAS AT LEAST 3 PROPERTIES
	 none False
	 one False
	 two False
	 three False

Expected output:

THING, HAS AT LEAST 1 PROPERTIES
	 none False
	 one True
	 two True
	 three True
THING, HAS AT LEAST 2 PROPERTIES
	 none False
	 one False
	 two True
	 three True
THING, HAS AT LEAST 3 PROPERTIES
	 none False
	 one False
	 two False
	 three True

Conda installation

I do not know if this is the correct place for this question. If not, forgive me.

I am trying to install owlread2 on OS X Ventura via conda following the "instructions" here:
https://anaconda.org/conda-forge/owlready2

conda install -c conda-forge owlready2
conda install -c "conda-forge/label/cf202003" owlready2

I have updated conda, but the two commands above does not find any packages:

PackagesNotFoundError: The following packages are not available from current channels:

  - owlready2

Yesterday I was able to install owlready2 on Windows 11 with the first command.

Is there any way to install owlready2 via conda on apple machines?

[BUG] Recursion Error on Cycle in Ontology

I have a really simple piece of code but it already runs into an error. My piece of code
should just iterate over the class names in an ontology and print them out. This works for the first 20 or
so, but then this error occurs:

Fatal Python error: Cannot recover from stack overflow. 

Current thread 0x0000000106d2ae00 (most recent call first): 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/util.py", line 249 in __enter__ 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 543 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 540 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 538 in _get_by_storid 
  File "/Users/PATH/.env/lib/python3.7/site-packages/owlready2/namespace.py", line 558 in _load_by_storid 
  ... 
[1]    51983 abort      python owl_to_nodenames.py 

My simple code is:

from owlready2 import get_ontology 
onto = get_ontology("Ontologie.owl").load() 
for this in onto.classes(): 
    print(this) 

Can you point me to the error? I originally tried it on a MacBook, but now I also tested it on a computer running Arch, same error.

Creating SWRL rule using imported ontology

Please see this issue,

protegeproject/swrlapi#25

I am facing a similar issue where i have to use an object_property (let's assume hasQuality) of an imported ontology, but when I try to execute rule, People(?p),hasQuality(?p,?q)->Patient(?p) I get the error ValueError: Cannot find entity 'hasQuality'!. Note that People and Patient are in the main owl file, which imports another owl file which has the property hasQuality.

Thank you in advance.

Simple queries not working

Hi,

The search query described here, for finding all is_a relationships do not work, even for the provided example.

I followed all the examples given, loaded the pizza ontology but on trying the search query, I get the following error:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/owlready2/namespace.py", line 191, in search v2 = [child.storid for child in v.descendants()] AttributeError: 'str' object has no attribute 'descendants'

Can someone please help me out?

TypeError: '<' not supported between instances of 'str' and 'int'

I am attempting to save dynamically created classes and subclasses to a rdfxml file. I got the class data from a csv that I managed with pandas df. When I try running onto.save(file = 'onto.rdfxml', format = 'rdfxml') the following error is returned:

'''TypeError: '<' not supported between instances of 'str' and 'int' on line 464 of driver.py'''

At first I thought that it had to do with special characters and ints being in the strings used in the class names. But, after removing all special characters and whitespaces and replacing all ints with their spelt out names (ie 1 = one), the same TypeError was returned.

Next, I tried seeing if the ontology was being saved as expected. Using the docs, I ran the code below, and it showed that the classes and subclasses were being successfully added. So, the issue was clearly with saving the file.

class_list = list(onto.classes())
for i in class_list:
    print(i, "is a subclass of: ", end='')
    for j in i.is_a:
        print(j, end=', ')
    print("\n")

Then, I tried to see if saving the ontology to a different file type would work. I tried turtle, xml, own, and omn, and while the onto.save line ran successfully, it never stored any data. The file size stayed at 0 bytes.

Again, the error is '''TypeError: '<' not supported between instances of 'str' and 'int' on line 464 of driver.py''' found at:
File /opt/anaconda3/lib/python3.8/site-packages/owlready2/driver.py:466, in _save(f, format, graph, filter)

Setting error_on_undefined_entities=False

Hi,
I run sparql query and some enitities do not exist in ontology. I recieve an error:

ValueError: No existing entity for IRI 'http://purl.obolibrary.org/obo/RO_0000052'! (use error_on_undefined_entities=False to accept unknown entities in SPARQL queries)

How can I set error_on_undefined_entities=False?

Ontology not loaded

I have followed the instructions as they appear here, yet when I trying to load SNOMED CT using

>>> from owlready2 import *
>>> from owlready2.pymedtermino2.umls import *
>>> default_world.set_backend(filename = "pym.sqlite3")
>>> import_umls("mmsys.zip", terminologies = ["ICD10", "SNOMEDCT_US", "CUI"])
>>> default_world.save()

Output is:
Importing UMLS from /Users/yoav/Documents/2021AB-full/mmsys.zip with Python version 3.8.12 and Owlready version 2-0.36...
Parsing config/2021AB/MRSTY.RRF.gz as MRSTY with encoding UTF-8
Parsing config/2021AB/MRRANK.RRF as MRRANK
Breaking ORIG cycles...
Finalizing only properties and restrictions...
Finalizing CUI - ORIG mapping...
FTS Indexing...

then

>>> PYM = get_ontology("http://PYM/").load()
>>> SNOMEDCT_US = PYM["SNOMEDCT_US"]

however SNOMED_US appears to be NoneType.

When I change the last line to SOMETHING = PYM["CUI"], an object is returned.

Not sure what I'm missing.

Encountering "TypeError: 'NoneType' object is not subscriptable" while saving an ontology (onto.save())

This is happening after I try to save an ontology after removing some of its Object Properties. Not sure what the exact cause is and how to fix it.

TypeError                                 Traceback (most recent call last)
<ipython-input-20-a50699e0134c> in <module>
     39     filename = "raw/"+DATASET+"_"+split+".owl"
     40     print(onto, len(list(onto.properties())), list(onto.properties()))
---> 41     onto.save(file = filename, format = "rdfxml")

d:\Programs\Anaconda3\envs\pytorch\lib\site-packages\owlready2\namespace.py in save(self, file, format, **kargs)
   1004       if _LOG_LEVEL: print("* Owlready2 * Saving ontology %s to %s..." % (self.name, file), file = sys.stderr)
   1005       file = open(file, "wb")
-> 1006       self.graph.save(file, format, **kargs)
   1007       file.close()
   1008     else:

d:\Programs\Anaconda3\envs\pytorch\lib\site-packages\owlready2\driver.py in save(self, f, format, commit, **kargs)
    223   def save(self, f, format = "rdfxml", commit = False, **kargs):
    224     if commit: self.parent.commit()
--> 225     _save(f, format, self, **kargs)
    226 
    227 

d:\Programs\Anaconda3\envs\pytorch\lib\site-packages\owlready2\driver.py in _save(f, format, graph, filter)
    500 
    501       else:
--> 502         o = _unabbreviate(o)
    503         s_lines.append("""  <%s rdf:resource="%s"/>""" % (p, o))
    504 

d:\Programs\Anaconda3\envs\pytorch\lib\site-packages\owlready2\driver.py in _unabbreviate(storid)
    290     @lru_cache(None)
    291     def _unabbreviate(storid):
--> 292       r = graph._unabbreviate(storid).replace("&", "&amp;")
    293       if r.startswith(base_iri):
    294         if base_iri.endswith("/"): return r[len(base_iri) :]

d:\Programs\Anaconda3\envs\pytorch\lib\site-packages\owlready2\triplelite.py in _unabbreviate(self, storid)
    489 
    490   def _unabbreviate(self, storid):
--> 491     return self.execute("SELECT iri FROM resources WHERE storid=? LIMIT 1", (storid,)).fetchone()[0]
    492 
    493   def get_storid_dict(self):

read custom datatypes owlready2

Hello,

I have successfully defined a new datatype using owlready2, with a parser and unparser function.

But when I try to read the .owl file, this raise an error : ValueError: Cannot read literal of datatype 305!

is there a way to successfully read a value that has a custom datatype ?

Forum/Mailing List Down

The link in the Readme to the mailing list, http://owlready.8326.n8.nabble.com, gives a 404.

Problem loading ontology from an N-triples file

Hello
I'm testing owlready2 which seems interesting.
But, I'm encoutering problem with the loading phase of one of my files with
senneville_ontology= get_ontology("file://c://wamp64/www/barbules/ontologies/test.nt").load()
where test.nt contains only one line
<http://barbules.givingsense.eu/ontologies/barbules/SENNEVILLE> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#NamedIndividual> .
I'm getting the following error:
...
File "C:\wamp64\www\CPD\trials\venv\lib\site-packages\owlready2\rdfxml_2_ntriples.py", line 315, in parse
raise OwlReadyOntologyParsingError("RDF/XML parsing error in file %s, line %s, column %s." % (getattr(f, "name", getattr(f, "url", "???")), parser.CurrentLineNumber, parser.CurrentColumnNumber)) from e
owlready2.base.OwlReadyOntologyParsingError: RDF/XML parsing error in file c://wamp64/www/barbules/ontologies/test.nt, line 1, column 7.
So, the file is recognized as being an N-triples file, but the parser fails to parse it.

Can Domain and Range be retrieved for SNOMED-CT relationships?

Hello, thanks for providing SNOMED-CT access via owlready2!

In the SNOMED-CT documentation it is mentioned, that each relationship has a defined domain and range:
https://confluence.ihtsdotools.org/display/DOCEG/Structure+of+Domain+Coverage
grafik

For instance for the attribute Associated morphology (attribute) (116676008) it is stated that the domain is Clinical finding (finding) (404684003) and range is Morphologically abnormal structure (morphologic abnormality) (49755003).

In the PyMedTermino2 documentation, is is explained how relationships of concepts can be listed, but that does not cover whether another relationship can be used with a given concept regarding domain/range.

Can this information also be retrieved with owlready2/pymedtermino2?

Issues with exported ontology XML if entity IRIs use "/" instead of "#"

First of all, a fantastic tool!

I played with it today making ontology.

I noticed issues in generated ontology if I use "/" instead of "#" for entities IRIs.

Code for IRIs which use "/":

onto = get_ontology("http://knowledge.graph/wind/")
define_datatype_in_ontology(VestasNaming, "http://knowledge.graph/wind/VestasNaming", onto)

class DO(Thing):
    namespace = onto

class notation(Thing >> VestasNaming):
    namespace = onto
    
HorWdSpd = DO("HorWdSpd", namespace = onto, 
              label="Horizontal Wind Speed", 
              comment="IEC data object instance for Horizontal Wind Speed")

HorWdSpd.notation.append(VestasNaming("WindSpeed"))

onto.save("./ontology.xml")

which results in

<?xml version="1.0"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
         xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
         xmlns:owl="http://www.w3.org/2002/07/owl#"
         xmlns:wind="http://knowledge.graph/wind/"
         xmlns="http://knowledge.graph/wind/">

<owl:Ontology rdf:about="http://knowledge.graph/wind"/>

<owl:DatatypeProperty rdf:about="notation">
  <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
  <rdfs:range rdf:resource="VestasNaming"/>
</owl:DatatypeProperty>

<owl:Class rdf:about="DO">
  <rdfs:subClassOf rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
</owl:Class>

<rdfs:Datatype rdf:about="VestasNaming"/>

<wind:DO rdf:about="HorWdSpd">
  <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
  <rdfs:label rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Horizontal Wind Speed</rdfs:label>
  <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">IEC data object instance for Horizontal Wind Speed</rdfs:comment>
  <wind:notation rdf:datatype="VestasNaming">WindSpeed</wind:notation>
</wind:DO>


</rdf:RDF>

which when loaded to Protege results in two DO classes instead of one. One of those DO classes has correct IRI but no instances/individuals, the second one with an IRI equal to the filepath to onotology (obviously worng IRI) has a HorWdSpd individual related to it.

However, if I use "#" instead for IRI entities (i.e., base_iri#ClassName):

onto = get_ontology("http://knowledge.graph/wind")
define_datatype_in_ontology(VestasNaming, "http://knowledge.graph/wind#VestasNaming", onto)

class DO(Thing):
    namespace = onto

class notation(Thing >> VestasNaming):
    namespace = onto
    
HorWdSpd = DO("HorWdSpd", namespace = onto, 
              label="Horizontal Wind Speed", 
              comment="IEC data object instance for Horizontal Wind Speed")

HorWdSpd.notation.append(VestasNaming("WindSpeed"))

onto.save("./ontology.xml")

everything works as expected and resulting XML is correct:

<?xml version="1.0"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
         xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
         xmlns:owl="http://www.w3.org/2002/07/owl#"
         xml:base="http://knowledge.graph/wind"
         xmlns="http://knowledge.graph/wind#">

<owl:Ontology rdf:about="http://knowledge.graph/wind"/>

<owl:DatatypeProperty rdf:about="#notation">
  <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
  <rdfs:range rdf:resource="#VestasNaming"/>
</owl:DatatypeProperty>

<owl:Class rdf:about="#DO">
  <rdfs:subClassOf rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
</owl:Class>

<rdfs:Datatype rdf:about="#VestasNaming"/>

<DO rdf:about="#HorWdSpd">
  <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
  <rdfs:label rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Horizontal Wind Speed</rdfs:label>
  <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">IEC data object instance for Horizontal Wind Speed</rdfs:comment>
  <notation rdf:datatype="#VestasNaming">WindSpeed</notation>
</DO>


</rdf:RDF>

which when loaded in Protege result in a single class DO, and HorWdSpd instance of it.

Is there anything I should do to make sure that entity IRIs which use "/" work properly when ontology is exported to XML?

ontology import: classes of imported ontologies do not appear in target ontology class list

When importing an additional

onto = get_ontology("my_ontology.owl").load()
list(onto.classes())
... classes of onto are listed
# check imported ontologies - should be empty
onto.imported_ontologies
>> []  

another_onto = get_ontology("my_other_ontology.owl").load()
list(onto.classes())
... classes of another_onto are listed

onto.imported_ontologies.append(another_onto)
# checking ontology import
onto.imported_ontologies
>>[get_ontology("my_other_ontology")]

list(onto.classes())
... still only classes of onto appear, but not of another_onto

Intuitive behavior would be: here all classes should appear.

Change to multiprocessing prevents use in some contexts.

Hello. The recent change to use the multiprocessing instead of threading package for certain things like locks has prevented installation in certain virtualized environments that do not support multithreading. Would it be possible to scope these changes to a feature flag or maybe using a shim?

Saving only elements of the ontology used by the individuals

Hi, thanks for this library!

I was trying to create some individuals for a fairly large ontology, but after running onto.save(file = "output.n3", format = "ntriples") I see that the entire ontology is also in the saved file. Is there a way to only dump the elements that are actually used by the individuals?

Cheers.

Loading ontology

Behind a lab proxy, i would like to download ontology owl file and not rely on local file copy.
What would be the best strategy:
Can I provided a file like BytesIO object to get_ontology function, dealing with the download overhead myself?
Can i pass proxy settings to get_ontology?

Thank you for your time, (loving owlready2)

Cannot reload Pymedtermino2 Quadstore Non-Exclusively

Hello, I am working on a project where several processes need to use the Pymedtermino2 submodule concurrently and am having issues on both reloading the quadstore after the initial importation, and also non-exclusively accessing the reloaded quadstore.

When working with the first importation using the following code, everything works perfectly and I can access the database from multiple processes concurrently.

default_world.set_backend(filename = "pym.sqlite3", exclusive=False)
import_umls(umls_path, terminologies = ["ICD10", "SNOMEDCT_US", "CUI"])
default_world.save()
PYM = get_ontology("http://PYM/").load()

My problems start to arise when I am trying to reload the data from the quadstore saved in pym.sqlite3. If I am starting fresh and just imported everything, the following code can be run multiple times from different processes.

if not os.path.exists('pym.sqlite3'):
try:
default_world.set_backend(filename = "pym.sqlite3", exclusive=False)
PYM = get_ontology("http://PYM/").load()
default_world.save()
except:
PYM = World(filename= 'pym.sqlite3', exclusive=False).get_ontology('http://PYM").load()

The try block is placed there since upon the second time calling set_backend in a session, I recieve a ValueError: Cannot save existent quadstore in 'pym.sqlite3': File already exists! Use a new filename for saving quadstore or, for opening an already existent quadstore, do not create any triple before calling set_backend().

Additionally, I am getting many variations on OperationalError: database is locked whenever I try to access the database repeatedly.

Is there any guidance on what I am doing wrong or are there any possible bugs? Thanks for the help.

Memmory issue

Hello, I think there is a memory issue I face when dealing with large ontologies,
I was able to fix one related to reasoning memory (fixing java memory in reasoning.py) JAVA_MEMORY = 2000 which is limited to 2 GB, I managed to increase that.

There are also the memory settings for the SQL queries which I couldn't fix and it is limiting me from utilizing my available resources. can you help?

Issue with SWRL Rules and Data Property Inference

Context:

I have an ontology (.owl file) to which I added SWRL rules using the SWRL Plugin in the Protege editor. I have two queries:

  1. Can the data property within the ontology be inferred without the Pellet reasoner? Currently, the data property is not accessible by owl2ready.

  2. Is there a built-in function or way to access SWRL rules in the ontology?

duplicate file in owlready2 0.38 "driver (copie 1).py"

Hi,
I noticed that there seems to be a duplicated file in owlready2==0.38 called driver (copie 1).py.
It seems to be a duplication of driver.py. Would you mind removing or renaming it since it contains a space in the filename that prevents me from building a package with bazel.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.