API reference

KGObject

class fairgraph.KGObject(id: str | None = None, data: Dict[str, Any] | None = None, space: str | None = None, scope: str | None = None, **properties)[source]

Bases: ContainsMetadata, RepresentsSingleObject, SupportsQuerying

Base class for Knowledge Graph objects.

Should not be instantiated directly, intended to be subclassed.

classmethod from_kg_instance(data: JSONdict, client: KGClient, scope: str | None = None)[source]

Create an instance of the class from a JSON-LD document.

classmethod from_uri(uri: str, client: KGClient, use_cache: bool = True, scope: str = 'released', follow_links: Dict[str, Any] | None = None)[source]

Retrieve an instance from the Knowledge Graph based on its URI.

Parameters:
  • uri (str) – long-form identifier for the KG instance (a full URI)

  • client – a KGClient

  • scope (str, optional) – The scope of the lookup. Valid values are “released”, “in progress”, or “any”. Defaults to “released”.

  • use_cache (bool) – Whether to use cached data if they exist. Defaults to True.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

classmethod from_uuid(uuid: str, client: KGClient, use_cache: bool = True, scope: str = 'released', follow_links: Dict[str, Any] | None = None)[source]

Retrieve an instance from the Knowledge Graph based on its UUID.

Parameters:
  • uuid (str) – short-form identifier for the KG instance (a UUID).

  • client – a KGClient

  • scope (str, optional) – The scope of the lookup. Valid values are “released”, “in progress”, or “any”. Defaults to “released”.

  • use_cache (bool) – Whether to use cached data if they exist. Defaults to True.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

classmethod from_id(id: str, client: KGClient, use_cache: bool = True, scope: str = 'released', follow_links: Dict[str, Any] | None = None)[source]

Retrieve an instance from the Knowledge Graph based on either its URI or UUID.

Parameters:
  • id (str) – short-form (UUID) or long-form (URI) identifier for the KG instance.

  • client – a KGClient

  • scope (str, optional) – The scope of the lookup. Valid values are “released”, “in progress”, or “any”. Defaults to “released”.

  • use_cache (bool) – Whether to use cached data if they exist. Defaults to True.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

classmethod from_alias(alias: str, client: KGClient, space: str | None = None, scope: str = 'released', follow_links: Dict[str, Any] | None = None)[source]

Retrieve an instance from the Knowledge Graph based on its alias/short name.

Note that not all metadata classes have an alias.

Parameters:
  • alias (str) – a short name used to identify a KG instance.

  • client – a KGClient

  • space (str, optional) – the KG space to look in. Default is to look in all available spaces.

  • scope (str, optional) – The scope of the lookup. Valid values are “released”, “in progress”, or “any”. Defaults to “released”.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

classmethod uri_from_uuid(uuid: str, client: KGClient) str[source]

Convert an instances short-form identifier (a UUID) into the long-form (a URI)

classmethod list(client: KGClient, size: int = 100, from_index: int = 0, api: str = 'auto', scope: str = 'released', space: str | None = None, follow_links: Dict[str, Any] | None = None, **filters) List[KGObject][source]

List all objects of this type in the Knowledge Graph

Parameters:
  • client – KGClient object that handles the communication with the KG.

  • size (int, optional) – The maximum number of instances to return. Default is 100.

  • from_index (int, optional) – The index of the first instance to return. Default is 0.

  • api (str) – The KG API to use for the query. Can be ‘query’, ‘core’, or ‘auto’. Default is ‘auto’.

  • scope (str, optional) – The scope to use for the query. Can be ‘released’, ‘in progress’, or ‘all’. Default is ‘released’.

  • space (str, optional) – The KG space to be queried. If not specified, results from all accessible spaces will be included.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

  • filters – Optional keyword arguments representing filters to apply to the query.

Returns:

A list of instances of this class representing the objects returned by the KG query.

Raises:
  • ValueError – If invalid arguments are passed to the method.

  • NotImplementedError – If ‘follow_links’ is used with api=’core’.

Example

