API Reference#

This document is for advanced users of SimPhoNy and defines all its public API details. This means that only when there is a breaking change in any of the methods listed on this page, the major version number of SimPhoNy will change accordingly, as prescribed by the Semantic Versioning Specification.

Do not rely on the stability of methods not listed on this page.

If the __init__ method is not listed for a class, you are not expected to instantiate such class by yourself, and thus doing so is unsupported.

Ontology management#

simphony_osp.tools.pico.install(*files: Union[pathlib.Path, str], overwrite: bool = False) None[source]#

Install ontology packages.

Parameters
  • files – Paths of ontology packages to install. Alternatively, identifiers of ontology packages that are bundled with SimPhoNy.

  • overwrite – Whether to overwrite already installed ontology packages.

simphony_osp.tools.pico.uninstall(*identifiers: str) None[source]#

Uninstall ontology packages.

Parameters

identifiers – Identifiers of the ontology packages to uninstall.

simphony_osp.tools.pico.packages() Tuple[str][source]#

Returns the identifiers of all installed packages.

simphony_osp.tools.pico.namespaces() Tuple[simphony_osp.ontology.OntologyNamespace][source]#

Returns namespace objects for all the installed namespaces.

Terminological- and assertional knowledge#

class simphony_osp.ontology.OntologyNamespace(iri: Union[str, URIRef], ontology: Optional[Session] = None, name: Optional[str] = None)#

Bases: object

An ontology namespace.

Ontology namespace objects allow access to the terminological knowledge from the installed ontologies.

__contains__(item: Union[simphony_osp.ontology.OntologyEntity, rdflib.term.Identifier]) bool[source]#

Check whether the given ontology entity is part of the namespace.

An ontology entity is considered to be part of a namespace if its IRI starts with the namespace IRI and if it is part of the session that the namespace is bound to. Identifiers are only required to start with the namespace IRI to be considered part of the namespace object. Blank nodes are never part of a namespace.

Parameters

item – An ontology entity or identifier.

Returns

Whether the given entity or identifier is part of the namespace. Blank nodes are never part of a namespace.

__eq__(other: simphony_osp.ontology.OntologyNamespace) bool[source]#

Check whether the two namespace objects are equal.

Two namespace objects are considered to be equal when both have the same IRI and are bound to the same session.

Parameters

other – The namespace object to compare with.

Returns

Whether the given namespace object is equal.

Return type

bool

__getattr__(name: str) simphony_osp.ontology.OntologyEntity[source]#

Retrieve an entity by suffix or label.

Parameters

name – The label or namespace suffix of the ontology entity.

Raises
  • AttributeError – Unknown label or suffix.

  • AttributeError – Multiple entities for the given label or suffix.

Returns

An ontology entity with matching label or suffix.

__getitem__(name: str) simphony_osp.ontology.OntologyEntity[source]#

Retrieve an entity by suffix or label.

Useful for entities whose labels or suffixes contain characters which are not compatible with the Python syntax rules.

Parameters

name – The suffix or label of the ontology entity.

Raises
  • KeyError – Unknown label or suffix.

  • KeyError – Multiple entities for the given label or suffix.

Returns

An ontology entity with matching label or suffix.

__iter__() Iterator[simphony_osp.ontology.OntologyEntity][source]#

Iterate over the ontology entities in the namespace.

__len__() int[source]#

Return the number of entities in the namespace.

from_iri(iri: Union[str, rdflib.term.URIRef]) simphony_osp.ontology.OntologyEntity[source]#

Get an ontology entity directly from its IRI.

For consistency, this method only returns entities from this namespace.

Parameters

iri – The iri of the ontology entity.

Returns

The ontology entity.

Raises
  • KeyError – When the IRI does not belong to the namespace.

  • ValueError – When an invalid IRI is received.

from_label(label: str, lang: Optional[str] = None, case_sensitive: bool = False) simphony_osp.ontology.OntologyEntity[source]#

Get an ontology entity from its label.

Parameters
  • label – The label to match.

  • lang – Optionally filter labels by a specific language.

  • case_sensitive – Whether the match should be case-sensitive or not. The default setting is a case-insensitive lookup.

Raises
  • KeyError – No label matches the given one.

  • KeyError – More than one label matches the given one.

from_suffix(suffix: str) simphony_osp.ontology.OntologyEntity[source]#

Get an ontology entity from its namespace suffix.

Parameters

suffix – Suffix of the ontology entity.

Raises
  • KeyError – When no entity with such suffix exists in the namespace.

  • ValueError – When an invalid suffix is received (e.g. it contains a space).

get(name: str, default: Optional[Any] = None) simphony_osp.ontology.OntologyEntity[source]#

Get ontology entities from the bounded session by suffix or label.

Parameters
  • name – The label or suffix of the ontology entity.

  • default – The entity to return if no entity with such label or suffix is found.

Raises
  • KeyError – Unknown label or suffix (and no default given).

  • KeyError – Multiple entities for the given label or suffix.

Returns

The ontology entity with given label or suffix, or the default value.

property iri: rdflib.term.URIRef#

The IRI of the namespace.

property name: Optional[str]#

The name of the namespace.

For namespaces that have been imported from the simphony_osp.namespaces module, this name matches the alias given to the namespace in its ontology package.

class simphony_osp.ontology.OntologyEntity(uid: UID, session: Optional[Union[Session, Container, Wrapper]] = None, triples: Optional[Iterable[Triple]] = None, merge: Optional[bool] = False)#

Abstract superclass of any entity in ontology entity.

__bool__()[source]#

Returns the boolean value of the entity, always true.

__eq__(other: simphony_osp.ontology.OntologyEntity) bool[source]#

Check whether two entities are the same.

Two entities are considered equal when they have the same identifier and are stored in the same session.

Parameters

other – The other entity.

Returns

Whether the two entities are the same.

property direct_subclasses: FrozenSet[simphony_osp.ontology.entity.ONTOLOGY_ENTITY]#

Get the direct subclasses of the entity.

Returns

The direct subclasses of the entity.

property direct_superclasses: FrozenSet[simphony_osp.ontology.entity.ONTOLOGY_ENTITY]#

Get the direct superclasses of the entity.

Returns

The direct superclasses of the entity.

property identifier: rdflib.term.Identifier#

Semantic web resource identifying the entity.

Usually an URIRef or BNode.

property iri: rdflib.term.URIRef#

IRI of the Entity.

Raises

TypeError – When the identifier of the ontology entity is not an IRI.

is_subclass_of(other: simphony_osp.ontology.OntologyEntity) bool[source]#

Perform a subclass check.

Parameters

other – The other entity.

Returns

Whether self is a subclass of the other entity.

Return type

bool

is_superclass_of(other: simphony_osp.ontology.OntologyEntity) bool[source]#

Perform a superclass check.

Parameters

other – The other ontology entity.

Returns

Whether self is a superclass of the other other entity.

iter_labels(lang: Optional[str] = None, return_prop: bool = False, return_literal: bool = True) Iterator[Union[rdflib.term.Literal, str, Tuple[str, rdflib.term.URIRef], Tuple[rdflib.term.Literal, rdflib.term.URIRef]]][source]#

Returns all the available labels for this ontology entity.

Parameters
  • lang – retrieve labels only in a specific language.

  • return_prop – Whether to return the property that designates the label. When active, it is the second argument.

  • return_literal – Whether to return a literal or a string with the label (the former contains the language, the latter not).

Returns

An iterator yielding strings or literals; or tuples whose first element is a string or literal, and second element the property defining this label.

property label: Optional[str]#

Get the preferred label of this entity, if it exists.

See the docstring for label_literal for more information on the definition of preferred label.

property label_lang: Optional[str]#

Get the language of the main label of this entity.

See the docstring for label_literal for more information on the definition of main label.

property label_literal: Optional[rdflib.term.Literal]#

Get the main label for this entity.

The labels are first sorted by the property defining them, then by their language, and then by their length.

Returns

The first label in the resulting ordering is returned. If the entity has no label, then None is returned.

property namespace: Optional[OntologyNamespace]#

Return the ontology namespace to which this entity is associated.

property session: Session#

The session where the entity is stored.

property subclasses: FrozenSet[simphony_osp.ontology.entity.ONTOLOGY_ENTITY]#

Get the subclasses of the entity.

Returns

The subclasses of the entity

property superclasses: FrozenSet[simphony_osp.ontology.entity.ONTOLOGY_ENTITY]#

Get the superclass of the entity.

Returns

The superclasses of the entity.

