# query { #tvbo.ontology.query }

`ontology.query`

SPARQL-based query helpers for the TVBO ontology.

This module provides thin wrappers around owlready2's SPARQL engine and the low-level triple store to look up ontology classes and individuals by label, synonym, acronym or symbol, traverse relationships (parents and children) and normalise IRIs to their prefixed form.

## Attributes

| Name | Description |
| --- | --- |
| [prefixes](#tvbo.ontology.query.prefixes) |  |

## Functions

| Name | Description |
| --- | --- |
| [build_filter](#tvbo.ontology.query.build_filter) | Build a single SPARQL `FILTER` clause matching a variable against a label. |
| [convert_greek_to_latin](#tvbo.ontology.query.convert_greek_to_latin) | Converts Greek letters and the micro sign (µ) in the input text to their corresponding Latin names. |
| [flatten_list](#tvbo.ontology.query.flatten_list) | Recursively flattens a list of lists. |
| [get_children](#tvbo.ontology.query.get_children) | Return the incoming edges of a class, i.e. entities that point to it. |
| [get_class_relationships](#tvbo.ontology.query.get_class_relationships) | Return all direct predicate-object pairs for an ontology class. |
| [get_parents](#tvbo.ontology.query.get_parents) | Return the outgoing edges of a class, i.e. entities it points to. |
| [instance_class_relationship](#tvbo.ontology.query.instance_class_relationship) | Return classes linked to a subject through an OWL restriction. |
| [iri2prefix](#tvbo.ontology.query.iri2prefix) | Abbreviate a full IRI to its prefixed (CURIE-like) form. |
| [label_search](#tvbo.ontology.query.label_search) | Search the ontology for entities matching a label across several fields. |
| [sparql_query](#tvbo.ontology.query.sparql_query) | Run a SPARQL query against an ontology world and collect the results. |

### build_filter { #tvbo.ontology.query.build_filter }

```python
ontology.query.build_filter(label, field, exact, case_sensitive)
```

Build a single SPARQL `FILTER` clause matching a variable against a label.

The clause guards the variable with `BOUND` and compares it to `label` using either equality (exact) or `CONTAINS` (substring), optionally lowercasing both sides for case-insensitive matching.

#### Parameters {.doc-section .doc-section-parameters}

| Name           | Type   | Description                                                     | Default    |
|----------------|--------|-----------------------------------------------------------------|------------|
| label          | str    | The search term to match against.                               | _required_ |
| field          | str    | Name of the SPARQL variable (without the leading `?`) to test.  | _required_ |
| exact          | bool   | If `True`, require an exact match; otherwise match a substring. | _required_ |
| case_sensitive | bool   | If `False`, compare using `LCASE` on both operands.             | _required_ |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type   | Description                                                     |
|--------|--------|-----------------------------------------------------------------|
|        | str    | A SPARQL boolean expression suitable for use inside a `FILTER`. |

### convert_greek_to_latin { #tvbo.ontology.query.convert_greek_to_latin }

```python
ontology.query.convert_greek_to_latin(text)
```

Converts Greek letters and the micro sign (µ) in the input text to their corresponding Latin names.

Args:
text (str): The input text that may contain Greek letters or the micro sign.

Returns:
str: The text with all Greek letters and the micro sign replaced by their Latin names.

### flatten_list { #tvbo.ontology.query.flatten_list }

```python
ontology.query.flatten_list(nested_list)
```

Recursively flattens a list of lists.

#### Parameters {.doc-section .doc-section-parameters}

| Name        | Type   | Description                           | Default    |
|-------------|--------|---------------------------------------|------------|
| nested_list | list   | A list that may contain nested lists. | _required_ |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type        | Description                                           |
|--------|-------------|-------------------------------------------------------|
| list   | list\[Any\] | A flattened list with all elements from nested lists. |

### get_children { #tvbo.ontology.query.get_children }

```python
ontology.query.get_children(cl, onto=None)
```

Return the incoming edges of a class, i.e. entities that point to it.

Scans the triple store for triples whose object is `cl` and returns each predicate together with the subject entity, giving the class's immediate children in the relationship graph.

#### Parameters {.doc-section .doc-section-parameters}

| Name   | Type   | Description                                                                                                                                 | Default    |
|--------|--------|---------------------------------------------------------------------------------------------------------------------------------------------|------------|
| cl     | Any    | The target class as an owlready2 entity, a label string, or an integer identifier (zero-padded to six digits and resolved by `identifier`). | _required_ |
| onto   | Any    | The ontology to query. Defaults to the global runtime ontology.                                                                             | `None`     |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type                      | Description                                                            |
|--------|---------------------------|------------------------------------------------------------------------|
|        | list\[tuple\[str, Any\]\] | A list of `(predicate, entity)` tuples, with predicates abbreviated to |
|        | list\[tuple\[str, Any\]\] | their prefixed form.                                                   |

### get_class_relationships { #tvbo.ontology.query.get_class_relationships }

```python
ontology.query.get_class_relationships(class_iri)
```

Return all direct predicate-object pairs for an ontology class.

#### Parameters {.doc-section .doc-section-parameters}

| Name      | Type       | Description                                                                             | Default    |
|-----------|------------|-----------------------------------------------------------------------------------------|------------|
| class_iri | str \| Any | Either the class IRI as a string, or an owlready2 entity whose `iri` attribute is used. | _required_ |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type                      | Description                                                            |
|--------|---------------------------|------------------------------------------------------------------------|
|        | list\[tuple\[Any, Any\]\] | A list of `(predicate, object)` rows for every triple whose subject is |
|        | list\[tuple\[Any, Any\]\] | the given class.                                                       |

### get_parents { #tvbo.ontology.query.get_parents }

```python
ontology.query.get_parents(cl, onto=None)
```

Return the outgoing edges of a class, i.e. entities it points to.

Scans the triple store for triples whose subject is `cl` and returns each predicate together with the resolvable object entity, giving the class's immediate parents in the relationship graph.

#### Parameters {.doc-section .doc-section-parameters}

| Name   | Type   | Description                                                                                                                                 | Default    |
|--------|--------|---------------------------------------------------------------------------------------------------------------------------------------------|------------|
| cl     | Any    | The source class as an owlready2 entity, a label string, or an integer identifier (zero-padded to six digits and resolved by `identifier`). | _required_ |
| onto   | Any    | The ontology to query. Defaults to the global runtime ontology.                                                                             | `None`     |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type                      | Description                                                            |
|--------|---------------------------|------------------------------------------------------------------------|
|        | list\[tuple\[str, Any\]\] | A list of `(predicate, entity)` tuples, with predicates abbreviated to |
|        | list\[tuple\[str, Any\]\] | their prefixed form; objects that do not resolve to an entity are      |
|        | list\[tuple\[str, Any\]\] | skipped.                                                               |

### instance_class_relationship { #tvbo.ontology.query.instance_class_relationship }

```python
ontology.query.instance_class_relationship(subject_iri, predicate='prov:used')
```

Return classes linked to a subject through an OWL restriction.

Follows `owl:Restriction` nodes attached to the subject and returns the classes referenced by their `owl:someValuesFrom`, optionally constrained to restrictions on a given `owl:onProperty`.

#### Parameters {.doc-section .doc-section-parameters}

| Name        | Type   | Description                                                                                                                     | Default       |
|-------------|--------|---------------------------------------------------------------------------------------------------------------------------------|---------------|
| subject_iri | str    | IRI of the subject class or individual to inspect.                                                                              | _required_    |
| predicate   | str    | Prefixed property (e.g. `prov:used`) that the restriction must be `owl:onProperty` of; an empty string removes this constraint. | `'prov:used'` |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type                      | Description                                                     |
|--------|---------------------------|-----------------------------------------------------------------|
|        | list\[tuple\[Any, Any\]\] | A list of `(predicate, object)` rows describing the restriction |
|        | list\[tuple\[Any, Any\]\] | property and the class it points to.                            |

### iri2prefix { #tvbo.ontology.query.iri2prefix }

```python
ontology.query.iri2prefix(iri)
```

Abbreviate a full IRI to its prefixed (CURIE-like) form.

Each known namespace base (`rdf`, `rdfs`, `owl`, `tvbo`) is replaced by its short prefix; an IRI with no matching namespace is returned unchanged.

#### Parameters {.doc-section .doc-section-parameters}

| Name   | Type   | Description                     | Default    |
|--------|--------|---------------------------------|------------|
| iri    | str    | The absolute IRI to abbreviate. | _required_ |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type   | Description                                                   |
|--------|--------|---------------------------------------------------------------|
|        | str    | The IRI with any known namespace base replaced by its prefix. |

### label_search { #tvbo.ontology.query.label_search }

```python
ontology.query.label_search(
    label,
    include=None,
    exact_match=None,
    case_sensitive=False,
    root_class=None,
    greek_to_latin=True,
    ignore_underscore=False,
    types=None,
    onto=None,
)
```

Search the ontology for entities matching a label across several fields.

Builds a SPARQL query that tests `rdfs:label`, `skos:altLabel` and each included annotation property (e.g. `synonym`, `acronym`, `symbol`) against the search term, then returns the matching classes and/or individuals.
Optionally restricts the results to descendants of a given root class.

#### Parameters {.doc-section .doc-section-parameters}

| Name              | Type                       | Description                                                                                                             | Default    |
|-------------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------|------------|
| label             | str                        | The term to search for.                                                                                                 | _required_ |
| include           | list\[str\] \| None        | Extra annotation fields to match on. Bare names are prefixed with `tvbo:`; values containing `:` are used as-is.        | `None`     |
| exact_match       | str \| list\[str\] \| None | Field name, list of field names, or `"all"` for which matching must be exact rather than substring-based.               | `None`     |
| case_sensitive    | bool                       | Whether comparisons are case sensitive.                                                                                 | `False`    |
| root_class        | Any                        | If given, keep only results that are descendants of this class (an entity or a label string resolved via `search_one`). | `None`     |
| greek_to_latin    | bool                       | If `True`, transliterate Greek letters in `label` to their Latin names before searching.                                | `True`     |
| ignore_underscore | bool                       | If `True`, strip underscores from `label`.                                                                              | `False`    |
| types             | list\[str\] \| None        | The RDF types to restrict subjects to (e.g. `owl:Class`, `owl:NamedIndividual`).                                        | `None`     |
| onto              | Any                        | The ontology to query. Defaults to the global runtime ontology.                                                         | `None`     |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type                         | Description                                                             |
|--------|------------------------------|-------------------------------------------------------------------------|
|        | list\[owlready2.ThingClass\] | A de-duplicated list of matching ontology entities, optionally filtered |
|        | list\[owlready2.ThingClass\] | to descendants of `root_class`.                                         |

### sparql_query { #tvbo.ontology.query.sparql_query }

```python
ontology.query.sparql_query(query_string, flatten_result=True, world=None)
```

Run a SPARQL query against an ontology world and collect the results.

Undefined entities are tolerated (`error_on_undefined_entities=False`) so that optional clauses referencing annotation properties absent from the generated ontology match nothing instead of raising.

#### Parameters {.doc-section .doc-section-parameters}

| Name           | Type   | Description                                                                                            | Default    |
|----------------|--------|--------------------------------------------------------------------------------------------------------|------------|
| query_string   | str    | The SPARQL query to execute.                                                                           | _required_ |
| flatten_result | bool   | If `True`, recursively flatten the result rows into a single flat list; otherwise return the raw rows. | `True`     |
| world          | Any    | An owlready2 `World` to query. Defaults to the global runtime ontology's world when `None`.            | `None`     |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type        | Description                                                           |
|--------|-------------|-----------------------------------------------------------------------|
|        | list\[Any\] | The query results, flattened into a single list when `flatten_result` |
|        | list\[Any\] | is `True`, otherwise the raw list of result rows.                     |