>>> from fairgraph import KGClient
>>> import fairgraph.openminds.controlled_terms as terms
>>> interneuron_types = terms.CellType.list(client, name="interneuron")
>>> for ct in interneuron_types[:4]:
...     print(f"{ct.name:<30} {ct.definition}")
cerebellar interneuron         None
cholinergic interneuron        An inhibitory interneuron which mainly uses the neurotrasmitter acetylcholine (ACh).
cortical interneuron           None
fast spiking interneuron       A parvalbumin positive GABAergic interneuron with a high-frequency firing pattern.
classmethod count(client: KGClient, api: str = 'auto', scope: str = 'released', space: str | None = None, **filters) int[source]

Count the number of objects of a given type and (optionally) matching a given set of filters.

Parameters:
  • client – KGClient object that handles the communication with the KG.

  • api (str) – The KG API to use for the query. Can be ‘query’, ‘core’, or ‘auto’. Default is ‘auto’.

  • scope (str, optional) – The scope to use for the query. Can be ‘released’, ‘in progress’, or ‘all’. Default is ‘released’.

  • space (str, optional) – The KG space to be queried. If not specified, results from all accessible spaces will be counted.

  • filters – Optional keyword arguments representing filters to apply to the query.

Returns:

The number of instances of this class in the given space that would match the given filters, or the total number of instances if no filters are provided.

Raises:
  • ValueError – If invalid arguments are passed to the method.

  • NotImplementedError – If ‘follow_links’ is used with api=’core’.

Example

>>> from fairgraph import KGClient
>>> import fairgraph.openminds.controlled_terms as terms
>>> terms.CellType.count(client, name="interneuron")
8
diff(other)[source]

Return a dictionary containing the differences between two metadata objects.

exists(client: KGClient) bool[source]

Check if this object already exists in the KnowledgeGraph

modified_data() Dict[str, Any][source]

Return a dict containing the properties that have been modified locally from the values originally obtained from the Knowledge Graph.

save(client: KGClient, space: str | None = None, recursive: bool = True, activity_log: ActivityLog | None = None, replace: bool = False, ignore_auth_errors: bool = False)[source]

Store the current object in the Knowledge Graph, either updating an existing instance or creating a new one as appropriate.

Parameters:
  • client – KGClient object that handles the communication with the KG.

  • space (str, optional) – The KG space to save the object in. If not provided, a default space is used depending on the object type.

  • recursive (bool, optional) – Whether to recursively save any children of this object. Defaults to True.

  • activity_log (ActivityLog, optional) – An ActivityLog instance to log the operations performed during the save operation. This is particularly helpful with recursive=True.

  • replace (bool, optional) – Whether to completely replace an existing KG instance with this one, or just update the existing object with any modified properties. Defaults to False.

  • ignore_auth_errors (bool, optional) – Whether to continue silently when encountering authentication errors. Defaults to False.

Raises:

- An AuthorizationError if the current user is not authorized to perform the requested operation.

delete(client: KGClient, ignore_not_found: bool = True)[source]

Delete the current metadata object from the KG.

If ignore_not_found is False, an exception will be raised if the object does not exist. Otherwise, the method will finish silently.

classmethod by_name(name: str, client: KGClient, match: str = 'equals', all: bool = False, space: str | None = None, scope: str = 'released', follow_links: Dict[str, Any] | None = None) KGObject | List[KGObject] | None[source]

Retrieve an instance from the Knowledge Graph based on its name.

Note that not all metadata classes have a name property.

Parameters:
  • name (str) – a string to search for in the name property.

  • client – a KGClient

  • match (str, optional) – either “equals” (exact match - default) or “contains”.

  • all (bool, optional) – Whether to return all objects that match the name, or only the first. Defaults to False.

  • space (str, optional) – the KG space to search in. Default is to search in all available spaces.

  • scope (str, optional) – The scope of the search. Valid values are “released”, “in progress”, or “any”. Defaults to “released”.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

show(max_width: int | None = None, include_empty_properties=False)[source]

Print a table showing the metadata contained in this object.

classmethod generate_query(client: KGClient, space: str | None, filters: Dict[str, Any] | None = None, follow_links: Dict[str, Any] | None = None, label: str | None = None) Dict[str, Any] | None[source]

Generate a KG query definition as a JSON-LD document.

Parameters:
  • client – KGClient object that handles the communication with the KG.

  • space (str, optional) – if provided, restrict the query to metadata stored in the given KG space.

  • filters (dict) – A dictonary defining search parameters for the query.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

  • label (str, optional) – a label for the query

Returns:

A JSON-LD document containing the KG query definition.