property triples: Set[Tuple[rdflib.term.Node, rdflib.term.Node, rdflib.term.Node]]#

Get the all the triples where the entity is the subject.

Triples from the underlying RDFLib graph where the entity is stored in which the entity’s identifier is the subject.

class simphony_osp.ontology.OntologyClass(uid: UID, session: Optional[Session] = None, triples: Optional[Iterable[Triple]] = None, merge: bool = False)#

Bases: simphony_osp.ontology.OntologyEntity

A class defined in the ontology.

__call__(session=None, iri: Optional[Union[rdflib.term.URIRef, str]] = None, identifier: Optional[Union[uuid.UUID, str, rdflib.term.Node, int, bytes]] = None, _force: bool = False, **kwargs)[source]#

Create an OntologyIndividual object from this ontology class.

Parameters
  • identifier – The identifier of the ontology individual. When set to a string, has the same effect as the keyword argument iri. When set to`None`, a new identifier with a random UUID is generated. When set to any of the other accepted types, the given value is used to generate the UUID of the identifier. Defaults to None.

  • iri – The same as the identifier, but exclusively for IRI identifiers.

  • session – The session that the ontology individual will be stored in. Defaults to None (the default session).

Raises

TypeError – Error occurred during instantiation.

Returns

The new ontology individual.

property attributes: Mapping[simphony_osp.ontology.OntologyAttribute, FrozenSet[Optional[Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector]]]]#

Get the attributes of this class.

The attributes that all instances of this class are expected to have. A class can have attributes because one of its superclasses (including itself) has a default value for an attribute, or because the axioms affecting the superclass explicitly state that the class has such an attribute.

property axioms: FrozenSet[Union[simphony_osp.ontology.Restriction, simphony_osp.ontology.Composition]]#

Get all the axioms for the ontology class.

Axioms are OWL Restrictions and Compositions. Includes axioms inherited from its superclasses.

Returns

Axioms for the ontology class.

property optional_attributes: FrozenSet[simphony_osp.ontology.OntologyAttribute]#

Get the optional attributes of this class.

The optional attributes are the non-mandatory attributes (those not returned by the attributes property) that have the class defined as their domain, or any of its superclasses.

class simphony_osp.ontology.Restriction(uid: UID, session: Optional[Session] = None, triples: Optional[Iterable[Triple]] = None, merge: bool = False)#

Bases: simphony_osp.ontology.OntologyEntity

Restrictions on ontology classes.

property attribute: simphony_osp.ontology.OntologyAttribute#

The attribute that the ATTRIBUTE_RESTRICTION acts on.

Raises

AttributeError – Called on a RELATIONSHIP_RESTRICTION.

Returns

The attribute.

property quantifier: simphony_osp.ontology.QUANTIFIER#

Get the quantifier of the restriction.

Returns

The quantifier of the restriction.

property relationship: simphony_osp.ontology.OntologyRelationship#

The relationship that the RELATIONSHIP_RESTRICTION acts on.

Raises

AttributeError – Called on an ATTRIBUTE_RESTRICTION.

Returns

The relationship the restriction acts on.

property rtype: simphony_osp.ontology.RTYPE#

Type of restriction.

Whether the restriction acts on attributes or relationships.

Returns

The type of restriction.

Return type

RTYPE

property target: Union[OntologyClass, URIRef]#

The target ontology class or datatype.

Returns

The target class or datatype.

class simphony_osp.ontology.RESTRICTION_QUANTIFIER(value)#

Bases: enum.Enum

Quantifiers for restrictions.

EXACTLY: int = 3#
MAX: int = 5#
MIN: int = 4#
ONLY: int = 2#
SOME: int = 1#
VALUE: int = 6#
class simphony_osp.ontology.RESTRICTION_TYPE(value)#

Bases: enum.Enum

Types of restrictions.

ATTRIBUTE_RESTRICTION = 1#
RELATIONSHIP_RESTRICTION = 2#
class simphony_osp.ontology.Composition(uid: UID, session: Optional[Session] = None, triples: Optional[Iterable[Triple]] = None, merge: bool = False)#

Bases: simphony_osp.ontology.OntologyEntity

Combinations of multiple classes using logical formulae.

property operands: Tuple[Union[OntologyClass, Composition, Restriction]]#

The individual classes the formula is composed of.

Returns

The operands.

property operator: simphony_osp.ontology.OPERATOR#

The operator that connects the different classes in the formula.

Returns

The operator Enum.

class simphony_osp.ontology.COMPOSITION_OPERATOR(value)#

Bases: enum.Enum

Operations applicable to class definitions.

AND = 1#
NOT = 3#
OR = 2#
class simphony_osp.ontology.OntologyRelationship(uid: UID, session: Optional[Session] = None, triples: Optional[Iterable[Triple]] = None, merge: bool = False)#

Bases: simphony_osp.ontology.OntologyEntity

A relationship defined in the ontology.

property inverse: Optional[simphony_osp.ontology.OntologyRelationship]#

Get the inverse relationship if it exists.

class simphony_osp.ontology.OntologyAttribute(uid: UID, session: Optional[Session] = None, triples: Optional[Iterable[Triple]] = None, merge: bool = False)#

Bases: simphony_osp.ontology.OntologyEntity

An attribute defined in the ontology.

property datatype: Optional[rdflib.term.URIRef]#

Get the data type of the attribute.

Returns

IRI of the datatype.

Raises

NotImplementedError – More than one data type associated with the attribute.

class simphony_osp.ontology.OntologyAnnotation(uid: UID, session: Optional[Session] = None, triples: Optional[Iterable[Triple]] = None, merge: bool = False)#

Bases: simphony_osp.ontology.OntologyEntity

An annotation property defined in the ontology.

class simphony_osp.ontology.OntologyIndividual(uid: Optional[UID] = None, session: Optional[Session] = None, triples: Optional[Iterable[Triple]] = None, merge: bool = False, class_: Optional[OntologyClass] = None, attributes: Optional[Mapping[OntologyAttribute, Iterable[AttributeValue]]] = None)#

Bases: simphony_osp.ontology.OntologyEntity

An ontology individual.

__delitem__(rel: Union[OntologyAnnotation, OntologyAttribute, OntologyRelationship])[source]#

Delete all objects attached through the given predicate.

Parameters

rel – Either an ontology attribute, an ontology relationship or an ontology annotation (OWL datatype property, OWL object property, OWL annotation property). Alternatively a string, which will be resolved, using labels, to one of the classes described above.

__getattr__(name: str) simphony_osp.ontology.AttributeSet[source]#

Retrieve the value of an attribute of the individual.

Parameters

name – The label or suffix of the attribute.

Raises
  • AttributeError – Unknown attribute label or suffix.

  • AttributeError – Multiple attributes for the given label or suffix.

Returns

The value of the attribute (a python object).

__getitem__(rel: Union[OntologyAnnotation, OntologyAttribute, OntologyRelationship, str]) Union[simphony_osp.ontology.AttributeSet, simphony_osp.ontology.RelationshipSet, simphony_osp.ontology.AnnotationSet][source]#

Retrieve linked individuals, attribute values or annotation values.

The subscripting syntax individual[rel] allows: - When rel is an OntologyAttribute, to obtain a set containing all

the values assigned to the specified attribute. Such set can be modified in-place to change the assigned values.

  • When rel is an OntologyRelationship, to obtain a set containing all ontology individuals objects that are connected to individual through rel. Such set can be modified in-place to modify the existing connections.

  • When rel is an OntologyAnnotation, to obtain a set containing all the annotation values assigned to the specified annotation property. Such set can be modified in-place to modify the existing connections.

  • When rel is a string, the string is resolved to an OntologyAttribute, OntologyRelationship or OntologyAnnotation with a matching label, and then one of the cases above applies.

The reason why a set is returned and not a list, or any other container allowing repeated elements, is that the underlying RDF graph does not accept duplicate statements.

Parameters

rel – An ontology attribute, an ontology relationship or an ontology annotation (OWL datatype property, OWL object property, OWL annotation property). Alternatively a string, which will be resolved, using labels, to one of the classes described above.

Raises
  • KeyError – Unknown attribute, relationship or annotation label or suffix.

  • KeyError – Multiple attributes, relationships or annotations found for the given label or suffix.

  • TypeError – Trying to use something that is neither an OntologyAttribute, an OntologyRelationship, an OntologyAnnotation or a string as index.

__setattr__(name: str, value: Optional[Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, Set[Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector]]]]) None[source]#

Set the value(s) of an attribute.

