ontouml_models_lib.utils.queryable_element ========================================== .. py:module:: ontouml_models_lib.utils.queryable_element .. autoapi-nested-parse:: The `queryable_element` module provides the `QueryableElement` class, a base class designed to represent elements within the OntoUML/UFO catalog that can be queried using SPARQL. This module facilitates the execution of SPARQL queries on RDF graphs, manages query results, and ensures consistent hashing of both queries and graph data. Overview -------- The `QueryableElement` class serves as a foundational class for elements that interact with RDF graphs in the OntoUML/UFO catalog. It provides methods for executing SPARQL queries on these graphs, computing and checking hashes to prevent redundant query executions, and managing the storage of query results. This class is crucial for ensuring the integrity, consistency, and reusability of queries within the catalog. Dependencies ------------ - **rdflib**: For RDF graph operations and SPARQL query execution. - **hashlib**: For computing hashes of RDF graphs and SPARQL queries. - **pathlib**: For handling file paths in a platform-independent manner. - **csv**: For managing the storage of query results in CSV format. - **loguru**: For logging operations and debugging information. References ---------- For additional details on the OntoUML/UFO catalog, refer to the official OntoUML repository: https://github.com/OntoUML/ontouml-models Classes ------- .. autoapisummary:: ontouml_models_lib.utils.queryable_element.QueryableElement Module Contents --------------- .. py:class:: QueryableElement(id) Bases: :py:obj:`abc.ABC` A base class representing an element in the OntoUML/UFO catalog that can be queried using SPARQL. The `QueryableElement` class provides foundational functionality for executing SPARQL queries on RDF graphs, computing consistent hashes for both the RDF graphs and queries, and managing the storage of query results. It is designed to be extended by other classes, such as `Catalog` and `Model`, and should not be instantiated directly by users. This class is intended for internal use and should be accessed indirectly through the `Catalog` or `Model` classes. :ivar id: The unique identifier for the `QueryableElement`. :vartype id: str :ivar model_graph: The RDF graph associated with the `QueryableElement`. :vartype model_graph: Graph :ivar model_graph_hash: A persistent hash value computed from the RDF graph, used to ensure consistency and integrity of the graph's content. :vartype model_graph_hash: int .. py:attribute:: id :type: str .. py:attribute:: model_graph :type: rdflib.Graph .. py:attribute:: model_graph_hash :type: int .. py:method:: execute_query(query, results_path = None, save_results = True) Execute a SPARQL query on the element's RDF graph and return the results as a list of dictionaries. This method executes a SPARQL query on the `model_graph` associated with the `QueryableElement`. It first checks whether the combination of the graph's hash and the query's hash has already been executed, in which case it skips execution to prevent redundancy. If the query is executed and `save_results` is True, the results are saved to a CSV file, and the hash combination is recorded for future reference. :param query: A `Query` instance containing the SPARQL query to be executed. :type query: Query :param results_path: The path to the directory where the query results and hash file will be saved. If not provided, defaults to `./results`. :type results_path: Optional[Union[str, Path]] :param save_results: Whether to save the results to a CSV file. Defaults to True. :type save_results: bool :return: A list of dictionaries, where each dictionary represents a result row from the SPARQL query. :rtype: list[dict] **Example**:: >>> from ontouml_models_lib import Model >>> from ontouml_models_lib import Query >>> model = Model('/path/to/ontology_model_folder') >>> query = Query('/path/to/query.sparql') >>> results = model.execute_query(query, '/path/to/results', save_results=False) >>> print(results) # Output: [{'subject': 'ExampleSubject', 'predicate': 'ExamplePredicate', 'object': 'ExampleObject'}] .. py:method:: execute_queries(queries, results_path = None) Execute a list of SPARQL queries on the element's RDF graph and saves the results. This method iterates over a list of `Query` instances, executing each query on the `model_graph` associated with the `QueryableElement`. The results of each query are saved to a CSV file in the specified directory. This method is useful for batch processing multiple SPARQL queries on a single RDF graph. :param queries: A list of `Query` instances to be executed on the `model_graph`. :type queries: list[Query] :param results_path: The path to the directory where the query results will be saved. If not provided, defaults to `./results`. :type results_path: Optional[Path] **Example**:: >>> from ontouml_models_lib import Model >>> from ontouml_models_lib import Query >>> model = Model('/path/to/ontology_model_folder') >>> queries = [Query('/path/to/query1.sparql'), Query('/path/to/query2.sparql')] >>> model.execute_queries(queries, '/path/to/results') .. py:method:: _compute_hash() Compute a hash value for the QueryableElement. This method generates a hash value based on the element's unique identifier (`id`). The computed hash serves as a persistent identifier for the RDF graph associated with the element, ensuring consistency and integrity across operations involving the element. :return: The computed hash value for the QueryableElement. :rtype: int .. py:method:: _compute_query_hash(query) Compute a consistent hash value for a SPARQL query. This method generates a SHA-256 hash for the given SPARQL query string. The resulting hash is used to ensure that identical queries produce the same hash value, facilitating the management of query results and avoiding redundant executions. :param query: The SPARQL query string to be hashed. :type query: str :return: The computed hash value for the query. :rtype: int .. py:method:: _hash_exists(query_hash, results_path) Check if a query's hash value already exists in the results directory. This method verifies whether a hash value for a given SPARQL query has been previously computed and stored in the `.hashes.csv` file within the specified results directory. This prevents redundant executions of the same query on the same RDF graph. :param query_hash: The hash value of the SPARQL query to be checked. :type query_hash: int :param results_path: The path to the directory where query results and hash records are stored. :type results_path: Path :return: True if the query's hash value exists in the results directory; False otherwise. :rtype: bool .. py:method:: _save_results(results, result_file) Save the results of a SPARQL query to a CSV file. This method writes the results of a SPARQL query to a CSV file in the specified file. If no results are present, an empty file is created. :param results: A list of dicts containing the query results, where each dictionary represents a result row. :type results: list[dict] :param results_path: The path to the file to which the results will be saved. :type results_path: Path .. py:method:: _save_hash_file(query_hash, results_path) Save the hash value of a SPARQL query and the associated RDF graph to a file. This method records the hash values of a SPARQL query and the corresponding RDF graph in the `.hashes.csv` file within the specified directory. This ensures that the combination of the query and graph can be identified in future operations, preventing redundant executions. :param query_hash: The hash value of the SPARQL query being executed. :type query_hash: int :param results_path: The path to the directory where the hash record will be saved. :type results_path: Path