children(client: KGClient, follow_links: Dict[str, Any] | None = None) List[RepresentsSingleObject][source]

Return a list of child objects.

export(path: str, single_file: bool = False)[source]

Export metadata as files in JSON-LD format.

If any objects do not have IDs, these will be generated.

If single_file is False, then path must be the path to a directory, and each object will be exported as a file named for the object ID.

If single_file is True, then path should be the path to a file with extension “.jsonld”. This file will contain metadata for all objects.

classmethod from_jsonld(data: JSONdict, client: KGClient, scope: str | None = None)

Create an instance of the class from a JSON-LD document.

classmethod generate_query_filter_properties(filters: Dict[str, Any] | None = None)
Parameters:

filters (dict, optional) – A dict containing search parameters for the query.

classmethod generate_query_properties(follow_links: Dict[str, Any] | None = None)

Generate a list of QueryProperty instances for this class for use in constructing a KG query definition.

Parameters:

follow_links (dict) – The links in the graph to follow when constructing the query. Defaults to None.

is_released(client: KGClient, with_children: bool = False) bool

Release status of the node

classmethod normalize_filter(filter_dict: Dict[str, Any]) Dict[str, Any]

Normalize a dict containing filter key:value pairs so that it can be used in a call to the KG query API.

Example

>>> import fairgraph.openminds.core as omcore
>>> person = omcore.Person.from_uuid("045f846f-f010-4db8-97b9-b95b20970bf2", kg_client)
>>> filter_dict = {"custodians": person, "name": "Virtual"}
>>> omcore.Dataset.normalize_filter(filter_dict)
{'name': 'Virtual',
 'custodians': 'https://kg.ebrains.eu/api/instances/045f846f-f010-4db8-97b9-b95b20970bf2'}
release(client: KGClient, with_children: bool = False)

Release this node (make it available in public search).

resolve(client: KGClient, scope: str | None = None, use_cache: bool = True, follow_links: Dict[str, Any] | None = None)

Resolve properties that are represented by KGProxy objects.

Parameters:
  • client – KGClient object that handles the communication with the KG.

  • scope (str) – The scope of instances to include in the response. Valid values are ‘released’, ‘in progress’, ‘any’.

  • use_cache (bool) – whether to use cached data if they exist. Defaults to True.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

Note: a real (non-proxy) object resolves to itself.

classmethod set_error_handling(value: ErrorHandling | None, property_names: str | List[str] | None = None)

Control validation for this class.

Parameters:
  • value (str) – action to follow when there is a validation failure. (e.g. if a required property is not provided). Possible values: “error”, “warning”, “log”, None

  • property_names (str or list of str, optional) – If not provided, the error handling mode will be applied to all properties. If a property name or list of names is given, the mode will be applied only to those properties.

to_jsonld(normalized: bool = True, follow_links: bool = False, include_empty_properties: bool = False, include_reverse_properties: bool = False)

Return a JSON-LD representation of this metadata object

Parameters:
  • normalized (bool) – Whether to expand all URIs. Defaults to True.

  • follow_links (bool, optional) – Whether to represent linked objects just by their “@id” or to include their full metadata. Defaults to False.

  • include_empty_properties (bool, optional) – Whether to include empty properties (with value “null”). Defaults to False.

unrelease(client: KGClient, with_children: bool = False)

Un-release this node (remove it from public search).

EmbeddedMetadata

class fairgraph.EmbeddedMetadata(data: Dict[str, Any] | None = None, **properties)[source]

Bases: ContainsMetadata, Resolvable

Base class for metadata structures that are embedded in Knowledge Graph objects.

Args:

data (dict, optional): a JSON-LD document containing the KG representation of the metadata. properties: the metadata properties (property names and values)

property space: str | None

The KG space the metadata is stored in.

property default_space: str | None

The KG space new metadata will be stored in if no space is specified.

classmethod from_kg_instance(data: JSONdict, client: KGClient) None | EmbeddedMetadata[source]

Create an instance of the class from a JSON-LD document.

save(client: KGClient, space: str | None = None, recursive: bool = True, activity_log: ActivityLog | None = None, replace: bool = False)[source]

Save to the KG any sub-components of the metadata object that are KGObjects.

classmethod from_jsonld(data: JSONdict, client: KGClient, scope: str | None = None)

Create an instance of the class from a JSON-LD document.