Parameters
  • name – The label or suffix of the attribute.

  • value – The new value(s).

Raises
  • AttributeError – Unknown attribute label or suffix.

  • AttributeError – Multiple attributes for the given label or suffix.

__setitem__(rel: Union[OntologyAnnotation, OntologyAttribute, OntologyRelationship, str], values: Optional[Union[OntologyIndividual, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyRelationship, rdflib.term.URIRef, rdflib.term.Literal, Iterable[Union[OntologyIndividual, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyRelationship, rdflib.term.URIRef, rdflib.term.Literal]]]]) None[source]#

Manages object, data and annotation properties.

The subscripting syntax `individual[rel] = ` allows,

  • When rel is an OntologyRelationship, to replace the list of ontology individuals that are connected to individual through rel.

  • When rel is an OntologyAttribute, to replace the values of such attribute.

  • When rel is an OntologyAnnotation, to replace the annotation values of such annotation property.

  • When rel is a string, the string is resolved to an OntologyAttribute, OntologyRelationship or OntologyAnnotation with a matching label, and then one of the cases above applies.

This function only accepts hashable objects as input, as the underlying RDF graph does not accept duplicate statements.

Parameters
  • rel – Either an ontology attribute, an ontology relationship or an ontology annotation (OWL datatype property, OWL object property, OWL annotation property). Alternatively a string, which will be resolved, using labels, to one of the classes described above.

  • values – Either a single element compatible with the OWL standard (this includes ontology individuals) or a set of such elements.

Raises
  • KeyError – Unknown attribute, relationship or annotation label or suffix.

  • KeyError – Multiple attributes, relationships or annotations found for the given label or suffix.

  • TypeError – Trying to assign attributes using an object property, trying to assign ontology individuals using a data property, trying to use something that is neither an OntologyAttribute, an OntologyRelationship, an OntologyAnnotation nor a string as index.

property attributes: Mapping[simphony_osp.ontology.OntologyAttribute, FrozenSet[Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector]]]#

Get the attributes of this individual as a dictionary.

property classes: FrozenSet[simphony_osp.ontology.OntologyClass]#

Get the ontology classes of this ontology individual.

This property is writable. The classes that an ontology individual belongs to can be changed writing the desired values to this property.

Returns

A set with all the ontology classes of the ontology individual. When the individual has no classes, the set is empty.

connect(*individuals: Union[simphony_osp.ontology.OntologyIndividual, rdflib.term.Identifier, str], rel: Union[simphony_osp.ontology.OntologyRelationship, rdflib.term.Identifier]) None[source]#

Connect ontology individuals to other ontology individuals.

Parameters
  • individuals – The individuals to be connected. Their identifiers may also be used.

  • rel – The relationship between the objects.

Raises
  • TypeError – Objects that are not ontology individuals, identifiers or strings provided as positional arguments.

  • TypeError – Object that is not an ontology relationship or the identifier of an ontology relationship passed as keyword argument rel.

  • RuntimeError – Ontology individuals that belong to a different session provided.

disconnect(*individuals: Union[simphony_osp.ontology.OntologyIndividual, rdflib.term.Identifier, str], rel: Union[simphony_osp.ontology.OntologyRelationship, rdflib.term.Identifier] = rdflib.term.URIRef('http://www.w3.org/2002/07/owl#topObjectProperty'), oclass: Optional[simphony_osp.ontology.OntologyClass] = None) None[source]#

Disconnect ontology individuals from this one.

Parameters
  • individuals – Specify the individuals to disconnect. When no individuals are specified, all connected individuals are considered.

  • rel – Only remove individuals which are connected by subclass of the given relationship. Defaults to OWL.topObjectProperty (any relationship).

  • oclass – Only remove elements which are a subclass of the given ontology class. Defaults to None (no filter).

Raises
  • TypeError – Objects that are not ontology individuals, identifiers or strings provided as positional arguments.

  • TypeError – Object that is not an ontology relationship or the identifier of an ontology relationship passed as keyword argument rel.

  • TypeError – Object that is not an ontology class passed as keyword argument oclass.

  • RuntimeError – Ontology individuals that belong to a different session provided.

get(*individuals: Union[simphony_osp.ontology.OntologyIndividual, rdflib.term.Identifier, str], rel: Union[simphony_osp.ontology.OntologyRelationship, rdflib.term.Identifier] = rdflib.term.URIRef('http://www.w3.org/2002/07/owl#topObjectProperty'), oclass: Optional[simphony_osp.ontology.OntologyClass] = None, return_rel: bool = False) Union[simphony_osp.ontology.RelationshipSet, simphony_osp.ontology.OntologyIndividual, None, Tuple[Optional[simphony_osp.ontology.OntologyIndividual], ...], Tuple[Tuple[simphony_osp.ontology.OntologyIndividual, simphony_osp.ontology.OntologyRelationship]]][source]#

Return the connected individuals.

The structure of the output can vary depending on the form used for the call. See the “Returns:” section of this docstring for more details on this.

Note: If you are reading the SimPhoNy documentation API Reference, it is likely that you cannot read this docstring. As a workaround, click the source button to read it in its raw form.

Parameters
  • individuals – Restrict the elements to be returned to a certain subset of the connected elements.

  • rel – Only return individuals which are connected by a subclass of the given relationship. Defaults to OWL.topObjectProperty (any relationship).

  • oclass – Only yield individuals which are a subclass of the given ontology class. Defaults to None (no filter).

  • return_rel – Whether to return the connecting relationship. Defaults to False.

Returns

The result of the

call is a set-like object. This corresponds to the calls get(), get(rel=___), get(oclass=___), get(rel=___, oclass=___), with the parameter return_rel unset or set to False.

Calls with *individuals (Optional[OntologyIndividual],

Tuple[Optional[“OntologyIndividual”], …]):

The position of each element in the result is determined by the position of the corresponding identifier/individual in the given list of identifiers/individuals. In this case, the result can contain None values if a given identifier/individual is not connected to this individual, or if it does not satisfy the class filter. When only one individual or identifier is specified, a single object is returned instead of a Tuple. This description corresponds to the calls get(*individuals), get(*individuals, rel=___), get(*individuals, rel=___, oclass=___), with the parameter return_rel unset or set to False.

Calls with return_rel=True (Tuple[

Tuple[OntologyIndividual, OntologyRelationship]]):

The dependence of the order of the elements is maintained for the calls with *individuals, a non-deterministic order is used for the calls without *individuals. No None values are contained in the result (such identifiers or individuals are simply skipped). Moreover, the elements returned are now pairs of individuals and the relationship connecting this individual to such ones. This description corresponds to any call of the form get(…, return_rel=True).

Return type

Calls without *individuals (RelationshipSet)

Raises
  • TypeError – Objects that are not ontology individuals, identifiers or strings provided as positional arguments.

  • TypeError – Object that is not an ontology relationship or the identifier of an ontology relationship passed as keyword argument rel.

  • TypeError – Object that is not an ontology class passed as keyword argument oclass.

  • RuntimeError – Ontology individuals that belong to a different session provided.

is_a(ontology_class: simphony_osp.ontology.OntologyClass) bool[source]#

Check if the individual is an instance of the given ontology class.

Parameters

ontology_class – The ontology class to test against.

Returns

Whether the ontology individual is an instance of such ontology class.

iter(*individuals: Union[simphony_osp.ontology.OntologyIndividual, rdflib.term.Identifier, str], rel: Union[simphony_osp.ontology.OntologyRelationship, rdflib.term.Identifier] = rdflib.term.URIRef('http://www.w3.org/2002/07/owl#topObjectProperty'), oclass: Optional[simphony_osp.ontology.OntologyClass] = None, return_rel: bool = False) Union[Iterator[simphony_osp.ontology.OntologyIndividual], Iterator[Optional[simphony_osp.ontology.OntologyIndividual]], Iterator[Tuple[simphony_osp.ontology.OntologyIndividual, simphony_osp.ontology.OntologyRelationship]]][source]#

Iterate over the connected individuals.

The structure of the output can vary depending on the form used for the call. See the “Returns:” section of this docstring for more details on this.

Note: If you are reading the SimPhoNy documentation API Reference, it is likely that you cannot read this docstring. As a workaround, click the source button to read it in its raw form.

Parameters
  • individuals – Restrict the elements to be returned to a certain subset of the connected elements.

  • rel – Only yield individuals which are connected by a subclass of the given relationship. Defaults to OWL.topObjectProperty (any relationship).

  • oclass – Only yield individuals which are a subclass of the given ontology class. Defaults to None (no filter).

  • return_rel – Whether to yield the connecting relationship. Defaults to False.

