API Reference

This document is for developers and/or advanced users of OSP-core, it contains all API details.

CUDS

class osp.core.cuds.Cuds(attributes: Dict[osp.core.ontology.attribute.OntologyAttribute, Any], oclass: Optional[osp.core.ontology.oclass.OntologyClass] = None, session: Optional[osp.core.session.session.Session] = None, iri: Optional[rdflib.term.URIRef] = None, uid: Optional[Union[uuid.UUID, rdflib.term.URIRef]] = None, extra_triples: Iterable[Tuple[Union[rdflib.term.URIRef, rdflib.term.BNode], Union[rdflib.term.URIRef, rdflib.term.BNode], Union[rdflib.term.URIRef, rdflib.term.BNode]]] = ())[source]

Bases: object

A Common Universal Data Structure.

The CUDS object is an ontology individual that can be used like a container. It has attributes and is connected to other cuds objects via relationships.

add(*args: osp.core.cuds.Cuds, rel: Optional[osp.core.ontology.relationship.OntologyRelationship] = None)Union[osp.core.cuds.Cuds, List[osp.core.cuds.Cuds]][source]

Add CUDS objects to their respective relationship.

If the added objects are associated with the same session, only a link is created. Otherwise, the a deepcopy is made and added to the session of this Cuds object. Before adding, check for invalid keys to avoid inconsistencies later.

Parameters
Raises
  • TypeError – Ne relationship given and no default specified.

  • ValueError – Added a CUDS object that is already in the container.

Returns

The CUDS objects that have been added,

associated with the session of the current CUDS object. Result type is a list, if more than one CUDS object is returned.

Return type

Union[Cuds, List[Cuds]]

get(*uids: Union[uuid.UUID, rdflib.term.URIRef], rel: osp.core.ontology.relationship.OntologyRelationship = <OntologyRelationship cuba.activeRelationship>, oclass: Optional[osp.core.ontology.oclass.OntologyClass] = None, return_rel: bool = False)Union[osp.core.cuds.Cuds, List[osp.core.cuds.Cuds]][source]

Return the contained elements.

Filter elements by given type, uid or relationship. Expected calls are get(), get(*uids), get(rel), get(oclass), get(*indentifiers, rel), get(rel, oclass). If uids are specified:

The position of each element in the result is determined by to the position of the corresponding uid in the given list of uids. In this case, the result can contain None values if a given uid is not a child of this cuds_object. If only a single indentifier is given, only this one element is returned (i.e. no list).

If no uids are specified:

The result is a collection, where the elements are ordered randomly.

Parameters
  • uids (Union[UUID, URIRef]) – uids of the elements.

  • rel (OntologyRelationship, optional) – Only return cuds_object which are connected by subclass of given relationship. Defaults to cuba.activeRelationship.

  • oclass (OntologyClass, optional) – Only return elements which are a subclass of the given ontology class. Defaults to None.

  • return_rel (bool, optional) – Whether to return the connecting relationship. Defaults to False.

Returns

The queried objects.

Return type

Union[Cuds, List[Cuds]]

get_attributes()[source]

Get the attributes as a dictionary.

get_triples(include_neighbor_types=False)[source]

Get the triples of the cuds object.

property iri

Get the IRI of the CUDS object.

is_a(oclass)[source]

Check if the CUDS object is an instance of the given oclass.

Parameters

oclass (OntologyClass) – Check if the CUDS object is an instance of this oclass.

Returns

Whether the CUDS object is an instance of the given oclass.

Return type

bool

iter(*uids: Union[uuid.UUID, rdflib.term.URIRef], rel: osp.core.ontology.relationship.OntologyRelationship = <OntologyRelationship cuba.activeRelationship>, oclass: Optional[osp.core.ontology.oclass.OntologyClass] = None, return_rel: bool = False)Iterator[osp.core.cuds.Cuds][source]

Iterate over the contained elements.

Only iterate over objects of a given type, uid or oclass.

Expected calls are iter(), iter(*uids), iter(rel), iter(oclass), iter(*uids, rel), iter(rel, oclass). If uids are specified:

The position of each element in the result is determined by to the position of the corresponding uid in the given list of uids. In this case, the result can contain None values if a given uid is not a child of this cuds_object.