classmethod generate_query_filter_properties(filters: Dict[str, Any] | None = None)
Parameters:

filters (dict, optional) – A dict containing search parameters for the query.

classmethod generate_query_properties(follow_links: Dict[str, Any] | None = None)

Generate a list of QueryProperty instances for this class for use in constructing a KG query definition.

Parameters:

follow_links (dict) – The links in the graph to follow when constructing the query. Defaults to None.

classmethod normalize_filter(filter_dict: Dict[str, Any]) Dict[str, Any]

Normalize a dict containing filter key:value pairs so that it can be used in a call to the KG query API.

Example

>>> import fairgraph.openminds.core as omcore
>>> person = omcore.Person.from_uuid("045f846f-f010-4db8-97b9-b95b20970bf2", kg_client)
>>> filter_dict = {"custodians": person, "name": "Virtual"}
>>> omcore.Dataset.normalize_filter(filter_dict)
{'name': 'Virtual',
 'custodians': 'https://kg.ebrains.eu/api/instances/045f846f-f010-4db8-97b9-b95b20970bf2'}
resolve(client: KGClient, scope: str | None = None, use_cache: bool = True, follow_links: Dict[str, Any] | None = None)

Resolve properties that are represented by KGProxy objects.

Parameters:
  • client – KGClient object that handles the communication with the KG.

  • scope (str) – The scope of instances to include in the response. Valid values are ‘released’, ‘in progress’, ‘any’.

  • use_cache (bool) – whether to use cached data if they exist. Defaults to True.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

Note: a real (non-proxy) object resolves to itself.

classmethod set_error_handling(value: ErrorHandling | None, property_names: str | List[str] | None = None)

Control validation for this class.

Parameters:
  • value (str) – action to follow when there is a validation failure. (e.g. if a required property is not provided). Possible values: “error”, “warning”, “log”, None

  • property_names (str or list of str, optional) – If not provided, the error handling mode will be applied to all properties. If a property name or list of names is given, the mode will be applied only to those properties.

to_jsonld(normalized: bool = True, follow_links: bool = False, include_empty_properties: bool = False, include_reverse_properties: bool = False)

Return a JSON-LD representation of this metadata object

Parameters:
  • normalized (bool) – Whether to expand all URIs. Defaults to True.

  • follow_links (bool, optional) – Whether to represent linked objects just by their “@id” or to include their full metadata. Defaults to False.

  • include_empty_properties (bool, optional) – Whether to include empty properties (with value “null”). Defaults to False.

KGProxy

class fairgraph.KGProxy(cls: str | KGObject, uri: str, preferred_scope: str = 'released')[source]

Bases: RepresentsSingleObject

Representation of an KGObject whose type and identifier are known but whose other metadata have not been retrieved from the KG.

Parameters:
  • cls (str, KGObject) – the type of the associated KG object, defined by a KGObject subclass or by the name of the subclass.

  • uri (URI) – The global identifier of the KG object.

  • preferred_scope (str, optional) – The preferred scope used to resolve the proxy. Valid values are “released”, “in progress”, or “any”.

Example

>>> import fairgraph.openminds
>>> proxy = KGProxy("openminds.core.Person", "https://kg.ebrains.eu/api/instances/bd554312-9829-4148-8803-cb873d0b32f9")
>>> person = proxy.resolve(kg_client)
>>> type(person)
<class 'fairgraph.openminds.core.actors.person.Person'>
>>> person.given_name
Andrew P.
property type: List[str]

Provide the global identifiers of the object type (as a list of URIs).

property classes: Tuple[KGObject] | List[KGObject]

Provide the metadata class associated with this object in a list.

This is provided for consistency with the KGQuery interface.

resolve(client: KGClient, scope: str | None = None, use_cache: bool = True, follow_links: Dict[str, Any] | None = None)[source]

Retrieve the full metadata for the KGObject represented by this proxy.

Parameters:
  • client – a KGClient

  • scope (str, optional) – The scope of the lookup. Valid values are “released”, “in progress”, or “any”. If not provided, the “preferred_scope” provided when creating the proxy object will be used.

  • use_cache (bool) – Whether to use cached data if they exist. Defaults to True.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

Returns:

a KGObject instance, of the appropriate subclass.

is_released(client: KGClient, with_children: bool = False) bool

Release status of the node

release(client: KGClient, with_children: bool = False)

Release this node (make it available in public search).