Returns

The

position of each element in the result is non-deterministic. This corresponds to the calls iter(), iter(rel=___), iter(oclass=___), iter(rel=___, oclass=___), with the parameter return_rel unset or set to False.

Calls with *individuals (Iterator[Optional[

OntologyIndividual]]):

The position of each element in the result is determined by the position of the corresponding identifier/individual in the given list of identifiers/individuals. In this case, the result can contain None values if a given identifier/individual is not connected to this individual, or if it does not satisfy the class filter. This description corresponds to the calls iter(*individuals), iter(*individuals, rel=___), iter(*individuals, rel=___, oclass=`___)`.

Calls with return_rel=True (Iterator[

Tuple[OntologyIndividual, OntologyRelationship]]):

The dependence of the order of the elements is maintained for the calls with *individuals. No None values are contained in the result (such identifiers or individuals are simply skipped). Moreover, the elements returned are now pairs of individualsand the relationship connecting this individual to such ones. This description corresponds to any call of the form iter(…, return_rel=True).

Return type

Calls without *individuals (Iterator[OntologyIndividual])

Raises
  • TypeError – Objects that are not ontology individuals, identifiers or strings provided as positional arguments.

  • TypeError – Object that is not an ontology relationship or the identifier of an ontology relationship passed as keyword argument rel.

  • TypeError – Object that is not an ontology class passed as keyword argument oclass.

  • RuntimeError – Ontology individuals that belong to a different session provided.

property operations: simphony_osp.ontology.operations.operations.OperationsNamespace#

Access operations specific this individual’s class.

class simphony_osp.ontology.RelationshipSet(relationship: Optional[simphony_osp.ontology.OntologyRelationship], individual: simphony_osp.ontology.OntologyIndividual, oclass: Optional[simphony_osp.ontology.OntologyClass] = None, inverse: bool = False, uids: Optional[Iterable[simphony_osp.utils.datatypes.UID]] = None)#

A set interface to an ontology individual’s relationships.

This class looks like and acts like the standard set, but it is an interface to the methods from OntologyIndividual that manage the relationships.

__and__(other: set) set#

Return self&other.

__contains__(item: simphony_osp.ontology.OntologyIndividual) bool[source]#

Check if an individual is connected via set’s relationship.

__ge__(other: set) bool#

Return self>=other.

__gt__(other: set) bool#

Return self>other.

__iadd__(other: Any) simphony_osp.ontology.utils.DataStructureSet#

Return self+=other (equivalent to self|=other).

__iand__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self&=other.

Should perform the intersection on the underlying data structure.

__invert__() simphony_osp.ontology.RelationshipSet[source]#

Get the inverse RelationshipSet.

__ior__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self|=other.

Should perform the union on the underlying data structure.

__isub__(other: Any) simphony_osp.ontology.utils.DataStructureSet#

Return self-=other.

Based on difference_update.

__iter__() Iterator[simphony_osp.ontology.OntologyIndividual][source]#

Iterate over individuals assigned to self._predicates.

Note: no class filter.

Returns

The mentioned underlying set.

__ixor__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self^=other.

Should perform the XOR operation on the underlying data structure.

__le__(other: set) bool#

Return self<=other.

__len__() int#

Return len(self).

__lt__(other: set) bool#

Return self<other.

__ne__(other: set) bool#

Return self!=other.

__or__(other: set) set#

Return self|other.

__radd__(other: set) set#

Return other&self.

__ror__(other: set) set#

Return other|self.

__rsub__(other: set) set#

Return value-self.

__rxor__(other: set) set#

Return value^self.

__xor__(other: set) set#

Return self^other.

add(other: Any) None#

Add an element to a set.

This has no effect if the element is already present.

all() simphony_osp.ontology.individual.ObjectSet#

Return all elements from the set.

Returns

All elements from the set, namely the set itself.

any() Optional[Union[OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyIndividual, OntologyRelationship, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, rdflib.term.URIRef, rdflib.term.Literal]]#

Return any element of the set.

Returns

Any element from the set if the set is not empty, else None.

clear() None#

Remove all elements from this set.

copy() set#

Return a shallow copy of a set.

difference(other: Iterable) set#

Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)

difference_update(other: Iterable[simphony_osp.ontology.OntologyIndividual]) None[source]#

Remove all elements of another set from this set.

discard(other: Any) None#

Remove an element from a set if it is a member.

If the element is not a member, do nothing.

property individual: simphony_osp.ontology.OntologyIndividual#

Ontology individual that this set refers to.

intersection(other: set) set#

Return the intersection of two sets as a new set.

(i.e. all elements that are in both sets.)

intersection_update(other: Iterable[simphony_osp.ontology.OntologyIndividual]) None[source]#

Update the set with the intersection of itself and another.

property inverse: simphony_osp.ontology.RelationshipSet#

Get the inverse RelationshipSet.

Returns a RelationshipSet that works in the inverse direction: the ontology individuals displayed are the ones which are the subject of the relationship.

isdisjoint(other: set) bool#

Return True if two sets have a null intersection.

issubset(other: set) bool#

Report whether another set contains this set.

issuperset(other: set) bool#

Report whether this set contains another set.

one() Union[OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyIndividual, OntologyRelationship, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, rdflib.term.URIRef, rdflib.term.Literal]#

Return one element.

Return one element if the set contains one element, else raise an exception.

Returns

The only element contained in the set.

Raises
pop() Any#

Remove and return an arbitrary set element.

Raises KeyError if the set is empty.

property predicate: Union[OntologyAnnotation, OntologyAttribute, OntologyRelationship]#

Predicate that this set refers to.

remove(other: Any) None#

Remove an element from a set; it must be a member.

If the element is not a member, raise a KeyError.

symmetric_difference(other: set) set#

Return the symmetric difference of two sets as a new set.

symmetric_difference_update(other: Iterable[simphony_osp.ontology.OntologyIndividual]) None[source]#

Update with the symmetric difference of it and another.

union(other: set) set#

Return the union of sets as a new set.

update(other: Iterable[simphony_osp.ontology.OntologyIndividual]) None[source]#

Update the set with the union of itself and other.

class simphony_osp.ontology.AttributeSet(attribute: Optional[simphony_osp.ontology.OntologyAttribute], individual: simphony_osp.ontology.OntologyIndividual)#

A set interface to an ontology individual’s attributes.

This class looks like and acts like the standard set, but it is an interface to the methods from OntologyIndividual that manage the attributes.

__and__(other: set) set#

Return self&other.

__contains__(item: Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector]) bool[source]#

Check whether a value is assigned to the set’s attribute.

__ge__(other: set) bool#

Return self>=other.

__gt__(other: set) bool#

Return self>other.

__iadd__(other: Any) simphony_osp.ontology.utils.DataStructureSet#

Return self+=other (equivalent to self|=other).

__iand__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self&=other.

Should perform the intersection on the underlying data structure.

__ior__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self|=other.

Should perform the union on the underlying data structure.

__isub__(other: Any) simphony_osp.ontology.utils.DataStructureSet#

Return self-=other.

Based on difference_update.

__iter__() Iterator[Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector]][source]#

The values assigned to the referred predicates.

Such predicates are the main attribute and its subclasses.

Returns

The mentioned values.

__ixor__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self^=other.

Should perform the XOR operation on the underlying data structure.

__le__(other: set) bool#

Return self<=other.

__len__() int#

Return len(self).

__lt__(other: set) bool#

Return self<other.

__ne__(other: set) bool#

Return self!=other.

__or__(other: set) set#

Return self|other.

__radd__(other: set) set#

Return other&self.

__ror__(other: set) set#

Return other|self.

__rsub__(other: set) set#

Return value-self.

__rxor__(other: set) set#

Return value^self.

__xor__(other: set) set#

Return self^other.

add(other: Any) None#

Add an element to a set.

This has no effect if the element is already present.

all() simphony_osp.ontology.individual.ObjectSet#

Return all elements from the set.

Returns

All elements from the set, namely the set itself.

any() Optional[Union[OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyIndividual, OntologyRelationship, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, rdflib.term.URIRef, rdflib.term.Literal]]#

Return any element of the set.

Returns

Any element from the set if the set is not empty, else None.

clear() None#

Remove all elements from this set.

copy() set#

Return a shallow copy of a set.

difference(other: Iterable) set#

Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)

difference_update(other: Iterable[Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector]]) None[source]#

Remove all elements of another set from this set.

discard(other: Any) None#