If no uids are specified:

The result is ordered randomly.

Parameters
  • uids (Union[UUID, URIRef]) – uids of the elements.

  • rel (OntologyRelationship, optional) – Only return cuds_object which are connected by subclass of given relationship. Defaults to cuba.activeRelationship.

  • oclass (OntologyClass, optional) – Only return elements which are a subclass of the given ontology class. Defaults to None.

  • return_rel (bool, optional) – Whether to return the connecting relationship. Defaults to False.

Returns

The queried objects.

Return type

Iterator[Cuds]

property oclass

Get the type of the cuds object.

property oclasses

Get the ontology classes of this CUDS object.

remove(*args: Union[osp.core.cuds.Cuds, uuid.UUID, rdflib.term.URIRef], rel: osp.core.ontology.relationship.OntologyRelationship = <OntologyRelationship cuba.activeRelationship>, oclass: Optional[osp.core.ontology.oclass.OntologyClass] = None)[source]

Remove elements from the CUDS object.

Expected calls are remove(), remove(*uids/Cuds), remove(rel), remove(oclass), remove(*uids/Cuds, rel), remove(rel, oclass)

Parameters
  • args (Union[Cuds, UUID, URIRef]) – UUIDs of the elements to remove or the elements themselves.

  • rel (OntologyRelationship, optional) – Only remove cuds_object which are connected by subclass of given relationship. Defaults to cuba.activeRelationship.

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

Raises

RuntimeError – No CUDS object removed, because specified CUDS objects are not in the container of the current CUDS object directly.

property session

Get the session of the cuds object.

property uid

Get the uid of the CUDS object.

This is the public getter of the property.

update(*args: osp.core.cuds.Cuds)List[osp.core.cuds.Cuds][source]

Update the Cuds object.

Updates the object by providing updated versions of CUDS objects that are directly in the container of this CUDS object. The updated versions must be associated with a different session.

Parameters

args (Cuds) – The updated versions to use to update the current object.

Raises
  • ValueError – Provided a CUDS objects is not in the container of the current CUDS

  • ValueError – Provided CUDS object is associated with the same session as the current CUDS object. Therefore it is not an updated version.

Returns

The CUDS objects that have been updated,

associated with the session of the current CUDS object. Result type is a list, if more than one CUDS object is returned.

Return type

Union[Cuds, List[Cuds]]

Ontology interface

class osp.core.ontology.namespace.OntologyNamespace(name, namespace_registry, iri)[source]

Bases: object

A namespace in the ontology.

__contains__(item)[source]

Check whether the given entity is part of the namespace.

Parameters

item (Union[str, rdflib.URIRef, OntologyEntity, rdflib.BNode]) – The name, IRI of an entity, the entity itself or a blank node.

Returns

Whether the given entity name or IRI is part of the

namespace. Blank nodes are never part of a namespace.

Return type

bool

__eq__(other)[source]

Check whether the two namespace objects are the same.

Parameters

other (OntologyNamespace) – The namespace to compare with.

Returns

Whether the given namespace is the same.

Return type

bool

__getattr__(name)[source]

Get an ontology entity from the registry by label or suffix.

Parameters

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

Raises

AttributeError – Unknown label or suffix.

Returns

The ontology entity.

Return type

OntologyEntity

__getitem__(label)[source]

Get an ontology entity from the registry by label.

Useful for entities whose labels contains characters which are not compatible with the Python syntax.

Parameters

label (str) – The label of the ontology entity.

Raises

KeyError – Unknown label.

Returns

The ontology entity.

Return type

OntologyEntity

__iter__()[source]

Iterate over the ontology entities in the namespace.

Returns

An iterator over the entities.

Return type

Iterator[OntologyEntity]

get(name, fallback=None)[source]

Get an ontology entity from the registry by suffix or label.

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

  • default (Any) – The value to return if it doesn’t exist.

  • fallback (Any) – The fallback value, defaults to None.

Returns

The ontology entity

Return type

OntologyEntity

get_default_rel()[source]

Get the default relationship of the namespace.

get_from_iri(iri, _name=None)[source]