unrelease(client: KGClient, with_children: bool = False)

Un-release this node (remove it from public search).

delete(client: KGClient, ignore_not_found: bool = True)[source]

Delete the instance which this proxy represents

KGQuery

class fairgraph.KGQuery(classes: str | KGObject | List[str | KGObject], filter: Dict[str, str], preferred_scope: str = 'released')[source]

Bases: Resolvable, SupportsQuerying

Representation of one or more KGObjects identified by a range of possible types and by some of their metadata, but whose specific identifier(s) is/are not known.

It is possible that no KGObjects match the types/metadata.

Parameters:
  • classes (list of KGObject subclasses) – a list of types to query.

  • filter (dict) – key:value pairs that should be matched. All pairs must match.

  • preferred_scope (str) – The preferred scope used to resolve the query. Valid values are “released”, “in progress”, or “any”.

Example

>>> import fairgraph.openminds.core as omcore
>>> from fairgraph.utility import as_list
>>> query = KGQuery([omcore.Person], {"family_name": "Amunts"})
>>> people = as_list(query.resolve(kg_client))
>>> len(people)
1
>>> people[0].family_name
Amunts
resolve(client: KGClient, size: int = 10000, from_index: int = 0, space: str | None = None, scope: str | None = None, use_cache: bool = True, follow_links: Dict[str, Any] | None = None)[source]

Retrieve the full metadata for the KGObject(s) represented by this query object.

Parameters:
  • client – a KGClient

  • from_index – The index of the first result to include in the response.

  • size – The maximum number of results to include in the response.

  • space – If specified, queries only in the given space.

  • scope (str, optional) – The scope of the query. Valid values are “released”, “in progress”, or “any”. If not provided, the “preferred_scope” provided when creating the proxy object will be used.

  • use_cache (bool) – Whether to use cached data if they exist. Defaults to True.

  • follow_links (dict) – The links in the graph to follow. Defaults to None.

Returns:

a KGObject instance, of the appropriate subclass.

count(client: KGClient, space: str | None = None, scope: str | None = None)[source]

Return the number of objects that would be returned by resolving this query.

KGClient

class fairgraph.KGClient(token: str | None = None, host: str = 'core.kg-ppd.ebrains.eu', client_id: str | None = None, client_secret: str | None = None)[source]

Bases: object

A client for accessing the EBRAINS Knowledge Graph (KG) API.

It can be used to retrieve, add, update, and delete KG nodes.

cache

A dictionary used for caching JSON-LD documents.

Type:

dict

accepted_terms_of_use

A boolean indicating whether the user has accepted the terms of use.

Type:

bool

Parameters:
  • token (str, optional) – An EBRAINS authentication token for accessing the KG API.

  • host (str, optional) – The hostname of the KG API. Use “core.kg-ppd.ebrains.eu” for testing and “core.kg.ebrains.eu” to work with the production KG.

  • client_id (str, optional) – For use together with client_secret in place of the token if you have a service account.

  • client_secret (str, optional) – The client secret to use for authentication. Required if client_id is provided.

Raises:
  • ImportError – If the kg_core package is not installed.

  • AuthenticationError – If neither a token nor client ID/secret are provided.

query(query: Dict[str, Any], filter: Dict[str, str] | None = None, instance_id: str | None = None, from_index: int = 0, size: int = 100, scope: str = 'released', id_key: str = '@id', use_stored_query: bool = False) ResultPage[JsonLdDocument][source]

Execute a Knowledge Graph (KG) query with the given filters and query definition.

Parameters:
  • query (Dict[str, Any]) – A dictionary containing the query definition in JSON-LD.

  • filter (Dict[str, str]) – A dictionary of filters to apply to the query. Each key represents the prop name to filter on, and the value represents the value(s) to filter on.

  • instance_id (Optional[URI]) – The URI of a specific KG instance to retrieve.

  • from_index (int) – The index of the first result to return (0-based).

  • size (int) – The maximum number of results to return.

  • scope (str) – The scope of the query. Valid values are “released”, “in progress”, or “any”. Default is “released”.

  • id_key (str) – The key that identifies the ID of a JSON-LD document. Default is “@id”.

  • use_stored_query (bool) – Whether to use a stored query with the given query_id instead of a dynamic query. Default is False.

Returns:

A ResultPage object containing a list of JSON-LD instances that satisfy the query, along with metadata about the query results such as total number of instances, and pagination information.

list(target_type: str, space: str | None = None, from_index: int = 0, size: int = 100, scope: str = 'released') ResultPage[JsonLdDocument][source]

List KG instances of a given type.

Parameters:
  • target_type – The URI if the instance type to list.

  • space – If specified, restricts the search to the given space.

  • from_index – The index of the first result to include in the response.

  • size – The maximum number of results to include in the response.

  • scope – The scope of instances to include in the response. Valid values are ‘released’, ‘in progress’, ‘any’. If ‘any’ is specified, all accessible instances are included in the response, but this may be slow where there are large numbers of instances.

Returns:

A ResultPage object containing the list of JSON-LD instances, along with metadata about the query results such as total number of instances, and pagination information.

instance_from_full_uri(uri: str, use_cache: bool = True, scope: str = 'released', require_full_data: bool = True) JsonLdDocument[source]

Return a specific KG instance identified by its URI.

Parameters:
  • uri – The global identifier of the instance

  • use_cache – whether to use cached data if they exist. Defaults to True.

  • scope – The scope of instances to include in the response. Valid values are ‘released’, ‘in progress’, ‘any’.

  • require_full_data – Whether to only return instances for which the user has full read access.

create_new_instance(data: JsonLdDocument, space: str, instance_id: str | None = None) JsonLdDocument[source]

Create a new KG instance using the data provided.

Parameters:
  • data (dict) – a JSON-LD document that should be added to the KG as a new instance.

  • space (str) – the space in which the instance should be stored.

  • instance_id (UUID, optional) – a UUID that should be used as the basis for the instance’s persistent identifier. If not specified, the KG will generate an ID.

update_instance(instance_id: str, data: JsonLdDocument) JsonLdDocument[source]

Update an existing KG instance using the data provided.

Parameters:
  • instance_id (UUID) – the instance’s persistent identifier.

  • data (dict) – a JSON-LD document that modifies some or all of the data of the existing instance.

replace_instance(instance_id: str, data: JsonLdDocument) JsonLdDocument[source]

Replace an existing KG instance using the data provided.

Parameters:
  • instance_id (UUID) – the instance’s persistent identifier.

  • data (dict) – a JSON-LD document that will replace the existing instance.

delete_instance(instance_id: str, ignore_not_found: bool = True)[source]

Delete a KG instance.

uri_from_uuid(uuid: str) str[source]

Return an instance’s URI given its UUID.

uuid_from_uri(uri: str) UUID[source]

Return an instance’s UUID given its URI.

store_query(query_label: str, query_definition: Dict[str, Any], space: str)[source]

Store a query definition in the KG.

Parameters:
  • query_label (str) – a label that can be used to identify and retrieve the query definition.

  • query_definition (dict) – a JSON-LD document defining a KG query.

  • space (str) – the space in which the query definition should be stored.

retrieve_query(query_label: str) Dict[str, Any][source]

Retrieve a stored query definition from the KG.

Parameters:

query_label (str) – the label of the query definition to be retrieved.

user_info() Dict[str, Any][source]

Returns information about the current user.

This information is that associated with the authorization token used.

configure_space(space_name: str | None = None, types: List[KGObject] | None = None) str[source]

Creates and configures a Knowledge Graph (KG) space with the specified name and types.

Parameters:
  • space_name (str, required (optional only if you run inside a collab)) – The name of the KG space to create and configure. If not provided, the method will try to obtain the collab ID from the environment variables and use it to generate a default space name in the format “collab-collab_id”. If you are not launching this from inside an EBRAINS collab, you should provide a space name.

  • types (list of Type, required) – An array containing the Type classes that should be included in this space.

Returns:

The name of the configured KG space.

Return type:

str

Example usage:

types = [Dataset, DatasetVersion, Software, SoftwareVersion] space_name = “collab-MyCollab” kg_client = KGClient() kg_client.configure_space(space_name, types)

move_to_space(uri: str, destination_space: str)[source]

Move a KG instance from one space to another.

This is not recursive, i.e. child instances much be moved individually.

is_released(uri: str, with_children: bool = False) bool[source]

Release status of a KG instance identified by its URI.

Parameters:
  • uri (URI) – persistent identifier of the instance.

  • with_children (bool) – whether to check if all the children of the instance have also been released.