Remove an element from a set if it is a member.

If the element is not a member, do nothing.

property individual: simphony_osp.ontology.OntologyIndividual#

Ontology individual that this set refers to.

intersection(other: set) set#

Return the intersection of two sets as a new set.

(i.e. all elements that are in both sets.)

intersection_update(other: Iterable[Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector]]) None[source]#

Update the set with the intersection of itself and another.

isdisjoint(other: set) bool#

Return True if two sets have a null intersection.

issubset(other: set) bool#

Report whether another set contains this set.

issuperset(other: set) bool#

Report whether this set contains another set.

one() Union[OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyIndividual, OntologyRelationship, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, rdflib.term.URIRef, rdflib.term.Literal]#

Return one element.

Return one element if the set contains one element, else raise an exception.

Returns

The only element contained in the set.

Raises
pop() Any#

Remove and return an arbitrary set element.

Raises KeyError if the set is empty.

property predicate: Union[OntologyAnnotation, OntologyAttribute, OntologyRelationship]#

Predicate that this set refers to.

remove(other: Any) None#

Remove an element from a set; it must be a member.

If the element is not a member, raise a KeyError.

symmetric_difference(other: set) set#

Return the symmetric difference of two sets as a new set.

symmetric_difference_update(other: Set[Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector]]) None[source]#

Update set with the symmetric difference of it and another.

union(other: set) set#

Return the union of sets as a new set.

update(other: Iterable[Union[str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector]]) None[source]#

Update the set with the union of itself and others.

class simphony_osp.ontology.AnnotationSet(annotation: Optional[simphony_osp.ontology.OntologyAnnotation], individual: simphony_osp.ontology.OntologyIndividual)#

A set interface to an ontology individual’s annotations.

This class looks like and acts like the standard set, but it is an interface to the methods from OntologyIndividual that manage the annotations.

__and__(other: set) set#

Return self&other.

__contains__(item) bool[source]#

Determine whether the individual is annotated with an item.

__ge__(other: set) bool#

Return self>=other.

__gt__(other: set) bool#

Return self>other.

__iadd__(other: Any) simphony_osp.ontology.utils.DataStructureSet#

Return self+=other (equivalent to self|=other).

__iand__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self&=other.

Should perform the intersection on the underlying data structure.

__ior__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self|=other.

Should perform the union on the underlying data structure.

__isub__(other: Any) simphony_osp.ontology.utils.DataStructureSet#

Return self-=other.

Based on difference_update.

__iter__() Iterator[Union[OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyIndividual, OntologyRelationship, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, rdflib.term.URIRef, rdflib.term.Literal]][source]#

Iterate over annotations linked to the individual.

__ixor__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self^=other.

Should perform the XOR operation on the underlying data structure.

__le__(other: set) bool#

Return self<=other.

__len__() int#

Return len(self).

__lt__(other: set) bool#

Return self<other.

__ne__(other: set) bool#

Return self!=other.

__or__(other: set) set#

Return self|other.

__radd__(other: set) set#

Return other&self.

__ror__(other: set) set#

Return other|self.

__rsub__(other: set) set#

Return value-self.

__rxor__(other: set) set#

Return value^self.

__xor__(other: set) set#

Return self^other.

add(other: Any) None#

Add an element to a set.

This has no effect if the element is already present.

all() simphony_osp.ontology.individual.ObjectSet#

Return all elements from the set.

Returns

All elements from the set, namely the set itself.

any() Optional[Union[OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyIndividual, OntologyRelationship, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, rdflib.term.URIRef, rdflib.term.Literal]]#

Return any element of the set.

Returns

Any element from the set if the set is not empty, else None.

clear() None#

Remove all elements from this set.

copy() set#

Return a shallow copy of a set.

difference(other: Iterable) set#

Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)

difference_update(other: Iterable[Any]) None[source]#

Return self-=other.

discard(other: Any) None#

Remove an element from a set if it is a member.

If the element is not a member, do nothing.

property individual: simphony_osp.ontology.OntologyIndividual#

Ontology individual that this set refers to.

intersection(other: set) set#

Return the intersection of two sets as a new set.

(i.e. all elements that are in both sets.)

intersection_update(other: Iterable[Union[OntologyIndividual, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyRelationship, rdflib.term.URIRef, rdflib.term.Literal]]) None[source]#

Update the set with the intersection of itself and another.

isdisjoint(other: set) bool#

Return True if two sets have a null intersection.

issubset(other: set) bool#

Report whether another set contains this set.

issuperset(other: set) bool#

Report whether this set contains another set.

one() Union[OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyIndividual, OntologyRelationship, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, rdflib.term.URIRef, rdflib.term.Literal]#

Return one element.

Return one element if the set contains one element, else raise an exception.

Returns

The only element contained in the set.

Raises
pop() Any#

Remove and return an arbitrary set element.

Raises KeyError if the set is empty.

property predicate: Union[OntologyAnnotation, OntologyAttribute, OntologyRelationship]#

Predicate that this set refers to.

remove(other: Any) None#

Remove an element from a set; it must be a member.

If the element is not a member, raise a KeyError.

symmetric_difference(other: set) set#

Return the symmetric difference of two sets as a new set.

symmetric_difference_update(other: Iterable[Union[OntologyIndividual, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyRelationship, rdflib.term.URIRef, rdflib.term.Literal]]) None[source]#

Return self^=other.

union(other: set) set#

Return the union of sets as a new set.

update(other: Iterable[Union[OntologyIndividual, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyRelationship, rdflib.term.URIRef, rdflib.term.Literal]]) None[source]#

Update the set with the union of itself and other.

class simphony_osp.ontology.ResultEmptyError#

Bases: Exception

The result is unexpectedly empty.

class simphony_osp.ontology.MultipleResultsError#

Bases: Exception

Only a single result is expected, but there were multiple.

Sessions and wrappers#

class simphony_osp.session.Session(base: Optional[Graph] = None, driver: Optional[InterfaceDriver] = None, ontology: Optional[Union[Session, bool]] = None, identifier: Optional[str] = None, namespaces: Dict[str, URIRef] = None, from_parser: Optional[OntologyParser] = None)#

‘Box’ that stores ontology individuals.

__contains__(item: simphony_osp.ontology.OntologyEntity)[source]#

Check whether an ontology entity is stored on the session.

__enter__()[source]#

Sets the session as the default session.

__exit__(exc_type, exc_val, exc_tb)[source]#

Restores the previous default session.

__init__(base: Optional[Graph] = None, driver: Optional[InterfaceDriver] = None, ontology: Optional[Union[Session, bool]] = None, identifier: Optional[str] = None, namespaces: Dict[str, URIRef] = None, from_parser: Optional[OntologyParser] = None)[source]#

Initializes the session.

The keyword arguments are used internally by SimPhoNy and are not meant to be set manually.

__iter__() Iterator[simphony_osp.ontology.OntologyEntity][source]#

Iterate over all the ontology entities in the session.

Be careful when using this operation, as it can be computationally very expensive.

__len__() int[source]#

Return the number of ontology entities within the session.

add(*individuals: Union[simphony_osp.ontology.OntologyIndividual, Iterable[simphony_osp.ontology.OntologyIndividual]], merge: bool = False, exists_ok: bool = False, all_triples: bool = False) Union[simphony_osp.ontology.OntologyIndividual, FrozenSet[simphony_osp.ontology.OntologyIndividual]][source]#

Copies ontology individuals to the session.

Parameters
  • individuals – Ontology individuals to add to this session.

  • merge – Whether to merge individuals with existing ones if their identifiers match (read the SimPhoNy documentation for more details).

  • exists_ok – Merge or overwrite individuals when they already exist in the session rather than raising an exception.

  • all_triples

    When an individual is added to the session, SimPhoNy only copies the details that are relevant from an ontological point of view: the individual’s attributes, the classes it belongs to, and its connections to other ontology individuals that are also being copied at the same time.

    However, in some cases, it is necessary to keep all the information about the individual, even if it cannot be understood by SimPhoNy. Set this option to True to copy all RDF statements describing the individual, that is, all RDF statements where the individual is the subject.

    One example of a situation where this option is useful is when the individual is attached through an object property to another one which is not properly defined (i.e. has no type assigned). This situation commonly arises when using the dcat:accessURL object property.

Returns

The new copies of the individuals.

Raises
  • RuntimeError – The individual being added has an identifier that

  • matches the identifier of an individual that already exists in the

  • session.

clear(force: bool = False)[source]#

Clear all the data stored in the session.