Get an ontology entity directly from its IRI.

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

Parameters
  • iri (Union[str, rdlib.URIRef]) – The iri of the ontology entity.

  • _name (str) – Not mean to be provided by the user. Just passed to the from_iri method of the namespace registry.

Returns

The ontology entity.

Return type

OntologyEntity

Raises

KeyError – When the iri does not belong to the namespace.

get_from_suffix(suffix, case_sensitive=False)[source]

Get an ontology entity from its namespace suffix.

Parameters
  • suffix (str) – Suffix of the ontology entity.

  • case_sensitive (bool) – Whether to search also for the same suffix with different capitalization. By default, such a search is performed.

get_iri()[source]

Get the IRI of the namespace.

get_name()[source]

Get the name of the namespace.

class osp.core.ontology.entity.OntologyEntity(namespace_registry, namespace_iri, name, iri_suffix)[source]

Bases: abc.ABC

Abstract superclass of any entity in the ontology.

property description

Get the description of the entity.

Returns

The description of the entity

Return type

str

property direct_subclasses

Get the direct subclasses of the entity.

Returns

The direct subclasses of the entity

Return type

Set[OntologyEntity]

property direct_superclasses

Get the direct superclass of the entity.

Returns

The direct superclasses of the entity

Return type

List[OntologyEntity]

get_triples()[source]

Get the triples of the entity.

property iri

Get the IRI of the Entity.

is_subclass_of(other)[source]

Perform a subclass check.

Parameters

other (Entity) – The other entity.

Returns

Whether self is a subclass of other.

Return type

bool

is_superclass_of(other)[source]

Perform a superclass check.

Parameters

other (Entity) – The other entity.

Returns

Whether self is a superclass of other.

Return type

bool

property name

Get the name of the entity.

property namespace

Get the namespace object of the entity.

property subclasses

Get the subclasses of the entity.

Returns

The direct subclasses of the entity

Return type

Set[OntologyEntity]

property superclasses

Get the superclass of the entity.

Returns

The direct superclasses of the entity

Return type

Set[OntologyEntity]

property tblname

Get the name used in storage backends to store instances.

class osp.core.ontology.oclass.OntologyClass(namespace_registry, namespace_iri, name, iri_suffix)[source]

Bases: osp.core.ontology.entity.OntologyEntity

A class defined in the ontology.

property attributes

Get all the attributes of this oclass.

Returns

Mapping from attribute to default

Return type

Dict[OntologyAttribute, str]

property axioms

Get all the axioms for the ontology class.

Include axioms of superclasses.

Returns

The list of axioms for the ontology class.

Return type

List[Restriction]

get_attribute_by_argname(name)[source]

Get the attribute object with the argname of the object.

Parameters

name (str) – The argname of the attribute

Returns

The attribute

Return type

OntologyAttribute

property own_attributes

Get the non-inherited attributes of this oclass.

Returns

Mapping from attribute to default

Return type

Dict[OntologyAttribute, str]

class osp.core.ontology.oclass_restriction.Restriction(bnode, namespace_registry)[source]

Bases: object

A class to represet restrictions on ontology classes.

property attribute

The attribute the restriction acts on.

Only for ATTRIBUTE_RESTRICTIONs.

Raises

AttributeError – self is a RELATIONSHIP_RESTRICTIONs.

Returns

The datatype of the attribute.

Return type

UriRef

property quantifier

Get the quantifier of the restriction.

Returns

The quantifier of the restriction.

Return type

QUANTIFIER

property relationship

The relationship the RELATIONSHIP_RESTRICTION acts on.

Raises

AttributeError – Called on an ATTRIBUTE_RESTRICTION.

Returns

The relationship the restriction acts on.

Return type

OntologyRelationship

property rtype

Return the type of restriction.

Whether the restriction acts on attributes or relationships.

Returns

The type of restriction.

Return type

RTYPE

property target

The target ontology class or datatype.

Returns

The target class or datatype.

Return type

Union[OntologyClass, UriRef]

class osp.core.ontology.oclass_composition.Composition(bnode, namespace_registry)[source]

Bases: object

Combine multiple classes using logical formulae.

property operands

The individual classes the formula is composed of.