Returns:

True if the instance and (optionally) all its children have been released. Otherwise False.

release(uri: str)[source]

Release the instance with the given uri

unrelease(uri: str)[source]

Unrelease the instance with the given uri

Queries

class fairgraph.queries.Query(node_type: str, label: str | None = None, space: str | None = None, properties: List[QueryProperty] | None = None)[source]

Bases: object

A Python representation of an EBRAINS Knowledge Graph query, which can be serialized to the JSON-LD used by the kg-core query API.

Parameters:
  • node_type (URI) – The URI of the node type to query.

  • label (str, optional) – A label for this query.

  • space (Optional[str], optional) – The KG space to query.

  • properties (Optional[List[QueryProperty]], optional) – A list of QueryProperty objects representing the properties to include in the results.

add_property()[source]

Adds a QueryProperty object to the list of properties to include.

serialize()[source]

Returns a JSON-LD representation of the query, suitable for sending to the KG.

Example

>>> q = Query(
...    node_type="https://openminds.ebrains.eu/core/ModelVersion",
...    label="fg-testing-modelversion",
...    space="model",
...    properties=[
...        QueryProperty("@type"),
...        QueryProperty(
...            "https://openminds.ebrains.eu/vocab/fullName",
...            name="vocab:fullName",
...            filter=Filter("CONTAINS", parameter="name"),
...            sorted=True,
...            required=True,
...        ),
...        QueryProperty(
...            "https://openminds.ebrains.eu/vocab/versionIdentifier",
...            name="vocab:versionIdentifier",
...            filter=Filter("EQUALS", parameter="version"),
...            required=True,
...        ),
...        QueryProperty(
...            "https://openminds.ebrains.eu/vocab/format",
...            name="vocab:format",
...            ensure_order=True,
...            properties=[
...                QueryProperty("@id", filter=Filter("EQUALS", parameter="format")),
...                QueryProperty("@type"),
...            ],
...        )
...     )
class fairgraph.queries.QueryProperty(path: str, name: str | None = None, filter: Filter | None = None, sorted: bool = False, required: bool = False, ensure_order: bool = False, properties: List[QueryProperty] | None = None, type_filter: str | None = None, reverse: bool = False, expect_single: bool = False)[source]

Bases: object

A property for a Knowledge Graph query.

Parameters:
  • path (URI) – The path of the property as a URI.

  • name (str, optional) – The name of the property to be used in the returned results.

  • filter (Filter, optional) – A filter based on the property.

  • sorted (bool, optional) – Whether to sort the results based on the property. Defaults to False.

  • required (bool, optional) – Whether the property is required. Defaults to False.

  • ensure_order (bool, optional) – Whether to ensure the ordering of results is maintained. Defaults to False.

  • properties (List[QueryProperty], optional) – A list of sub-properties.

  • type_filter (URI, optional) – Ensure that only objects that match the given type URI are returned.

  • reverse (bool, optional) – Whether the link defined by the path should be followed in the reverse direction. Defaults to False.

  • expect_single (bool, optional) – Whether to expect a single element in the result. Defaults to False.

add_property()[source]

Adds a sub-property to the QueryProperty object.

serialize()[source]

Returns a dictionary containing the serialized QueryProperty.

Example

>>> p = QueryProperty(
...    "https://openminds.ebrains.eu/vocab/fullName",
...    name="full_name",
...    filter=Filter("CONTAINS", parameter="name"),
...    sorted=True,
...    required=True
... )
class fairgraph.queries.Filter(operation: str, parameter: str | None = None, value: str | None = None)[source]

Bases: object

A filter for querying Knowledge Graph nodes.

Parameters:
  • operation (str) – The operation for the filter. Options are: (“CONTAINS”, “EQUALS”, “IS_EMPTY”, “STARTS_WITH”, “ENDS_WITH”, “REGEX”)

  • parameter (str, optional) – A parameter name for the filter.

  • value (str, optional) – The value to filter on.

serialize()[source]

Returns a dictionary containing the serialized filter.

Utility classes and functions

fairgraph.utility.as_list(obj: None | KGObject | dict | str | list | tuple) list[source]

Converts the input obj into a list.

Parameters:

obj – The input object to be converted to a list.

Returns:

A list - see Notes below.

Return type:

list

Raises:

TypeError – If the input obj cannot be converted to a list.

Notes

  • If obj is None, it returns an empty list.

  • If obj is a dict or a str, it returns a list containing obj.

  • If obj is a list or a tuple, it returns a list with the same elements as obj.

  • If obj is not any of the above, it tries to convert obj into a list. If it fails due to a TypeError, it raises a TypeError with an appropriate error message.

fairgraph.utility.expand_uri(uri_list: str | List[str], context: Dict[str, Any]) str | Tuple[str, ...][source]

Expands a URI or a list of URIs using a given context.

Parameters:
  • uri_list (Union[str, List[str]]) – A URI or a list of URIs to be expanded.

  • context (Dict[str, Any]) – A dictionary containing a mapping of prefixes to base URLs.

Returns:

An expanded URI or a tuple of expanded URIs.

Return type:

Union[str, Tuple[str, …]]

Raises:

ValueError – If a prefix in the URI is not found in the context.

Examples

>>> context = {'foaf': 'http://xmlns.com/foaf/0.1/'}
>>> uri_list = 'foaf:Person'
>>> expand_uri(uri_list, context)
'http://xmlns.com/foaf/0.1/Person'
fairgraph.utility.compact_uri(uri_list: str | List[str], context: Dict[str, Any], strict: bool = False) str | Tuple[str, ...][source]

Compacts a URI or a list of URIs using a given context.

Parameters:
  • uri_list (Union[str, List[str]]) – A URI or a list of URIs to be compacted.

  • context (Dict[str, Any]) – A dictionary containing a mapping of prefixes to base URLs.

  • strict (bool, optional) – Whether to raise an error if a URI cannot be compacted. Defaults to False.

Returns:

A compacted URI or a tuple of compacted URIs.

Return type:

Union[str, Tuple[str, …]]

Raises:

ValueError – If strict is True and a URI cannot be compacted.

Examples

>>> context = {'foaf': 'http://xmlns.com/foaf/0.1/'}
>>> uri_list = 'http://xmlns.com/foaf/0.1/Person'
>>> compact_uri(uri_list, context)
'foaf:Person'
fairgraph.utility.normalize_data(data: None | Dict[str, Any], context: Dict[str, Any]) None | Dict[str, Any][source]

Normalizes JSON-LD data using a given context.

Parameters:
  • data (Union[None, JSONdict]) – A JSON-LD data dict to be normalized.

  • context (Dict[str, Any]) – A dictionary containing a mapping of prefixes to base URLs.

Returns:

A normalized JSON-LD data dict.

Return type:

Union[None, JSONdict]

Examples

>>> context = {'foaf': 'http://xmlns.com/foaf/0.1/'}
>>> data = {
...     "foaf:name": "John Smith",
...     "foaf:age": 35,
...     "foaf:knows": {
...         "foaf:name": "Jane Doe",
...         "foaf:age": 25
...     }
... }
>>> normalize_data(data, context)
{
    "http://xmlns.com/foaf/0.1/name": "John Smith",
    "http://xmlns.com/foaf/0.1/age": 35,
    "http://xmlns.com/foaf/0.1/knows": {
        "http://xmlns.com/foaf/0.1/name": "Jane Doe",
        "http://xmlns.com/foaf/0.1/age": 25
    }
}
class fairgraph.utility.ActivityLog[source]

Bases: object

Represents a log of activities performed on Knowledge Graph objects.

entries

A list of LogEntry objects representing the activities performed.

Type:

List[LogEntry]

update(item: KGObject, delta: JSONdict | None, space: str | None, entry_type: str)[source]

Adds a new log entry to the activity log.

Parameters:
  • item (KGObject) – The object being logged.

  • delta (Optional[JSONdict]) – A dictionary containing the changes made to the object.

  • space (Optional[str]) – The Knowledge Graph space containing the object.

  • entry_type (str) – The type of the log entry.

class fairgraph.utility.LogEntry(cls: str, id: str | None, delta: Dict[str, Any] | None, space: str | None, type_: str)[source]

Bases: object

Represents an entry in an activity log.

cls

The name of the class of the Knowledge Grapg object.

Type:

str

id

The identifer of the object being logged.

Type:

Optional[str]

delta

A dictionary containing the changes made to the object.

Type:

Optional[JSONdict]

space

The Knowledge Graph space containing the object.

Type:

Optional[str]

type_

The type of the log entry.

Type:

str