Parameters

force – Try to clear read-only sessions too.

close() None[source]#

Close the connection to the session’s backend.

Sessions are an interface to a graph linked to an RDFLib store (a backend). If the session will not be used anymore, then it makes sense to close the connection to such backend to free resources.

commit() None[source]#

Commit pending changes to the session’s graph.

compute(**kwargs) None[source]#

Run simulations on supported graph stores.

delete(*entities: Union[simphony_osp.ontology.OntologyEntity, rdflib.term.Identifier, Iterable[Union[simphony_osp.ontology.OntologyEntity, rdflib.term.Identifier]]])[source]#

Remove ontology individuals from the session.

Parameters

entities – Ontology individuals to remove from the session. It is also possible to just provide their identifiers.

Raises

ValueError – When at least one of the given ontology individuals is not contained in the session.

from_label(label: str, lang: Optional[str] = None, case_sensitive: bool = False) FrozenSet[simphony_osp.ontology.OntologyEntity][source]#

Get an ontology entity from its label.

Parameters
  • label – The label of the ontology entity.

  • lang – The language of the label.

  • case_sensitive – when false, look for similar labels with different capitalization.

Raises

KeyError – Unknown label.

Returns

The ontology entity.

get(*individuals: Union[simphony_osp.ontology.OntologyIndividual, rdflib.term.Identifier, str], oclass: Optional[simphony_osp.ontology.OntologyClass] = None) Union[Set[simphony_osp.ontology.OntologyIndividual], simphony_osp.ontology.OntologyIndividual, None, Tuple[Optional[simphony_osp.ontology.OntologyIndividual]]][source]#

Return the individuals in the session.

The structure of the output can vary depending on the form used for the call. See the “Returns:” section of this docstring for more details on this.

Note: If you are reading the SimPhoNy documentation API Reference, it is likely that you cannot read this docstring. As a workaround, click the source button to read it in its raw form.

Parameters
  • individuals – Restrict the individuals to be returned to a certain subset of the individuals in the session.

  • oclass – Only yield ontology individuals which belong to a subclass of the given ontology class. Defaults to None (no filter).

Returns

The result of the

call is a set-like object. This corresponds to the calls get(), get(oclass=___).

Calls with *individuals (Optional[OntologyIndividual],

Tuple[Optional[“OntologyIndividual”], …]):