Returns

The operands.

Return type

Union[OntologyClass, Composition, Restriction]

property operator

The operator that connects the different classes in the formula.

Returns

The operator Enum.

Return type

OPERATOR

class osp.core.ontology.relationship.OntologyRelationship(namespace_registry, namespace_iri, name, iri_suffix)[source]

Bases: osp.core.ontology.entity.OntologyEntity

A relationship defined in the ontology.

property inverse

Get the inverse of this relationship.

If it doesn’t exist, add one to the graph.

Returns

The inverse relationship.

Return type

OntologyRelationship

class osp.core.ontology.attribute.OntologyAttribute(namespace_registry, namespace_iri, name, iri_suffix)[source]

Bases: osp.core.ontology.entity.OntologyEntity

An attribute defined in the ontology.

property argname

Get the name of the attribute when used as an argument.

This name is used when construction a cuds object or accessing the attributes of a CUDS object.

convert_to_basic_type(value)[source]

Convert from the datatype of the value to a python basic type.

Parameters

value (Any) – The value to convert

Returns

The converted value

Return type

Any

convert_to_datatype(value)[source]

Convert to the datatype of the value.

Parameters

value (Any) – The value to convert

Returns

The converted value

Return type

Any

property datatype

Get the datatype of the attribute.

Returns

IRI of the datatype

Return type

URIRef

Raises

RuntimeError – More than one datatype associated with the attribute. # TODO should be allowed

Sessions

class osp.core.session.session.Session[source]

Bases: abc.ABC

Abstract Base Class for all Sessions.

Defines the common standard API and sets the registry.

close()[source]

Close the connection to the backend.

delete_cuds_object(cuds_object)[source]

Remove a CUDS object.

Will not delete the cuds objects contained.

Parameters

cuds_object (Cuds) – The CUDS object to be deleted

prune(rel=None)[source]

Remove all elements not reachable from the sessions root.

Only consider given relationship and its subclasses.

Parameters

rel (Relationship, optional) – Only consider this relationship to calculate reachability.. Defaults to None.

class osp.core.session.core_session.CoreSession[source]

Bases: osp.core.session.session.Session, osp.core.session.sparql_backend.SPARQLBackend

Core default session for all objects.

class CoreSessionSparqlBindingSet(row, session)[source]

Bases: osp.core.session.sparql_backend.SparqlBindingSet

A row in the result. Mapping from variable to value.

class CoreSessionSparqlResult(query_result, session)[source]

Bases: osp.core.session.sparql_backend.SparqlResult

The result of a SPARQL query on the core session.

close()[source]

Close the connection.

class osp.core.session.wrapper_session.WrapperSession(engine)[source]

Bases: osp.core.session.session.Session

Common class for all wrapper sessions.

Sets the engine and creates the sets with the changed elements

static compute_auth(username, password, handshake)[source]

Will be called on the client, after the handshake.

This method should produce an object that is able to authenticate the user. The __init__() method of the session should have a keyword “auth”, that will have the output of this function as a value. –> The user can be authenticated on __init__()

Parameters
  • username (str) – The username as encoded in the URI.

  • password (str) – The password as encoded in the URI.

  • handshake (Any) – The result of the hanshake method.

Returns

Any JSON serializable object that is able to authenticate the user.

Return type

Any

expire(*cuds_or_uids)[source]

Let cuds_objects expire.

Expired objects will be reloaded lazily when attributed or relationships are accessed.

Parameters
  • *cuds_or_uids (Union[Cuds, UUID, URIRef]) – The cuds_object

  • uids to expire. (or) –

Returns

The set of uids that became expired

Return type

Set[UUID]

expire_all()[source]

Let all cuds_objects of the session expire.

Expired objects will be reloaded lazily when attributed or relationships are accessed.

Returns

The set of uids that became expired

Return type

Set[UUID]

static handshake(username, connection_id)[source]

Will be called on the server, before anything else.

Result of this method will be fed into compute_auth() below, that will be executed by the client.

Parameters
  • username (str) – The username of the user, as encoded in the URL.

  • connection_id (UUID) – A UUID for the connection.

Returns

Any JSON serializable object that should be fed into