The position of each element in the result is determined by the position of the corresponding identifier/individual in the given list of identifiers/individuals. In this case, the result can contain None values if a given identifier/individual is not in the session, or if it does not satisfy the class filter. This description corresponds to the calls get(*individuals), get(*individuals, oclass=`___)`.

Return type

Calls without *individuals (SessionSet)

Raises
  • TypeError – Objects that are not ontology individuals, identifiers or strings provided as positional arguments.

  • TypeError – Object that is not an ontology class passed as keyword argument oclass.

  • RuntimeError – Ontology individuals that belong to a different session provided.

iter(*individuals: Union[simphony_osp.ontology.OntologyIndividual, rdflib.term.Identifier, str], oclass: Optional[simphony_osp.ontology.OntologyClass] = None) Union[Iterator[simphony_osp.ontology.OntologyIndividual], Iterator[Optional[simphony_osp.ontology.OntologyIndividual]]][source]#

Iterate over the ontology individuals in the session.

The structure of the output can vary depending on the form used for the call. See the “Returns:” section of this docstring for more details on this.

Note: If you are reading the SimPhoNy documentation API Reference, it is likely that you cannot read this docstring. As a workaround, click the source button to read it in its raw form.

Parameters
  • individuals – Restrict the individuals to be returned to a certain subset of the individuals in the session.

  • oclass – Only yield ontology individuals which belong to a subclass of the given ontology class. Defaults to None (no filter).

Returns

The

position of each element in the result is non-deterministic. This corresponds to the calls iter(), iter(oclass=___).

Calls with *individuals (Iterator[Optional[

OntologyIndividual]]):

The position of each element in the result is determined by the position of the corresponding identifier/individual in the given list of identifiers/individuals. In this case, the result can contain None values if a given identifier/individual is not in the session, or if it does not satisfy the class filter. This description corresponds to the calls iter(*individuals), iter(*individuals, oclass=`___)`.

Return type

Calls without *individuals (Iterator[OntologyIndividual])

Raises
  • TypeError – Objects that are not ontology individuals, identifiers or strings provided as positional arguments.

  • TypeError – Object that is not an ontology class passed as keyword argument oclass.

  • RuntimeError – Ontology individuals that belong to a different session provided.

property locked: bool#

Whether the environment is locked or not.

A locked environment will not be closed when using it as a context manager and leaving the context. Useful for setting it as the default environment when it is not intended to close it afterwards.

sparql(query: str, ontology: bool = False) simphony_osp.session.session.QueryResult[source]#

Perform a SPARQL CONSTRUCT, DESCRIBE, SELECT or ASK query.

By default, the query is performed only on the session’s data (the ontology is not included).

Parameters
  • query – String to use as query.

  • ontology – Whether to include the ontology in the query or not. When the ontology is included, only read-only queries are possible.

class simphony_osp.session.SessionSet(session: Optional[simphony_osp.session.Session] = None, oclass: Optional[simphony_osp.ontology.OntologyClass] = None, uids: Optional[Iterable[simphony_osp.utils.datatypes.UID]] = None)#

A set interface to a session.

This class looks like and acts like the standard set, but it is an interface to the methods from Session that manage the addition and removal of individuals.

__and__(other: set) set#

Return self&other.

__contains__(item: simphony_osp.ontology.OntologyIndividual) bool[source]#

Check whether an ontology entity belongs to the session.

__ge__(other: set) bool#

Return self>=other.

__gt__(other: set) bool#

Return self>other.

__iadd__(other: Any) simphony_osp.ontology.utils.DataStructureSet#

Return self+=other (equivalent to self|=other).

__iand__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self&=other.

Should perform the intersection on the underlying data structure.

__ior__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self|=other.

Should perform the union on the underlying data structure.

__isub__(other: Any) simphony_osp.ontology.utils.DataStructureSet#

Return self-=other.

Based on difference_update.

__iter__()[source]#

The entities contained in the session.

__ixor__(other: set) simphony_osp.ontology.utils.DataStructureSet#

Return self^=other.

Should perform the XOR operation on the underlying data structure.

__le__(other: set) bool#

Return self<=other.

__len__() int#

Return len(self).

__lt__(other: set) bool#

Return self<other.

__ne__(other: set) bool#

Return self!=other.

__or__(other: set) set#

Return self|other.

__radd__(other: set) set#

Return other&self.

__ror__(other: set) set#

Return other|self.

__rsub__(other: set) set#

Return value-self.

__rxor__(other: set) set#

Return value^self.

__xor__(other: set) set#

Return self^other.

add(other: Any) None#

Add an element to a set.

This has no effect if the element is already present.

all() simphony_osp.session.SessionSet[source]#

Return all elements from the set.

Returns

All elements from the set, namely the set itself.

any() Optional[Union[OntologyAnnotation, OntologyAttribute, OntologyClass, OntologyIndividual, OntologyRelationship, str, float, fractions.Fraction, decimal.Decimal, int, bool, bytes, datetime.datetime, simphony_osp.utils.datatypes.UID, simphony_osp.utils.datatypes.Vector, rdflib.term.URIRef, rdflib.term.Literal]][source]#

Return any element of the set.

Returns

Any element from the set if the set is not empty, else None.

clear() None#

Remove all elements from this set.

copy() set#

Return a shallow copy of a set.

difference(other: Iterable) set#

Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)

difference_update(other: Iterable[simphony_osp.ontology.OntologyIndividual]) None[source]#

Remove all elements of another set from this set.

discard(other: Any) None#

Remove an element from a set if it is a member.

If the element is not a member, do nothing.

intersection(other: set) set#

Return the intersection of two sets as a new set.

(i.e. all elements that are in both sets.)

intersection_update(other: Iterable[simphony_osp.ontology.OntologyIndividual]) None[source]#

Update the set with the intersection of itself and another.

isdisjoint(other: set) bool#

Return True if two sets have a null intersection.

issubset(other: set) bool#

Report whether another set contains this set.

issuperset(other: set) bool#

Report whether this set contains another set.

one() simphony_osp.ontology.OntologyIndividual[source]#

Return one element.

Return one element if the set contains one element, else raise an exception.

Returns

The only element contained in the set.

Raises
pop() Any#

Remove and return an arbitrary set element.

Raises KeyError if the set is empty.

remove(other: Any) None#

Remove an element from a set; it must be a member.

If the element is not a member, raise a KeyError.

symmetric_difference(other: set) set#

Return the symmetric difference of two sets as a new set.

symmetric_difference_update(other: Iterable[simphony_osp.ontology.OntologyIndividual]) None[source]#

Update set with the symmetric difference of it and another.

union(other: set) set#

Return the union of sets as a new set.

update(other: Iterable[simphony_osp.ontology.OntologyIndividual]) None[source]#

Update the set with the union of itself and others.

simphony_osp.tools.import_file(file: Union[str, TextIO, dict, List[dict]], session: Optional[simphony_osp.session.Session] = None, format: Optional[str] = None, all_triples: bool = False, all_statements: bool = False) Union[simphony_osp.ontology.OntologyIndividual, Set[simphony_osp.ontology.OntologyIndividual]][source]#

Imports ontology individuals from a file and load them into a session.

Note: If you are reading the SimPhoNy documentation API Reference, it is likely that you cannot read this docstring. As a workaround, click the source button to read it in its raw form.

Parameters
  • file

    either, (str) the path of a file to import; (Union[List[dict], dict]) a dictionary representing the contents of

    a json file;

    (TextIO) any file-like object (in string mode) that provides a read() method. Note that it is possible to get such an object from any str object using the python standard library. For example, given the str object string, import io; filelike = io.StringIO(string) would create such an object. If not format is specified, it will be guessed.

  • session – the session in which the imported data will be stored.

  • format – the format of the content to import. The supported formats are the ones supported by RDFLib. See https://rdflib.readthedocs.io/en/latest/plugin_parsers.html. If no format is specified, then it will be guessed. Note that in some specific cases, the guess may be wrong. In such cases, try again specifying the format.

  • all_triples

    By default, SimPhoNy imports only ontology individuals. Moreover, not all information about such individuals is imported, but only the details that are relevant from an ontological point of view: the individual’s attributes, the classes it belongs to, and its connections to other ontology individuals that are also being copied at the same time.

    However, in some cases, it is necessary to keep all the information about an individual, even if it cannot be understood by SimPhoNy. Set this option to True to copy all RDF statements describing ontology individuals, that is, all RDF statements where the individuals are the subject.

    One example of a situation where this option is useful is when an individual is attached through an object property to another one which is not properly defined (i.e. has no type assigned). This situation commonly arises when using the dcat:accessURL object property.

  • all_statements

    SimPhoNy imports only ontology individuals by default. Moreover, not all information about such individuals is imported, but only the details that are relevant from an ontological point of view.

    Set this option to True to import all RDF statements contained in the file, even if they cannot be understood by SimPhoNy. Note that this option differs from all_triples because it is more general: the latter imports all triples where an ontology individual is the subject. This one imports all RDF statements, regardless of whether the subjects of the statements are individuals or not.

Returns

A set with the imported ontology individuals. If an individual was defined as the “main” one using the SimPhoNy ontology, then only the main individual is returned instead.

simphony_osp.tools.export_file(individuals_or_session: Optional[Union[simphony_osp.ontology.OntologyIndividual, Iterable[simphony_osp.ontology.OntologyIndividual], simphony_osp.session.Session]] = None, file: Optional[Union[str, TextIO]] = None, main: Optional[Union[str, rdflib.term.Identifier, simphony_osp.ontology.OntologyIndividual]] = None, format: str = 'text/turtle', all_triples: bool = False, all_statements: bool = False) Optional[str][source]#

Exports ontology individuals to a variety of formats.

Note: If you are reading the SimPhoNy documentation API Reference, it is likely that you cannot read this docstring. As a workaround, click the source button to read it in its raw form.

Parameters
  • individuals_or_session – (OntologyIndividual) A single ontology individual to export, or (Iterable[OntologyIndividual]) an iterable of ontology individuals, (Session) a session to serialize all of its ontology individuals. If None is specified, then the current session is exported.

  • file – either, (None) returns the exported file as a string, or (str) a path, to save the ontology individuals to, or (TextIO) any file-like object (in string mode) that provides a write() method. If this argument is not specified, a string with the results will be returned instead.

  • main – the identifier of an ontology individual to be marked as the “main” individual using the SimPhoNy ontology.

  • format – the target format. Defaults to triples in turtle syntax.

  • all_triples

    By default, SimPhoNy exports only ontology individuals. Moreover, not all information about such individuals is exported, but only the details that are relevant from an ontological point of view: the individual’s attributes, the classes it belongs to, and its connections to other ontology individuals that are also being copied at the same time.

    However, in some cases, it is necessary to keep all the information about an individual, even if it cannot be understood by SimPhoNy. Set this option to True to export all RDF statements describing ontology individuals, that is, all RDF statements where the individuals are the subject.

    One example of a situation where this option is useful is when an individual is attached through an object property to another one which is not properly defined (i.e. has no type assigned). This situation commonly arises when using the dcat:accessURL object property.

  • all_statements

    SimPhoNy exports only ontology individuals by default. Moreover, not all information about such individuals is exported, but only the details that are relevant from an ontological point of view.

    Set this option to True to export all RDF statements contained in a session, even if they cannot be understood by SimPhoNy. Note that this option differs from all_triples because it is more general: the latter exports all triples where an ontology individual is the subject. This one exports all RDF statements, regardless of whether the subjects of the statements are individuals or not.

Returns

The contents of the exported file as a string (if no file argument was provided), or nothing.

Visualization#

simphony_osp.tools.semantic2dot(*elements: Union[simphony_osp.ontology.OntologyIndividual, simphony_osp.ontology.OntologyNamespace, simphony_osp.session.Session], rel: Optional[Union[simphony_osp.ontology.OntologyRelationship, Iterable[simphony_osp.ontology.OntologyRelationship]]] = None) simphony_osp.tools.semantic2dot.Semantic2Dot[source]#

Utility for plotting ontology entities.

Note: If you are reading the SimPhoNy documentation API Reference, it is likely that you cannot read this docstring. As a workaround, click the source button to read it in its raw form.

Plot assertional knowledge (ontology individuals and the relationships between them), plot terminological knowledge (classes, relationships and attributes), or a combination of them.

Parameters
  • elements

    Elements to plot: (Session) plot the whole contents of a session; (OntologyNamespace) plot all the ontology entities contained

    in the ontology namespace;

    (OntologyIndividual) plots an ontology individual,

    or a collection of them, and the relationships between them if multiple are provided;

  • rel – When not None and when plotting an ontology individual, calls uses the method find(individual, rel=rel, find_all=True) from simphony_osp.tools.search to additionally plot such individuals.

class simphony_osp.tools.semantic2dot.Semantic2Dot(*elements: Union[simphony_osp.ontology.OntologyIndividual, simphony_osp.ontology.OntologyNamespace, simphony_osp.session.Session], rel: Optional[Union[simphony_osp.ontology.OntologyRelationship, Iterable[simphony_osp.ontology.OntologyRelationship]]] = None)[source]#

Class for ojects returned by the semantic2dot plotting tool.

Objects of this class produced as outcome of calling the semantic2dot plotting tool. They hold the graph information and can be used either to display it in a Jupyter notebook or render the graph to a file.

_repr_mimebundle_(include: Optional[Iterable[str]], exclude: Optional[Iterable[str]])[source]#

Render the graph as an image on IPython (e.g. Jupyter notebooks).

render(filename: Optional[str] = None, **kwargs) None[source]#

Save the graph to a dot and png file.

simphony_osp.tools.pretty_print(entity: simphony_osp.ontology.OntologyEntity, rel: typing.Union[simphony_osp.ontology.OntologyRelationship, typing.Iterable[simphony_osp.ontology.OntologyRelationship]] = <OntologyRelationship: http://www.w3.org/2002/07/owl#topObjectProperty>, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]#

Print a tree-like, text representation stemming from an individual.

Generates a tree-like, text-based representation stemming from a given ontology individual, that includes the IRI, ontology classes and attributes of the involved individuals, as well as the relationships connecting them.

Parameters
  • entity – Ontology individual to be used as starting point of the text-based representation.

  • file – A file to print the text to. Defaults to the standard output.

  • rel – Restrict the relationships to consider when searching for attached individuals to subclasses of the given relationships.

Tools#

simphony_osp.tools.host(wrapper: Type[simphony_osp.session.wrapper.WrapperSpawner], configuration_string: str = '', create: bool = False, hostname: str = '127.0.0.1', port: int = 6537, username: Optional[str] = None, password: Optional[str] = None, **kwargs: Union[str, int, float, bool, None, Iterable[Optional[Union[str, int, float, bool]]]])[source]#

Host a server based on a wrapper.

Opens the specified wrapper and starts listening for clients. The clients can connect to the wrapper’s session and perform actions.

Parameters
  • wrapper – The wrapper to be used.

  • configuration_string – The configuration string of the wrapper.

  • create – The value of the argument create for the wrapper.

  • hostname – Hostname where the server will listen.

  • port – The port that the server will use to listen.

  • username – A username for authenticating the client.

  • password – A password for authenticating the client.

  • **kwargs – Keyword arguments for the wrapper.

simphony_osp.tools.branch(individual, *individuals, rel: simphony_osp.ontology.OntologyRelationship) simphony_osp.ontology.OntologyIndividual[source]#

Like connect, but returns the element you connect to.

This makes it easier to create large structures involving ontology individuals.

Parameters
  • individual – The ontology individual that is the subject of the connections to be created.

  • individuals – Ontology individuals to connect to.

  • rel – Relationship to use.

Returns

The ontology individual that is the subject of the connections to be created (the first argument).

simphony_osp.tools.relationships_between(subj: simphony_osp.ontology.OntologyIndividual, obj: simphony_osp.ontology.OntologyIndividual) Set[simphony_osp.ontology.OntologyRelationship][source]#

Get the set of relationships between two ontology individuals.

Parameters
  • subj – The subject of the relationship.

  • obj – The object (target) of the relationship.

Returns

The set of relationships between the given subject and object individuals.

Development#

class simphony_osp.development.Wrapper(**kwargs: Union[str, int, float, bool, None, Iterable[Optional[Union[str, int, float, bool]]]])#

To be implemented by interface/wrapper developers.

This is the most generic type of interface.

__init__(**kwargs: Union[str, int, float, bool, None, Iterable[Optional[Union[str, int, float, bool]]]])#

Initialize the wrapper.

The __init__ method accepts JSON-serializable keyword arguments in order to let the user configure parameters of the wrapper that are not configurable via the ontology. For example, the type of solver used by a simulation engine.

Save such parameters to private attribute to use them later (e.g. in the open method).

Parameters

kwargs – JSON-serializable keyword arguments that contain no nested JSON objects (check the type hint for this argument).

add(triple: Tuple[rdflib.term.Node, rdflib.term.Node, rdflib.term.Node]) bool#

Inspect and control the addition of triples to the base graph.

Parameters

triple – The triple being added.

Returns

True when the triple should be added to the base graph. False when the triple should be caught, and therefore not added to the base graph. This triple will be latter available during commit on the buffer so that the changes that it introduces can be translated to the data structure.

abstract close() None#

Close the data source that the interface interacts with.

This method should NOT commit uncommitted changes.

This method should close the connection that was obtained in open, and free any locked up resources.

You can expect calls to this method even when the data source is already closed. Therefore, an implementation like the following is recommended.

>>> def close(self):
>>>    if your_data_source_is_already_closed:
>>>        return
>>>
>>>    # Close the connection to your data source.
>>>    # your_data_source_is_already_closed is for now True
abstract commit() None#

This method commits the changes made by the user.

Within this method, you have access to the following resources:

  • self.base: The base graph (rw). You are not expected to modify it.

  • self.old_graph: The old graph (ro).

  • self.new_graph: The new graph (ro).

  • self.buffer: The buffer of triples caught by add and remove (rw) that you now have to reflect on the data structures of your software.

  • self.session_base: A session based on the base graph (rw). You are not expected to modify it.

  • self.session_old: A session based on the old graph (ro).

  • self.session_new: A session based on the new graph (ro).

  • self.session: same as self.session_new.

  • self.added: A list of added individuals (rw). You are not expected to modify the entities.

  • self.updated: A list of updated individuals (rw). You are not expected to modify the entities.

  • self.deleted: A list of deleted individuals (rw). You are not expected to modify the entities.

Before updating the data structures, check that the changes provided by the user do not leave them in a consistent state. This necessary because SimPhoNy cannot revert the changes you make to your data structures. Raise an AssertionError if the check fails.

Raises

AssertionError – When the data provided by the user would produce an inconsistent or unpredictable state of the data structures.

compute(**kwargs: Union[str, int, float, bool, None, Iterable[Optional[Union[str, int, float, bool]]]]) None#

Compute new information (e.g. run a simulation).

Compute the new information on the backend and reflect the changes on the base graph. The default session is the base session.

The base graph is available on self.base, and a session based on the base graph is available on self.session and self.session_base.

delete(key: str) None#

Delete a file.

Delete the file associated with the provided key.

Parameters

key – Identifier of the individual associated with the file.

load(key: str) BinaryIO#

Retrieve a file.

Provide a file handle associated with the provided key.

Parameters

key – Identifier of the individual associated with the file.

Returns

File handle associated with the provided key.

abstract open(configuration: str, create: bool = False) None#

Open the data source that the wrapper interacts with.

You can expect calls to this method even when the data source is already accesible, therefore, an implementation similar to the one below is recommended.

>>> def open(self, configuration: str, create: bool = False):
>>>    if your_data_source_is_already_open:
>>>        return
>>>        # To improve the user experience you can check if the
>>>        # configuration string leads to a resource different from
>>>        # the current one and raise an error informing the user.
>>>
>>>    # Connect to your data source...
>>>    # your_data_source_is_already_open is for now True.

If you are using a custom base graph, please set self.base = your_graph within this method. Otherwise, an empty base graph will be created instead.

Parameters
  • configuration – Used to locate or configure the data source to be opened.

  • create – Whether the data source should be created if it does not exist. When false, if the data source does not exist, you should raise an exception. When true, create an empty data source.

abstract populate() None#

Populate the base session so that it represents the data source.

This command is run after the data source is opened. Here you are expected to populate the base graph so that its information mimics the information on the data source, unless you are generating triples on the fly using the triples method. The default session inside this method is a session based on the base graph.

The base graph is available on self.base, and a session based on the base graph is available on self.session and self.session_base.

remove(pattern: Tuple[Optional[rdflib.term.Node], Optional[rdflib.term.Node], Optional[rdflib.term.Node]]) Iterator[Tuple[rdflib.term.Node, rdflib.term.Node, rdflib.term.Node]]#

Inspect and control the removal of triples from the base graph.

Parameters

pattern – The pattern being removed.

Returns

An iterator with the triples that should be removed from the base graph. Any triples not included will not be removed, and will be available on the buffer during commit.

save(key: str, file: BinaryIO) None#

Save a file.

Read the bytestream offered as a file handle and save the contents somewhere, associating them with the provided key for later retrieval.

Parameters
  • key – Identifier of the individual associated with the file.

  • file – File (as a file-like object) to be saved.

triples(pattern: Tuple[Optional[rdflib.term.Node], Optional[rdflib.term.Node], Optional[rdflib.term.Node]]) Iterator[Tuple[rdflib.term.Node, rdflib.term.Node, rdflib.term.Node]]#

Intercept a triple pattern query.

Can be used to produce triples that do not exist on the base graph on the fly.

Parameters

pattern – The pattern being queried.

Returns

An iterator yielding triples

class simphony_osp.development.BufferType(value)#

Bases: enum.IntEnum

Enum representing the two possible types of triple buffers.

  • ADDED: For triples that have been added.

  • DELETED: For triples that have been deleted.

ADDED = 0#
DELETED = 1#
class simphony_osp.development.Operations(individual: OntologyIndividual)#

Bases: abc.ABC

Define operations for an ontology class.

__init__(individual: OntologyIndividual)[source]#

Initialization of your instance of the operations.

It is recommended to save the individual that is received as an argument to an instance attribute, as the operations to be executed are supposed to be related to it.

abstract property iri: Union[str, Iterable[str]]#

IRI of the ontology class for which operations should be registered.

It is also possible to define several IRIs at once (by returning an iterable).

simphony_osp.development.find_operations(packages: Optional[Union[List[str], str]] = None) Set[str]#

Generates the entry point definitions for operations.

Scans one or several packages and generates sets of strings that can be used in setup.py to register SimPhoNy ontology operations.

This method is meant to ease the work that operation developers have to do in their setup.py files.

Parameters

packages – name(s) of the package(s) to scan. When left empty, all packages on the working directory are scanned.

Returns

Set of strings that can be used with the “simphony_osp.ontology.operations” entry point.

Example

{“File = simphony_osp.ontology.operations.file:File”}