compute_auth().

Return type

Any

log_buffer_status(context)[source]

Log the current status of the buffers.

Parameters

context (BufferContext) – whether to print user or engine buffers

refresh(*cuds_or_uids)[source]

Refresh cuds_objects.

Load possibly updated data of cuds_object from the backend.

Parameters

*cuds_or_uids (Union[Cuds, UUID]) – The cuds_object or uids to refresh.

class osp.core.session.sim_wrapper_session.SimWrapperSession(engine, **kwargs)[source]

Bases: osp.core.session.wrapper_session.WrapperSession

Abstract class used for simulation sessions.

Contains methods necessary for all simulation sessions.

class osp.core.session.db.db_wrapper_session.DbWrapperSession(engine)[source]

Bases: osp.core.session.wrapper_session.WrapperSession

Abstract class for a DB Wrapper Session.

abstract close()[source]

Close the connection to the database.

static compute_auth(username, password, handshake)[source]

Will be called on the client, after the handshake.

This method should produce an object that is able to authenticate the user. The __init__() method of the session should have a keyword “auth”, that will have the output of this function as a value. –> The user can be authenticated on __init__()

Parameters
  • username (str) – The username as encoded in the URI.

  • password (str) – The password as encoded in the URI.

  • handshake (Any) – The result of the hanshake method.

Returns

Any JSON serializable object that is able to authenticate the user.

Return type

Any

class osp.core.session.db.sql_wrapper_session.SqlWrapperSession(engine)[source]

Bases: osp.core.session.db.triplestore_wrapper_session.TripleStoreWrapperSession

Abstract class for an SQL DB Wrapper Session.

check_schema()

Raise an error if sql session has data in not-supported.

Parameters

() (sql_session) – [description]

Raises

RuntimeError – [description]

Registry

class osp.core.session.registry.Registry[source]

Bases: dict

A dictionary that contains all local CUDS objects.

filter(criterion)[source]

Filter the registry.

Return a dictionary that is a subset of the registry. It contains only cuds objects that satisfy the given criterion.

Parameters

criterion (Callable[Cuds, bool]) – A function that decides whether a cuds object should be returned. If the function returns True on a cuds object it means the cuds object satisfies the criterion.

Returns

dict contains the cuds objects

satisfying the criterion.

Return type

Dict[Union[UUID, URIRef], Cuds]

filter_by_attribute(attribute, value)[source]

Filter by attribute and value.

Parameters
  • attribute (str) – The attribute to look for.

  • value (Any) – The corresponding value to look for.

Returns

A subset of the registry,

containing cuds objects with given attribute and value.

Return type

Dict[Union[UUID, URIRef], Cuds]

filter_by_oclass(oclass)[source]

Filter the registry by ontology class.

Parameters

oclass (OntologyClass) – The oclass used for filtering.

Returns

A subset of the registry,

containing cuds objects with given ontology class.

Return type

Dict[Union[UUID, URIRef], Cuds]

filter_by_relationships(relationship, consider_subrelationships=False)[source]

Filter the registry by relationships.

Return cuds objects containing the given relationship.

Parameters
  • relationship (OntologyRelationship) – The relationship to filter by.

  • consider_subrelationships (bool, optional) – Whether to return CUDS objects containing subrelationships of the given relationship. Defaults to False.

Returns

A subset of the registry,

containing cuds objects with given relationship.

Return type

Dict[Union[UUID, URIRef], Cuds]

get(uid)[source]

Return the object corresponding to a given uid.

Parameters

uid (Union[UUID, URIRef]) – The uid of the desired object.

Raises

ValueError – Unsupported key provided (not a uid object).

Returns

Cuds object with the uid.

Return type

Cuds

get_subtree(root, rel=None, skip=None)[source]

Get all the elements in the subtree rooted at given root.

Only use the given relationship for traversal.

Parameters
  • root (Union[UUID, URIRef, Cuds]) – The root of the subtree.

  • rel (Relationship, optional) – The relationship used for traversal. Defaults to None. Defaults to None.

  • skip (Set[Cuds], optional) – The elements to skip. Defaults to None. Defaults to None.

Returns

The set of elements in the subtree rooted in the given

uid.

Return type

Set[Cuds]

prune(*roots, rel=None)[source]

Remove all elements in the registry that are not reachable.

Parameters

rel (Relationship, optional) – Only consider this relationship. Defaults to None.

Returns

The set of removed elements.

Return type

List[Cuds]

put(cuds_object)[source]

Add an object to the registry.

Parameters

cuds_object (Cuds) – The cuds_object to put in the registry.

Raises

ValueError – Unsupported object provided (not a Cuds object).

reset()[source]

Delete the contents of the registry.

Utilities

class osp.core.utils.Cuds2dot(root)[source]

Utility for creating a dot and png representation of CUDS objects.

render(filename=None, **kwargs)[source]

Create the graph and save it to a dot and png file.

static shorten_uid(uid)[source]

Shortens the string of a given uid.

Parameters

uid (UUID) – uuid to shorten.

Returns

8 first and 3 last characters separated by ‘…’.

Return type

str

osp.core.utils.branch(cuds_object, *args, rel=None)[source]

Like Cuds.add(), but returns the element you add to.

This makes it easier to create large CUDS structures.

Parameters
  • cuds_object (Cuds) – the object to add to.

  • args (Cuds) – object(s) to add

  • rel (OntologyRelationship) – class of the relationship between the objects.

Raises

ValueError – adding an element already there.

Returns

The first argument.

Return type

Cuds

osp.core.utils.change_oclass(cuds_object, new_oclass, kwargs, _force=False)[source]

Change the oclass of a cuds object.

Only allowed if cuds object does not have any neighbors.

Parameters
  • cuds_object (Cuds) – The cuds object to change the oclass of

  • new_oclass (OntologyClass) – The new oclass of the cuds object

  • kwargs (Dict[str, Any]) – The keyword arguments used to instantiate cuds object of the new oclass.

Returns

The cuds object with the changed oclass

Return type

Cuds

osp.core.utils.check_arguments(types, *args)[source]

Check that the arguments provided are of the certain type(s).

Parameters
  • types (Union[Type, Tuple[Type]]) – tuple with all the allowed types

  • args (Any) – instances to check

Raises

TypeError – if the arguments are not of the correct type

osp.core.utils.clone_cuds_object(cuds_object)[source]

Avoid that the session gets copied.

Returns

A copy of self with the same session.

Return type

Cuds

osp.core.utils.create_from_cuds_object(cuds_object, session)[source]

Create a copy of the given cuds_object in a different session.

WARNING: Will not recursively copy children.

Parameters
  • cuds_object (Cuds) – The cuds object to copy

  • session (Session) – The session of the new Cuds object

Returns

A copy of self with the given session.

Return type

Cuds

osp.core.utils.create_from_triples(triples, neighbor_triples, session, fix_neighbors=True)[source]

Create a CUDS object from triples.

Parameters
  • triples (List[Tuple]) – The list of triples of the CUDS object to create.

  • neighbor_triples (List[Tuple]) – A list of important triples of neighbors, most importantly their types.

  • session (Session) – The session to create the CUDS object in.

  • fix_neighbors (bool) – Whether to remove the link from the old neighbors to this cuds object, defaults to True.

osp.core.utils.create_recycle(oclass, kwargs, session, uid, fix_neighbors=True, _force=False)[source]

Instantiate a cuds_object with a given session.

If cuds_object with same uid is already in the session, this object will be reused.

Parameters
  • oclass (Cuds) – The OntologyClass of cuds_object to instantiate

  • kwargs (Dict[str, Any]) – The kwargs of the cuds_object

  • session (Session) – The session of the new Cuds object

  • uid (Union[UUID, URIRef) – The uid of the new Cuds object

  • fix_neighbors (bool) – Whether to remove the link from the old neighbors to this cuds object, defaults to True

  • _force (bool) – Skip sanity checks.

Returns

The created cuds object.

Return type

Cuds

osp.core.utils.delete_cuds_object_recursively(cuds_object, rel=<OntologyRelationship cuba.activeRelationship>, max_depth=inf)[source]

Delete a cuds object and all the object inside of the container of it.

Parameters
  • cuds_object (Cuds) – The CUDS object to recursively delete.

  • rel (OntologyRelationship, optional) – The relationship used for traversal. Defaults to cuba.activeRelationship.

  • max_depth (int, optional) – The maximum depth of the recursion. Defaults to float(“inf”). Defaults to float(“inf”).

osp.core.utils.export_cuds(cuds_or_session: Optional = None, file: Optional[Union[str, TextIO]] = None, format: str = 'text/turtle', rel: osp.core.ontology.relationship.OntologyRelationship = <OntologyRelationship cuba.activeRelationship>, max_depth: float = inf)Optional[str][source]

Exports CUDS in a variety of formats (see the format argument).

Parameters
  • cuds_or_session (Union[Cuds, Session], optional) – the (Cuds) CUDS object to export, or (Session) a session to serialize all of its CUDS objects. If no item is specified, then the current session is exported.

  • file (str, optional) – either, (str) a path, to save the CUDS objects 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.

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

  • rel (OntologyRelationship) – the ontology relationship to use as containment relationship when exporting CUDS.

  • max_depth (float) – maximum depth to search for children CUDS.

osp.core.utils.get_neighbor_diff(cuds1, cuds2, mode='all')[source]

Get the ids of neighbors of cuds1 which are no neighbors in cuds2.

Furthermore get the relationship the neighbors are connected with. Optionally filter the considered relationships.

Args;

cuds1 (Cuds): A Cuds object. cuds2 (Cuds): A Cuds object. mode (str): one of “all”, “active”, “non-active”, whether to consider

only.

active or non-active relationships.

Returns

List of Tuples that

contain the found uids and relationships.

Return type

List[Tuple[Union[UUID, URIRef], Relationship]]

osp.core.utils.get_relationships_between(subj, obj)[source]

Get the set of relationships between two cuds objects.

Parameters
  • subj (Cuds) – The subject

  • obj (Cuds) – The object

Returns

The set of relationships between subject

and object.

Return type

Set[OntologyRelationship]

osp.core.utils.import_cuds(path_or_filelike: Union[str, TextIO, dict, List[dict]], session: Optional = None, format: str = None)[source]

Imports CUDS in various formats (see the format argument).

Parameters
  • path_or_filelike (Union[str, TextIO], optional) –

    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 (Session) – the session in which the imported data will be stored.

  • format (str, optional) – the format of the content to import. The supported formats are json and 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.

Returns (List[Cuds]): a list of cuds objects.

osp.core.utils.post(url, cuds_object, rel=<OntologyRelationship cuba.activeRelationship>, max_depth=inf)[source]

Will send the given CUDS object to the given URL.

Will also send the CUDS object in the container recursively.

Parameters
  • url (string) – The URL to send the CUDS object to

  • cuds_object (Cuds) – The CUDS to send

  • max_depth (int, optional) – The maximum depth to send CUDS objects recursively. Defaults to float(“inf”).

Returns

Server response

osp.core.utils.pretty_print(cuds_object, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print the given cuds_object in a human readable way.

The uuid, the type, the ancestors and the description and the contents is printed.

Parameters
  • cuds_object (Cuds) – container to be printed.

  • file (TextIOWrapper) – The file to print to.

osp.core.utils.remove_cuds_object(cuds_object)[source]

Remove a cuds_object from the data structure.

Removes the relationships to all neighbors. To delete it from the registry you must call the sessions prune method afterwards.

Parameters

cuds_object (Cuds) – The cuds_object to remove.

osp.core.utils.sparql(query_string: str, session: Optional = None)[source]

Performs a SPARQL query on a session (if supported by the session).

Parameters
  • query_string (str) – A string with the SPARQL query to perform.

  • session (Session, optional) – The session on which the SPARQL query will be performed. If no session is specified, then the current default session is used. This means that, when no session is specified, inside session with statements, the query will be performed on the session associated with such statement, while outside, it will be performed on the OSP-core default session, the core session.

Returns

A SparqlResult object, which can be iterated to obtain

the output rows. Then for each row, the value for each query variable can be retrieved as follows: row[‘variable’].

Return type

SparqlResult

Raises

NotImplementedError – when the session does not support SPARQL queries.