Skip to content

Commit

Permalink
add docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
srmnitc committed Apr 19, 2024
1 parent c146a78 commit 62d20ab
Show file tree
Hide file tree
Showing 11 changed files with 1,386 additions and 141 deletions.
483 changes: 416 additions & 67 deletions atomrdf/graph.py

Large diffs are not rendered by default.

43 changes: 40 additions & 3 deletions atomrdf/namespace.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
"""
This module provides the Namespace class for managing namespaces in the AtomRDF library.
The Namespace class extends the rdflib.Namespace class and provides additional functionality for working with namespaces.
Classes
-------
Namespace
A class representing a namespace in the AtomRDF library.
"""

import os
from rdflib import Literal, URIRef
from rdflib import Namespace as RDFLibNamespace
Expand All @@ -7,13 +18,39 @@


class Namespace(AttrSetter, RDFLibNamespace):
"""A class representing a namespace in the AtomRDF library.
This class extends the `rdflib.Namespace` classes.
Parameters
----------
infile : str
The input file path.
delimiter : str, optional
The delimiter used in the input file. Defaults to "/".
Attributes
----------
network : OntologyNetwork
The ontology network associated with the namespace.
name : str
The name of the namespace.
"""

def __init__(self, infile, delimiter="/"):
"""
Initialize the Namespace class.
Parameters
----------
infile : str
The input file path.
delimiter : str, optional
The delimiter used in the input file. Defaults to "/".
"""
AttrSetter.__init__(self)
self.network = OntologyNetwork(infile, delimiter=delimiter)
# print(type(self.network.onto.tree.base_iri))
# self.namespace = RDFLibNamespace(self.network.onto.tree.base_iri)
RDFLibNamespace.__init__(self.network.onto.tree.base_iri)
# self.namespace = RDFLibNamespace("http://purls.helmholtz-metadaten.de/cmso/")
self.name = self.network.onto.tree.name
mapdict = {}

Expand Down
154 changes: 139 additions & 15 deletions atomrdf/network/network.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@


import networkx as nx
import graphviz
import matplotlib.pyplot as plt
Expand Down Expand Up @@ -81,6 +83,26 @@ def __radd__(self, ontonetwork):
return self.__add__(ontonetwork)

def get_shortest_path(self, source, target, triples=False):
"""
Compute the shortest path between two nodes in the graph.
Parameters:
-----------
source : node
The starting node for the path.
target : node
The target node for the path.
triples : bool, optional
If True, returns the path as a list of triples. Each triple consists of three consecutive nodes in the path.
If False, returns the path as a list of nodes.
Returns:
--------
path : list
The shortest path between the source and target nodes. If `triples` is True, the path is returned as a list of triples.
If `triples` is False, the path is returned as a list of nodes.
"""
path = nx.shortest_path(self.g, source=source, target=target)
if triples:
triple_list = []
Expand Down Expand Up @@ -115,7 +137,20 @@ def _add_data_properties(self):

def add_namespace(self, namespace_name, namespace_iri):
"""
Add a new namespace
Add a new namespace.
Parameters
----------
namespace_name : str
The name of the namespace to add.
namespace_iri : str
The IRI of the namespace.
Raises
------
KeyError
If the namespace already exists.
"""
if namespace_name not in self.onto.namespaces.keys():
self.onto.namespaces[namespace_name] = namespace_iri
Expand All @@ -127,17 +162,40 @@ def add_term(
uri,
node_type,
namespace=None,
dm=[],
rn=[],
dm=(),
rn=(),
data_type=None,
node_id=None,
delimiter="/",
):
"""
Add a node
Add a node.
Parameters
----------
uri : str
The URI of the node.
node_type : str
The type of the node.
namespace : str, optional
The namespace of the node.
dm : list, optional
The domain metadata of the node.
rn : list, optional
The range metadata of the node.
data_type : str, optional
The data type of the node.
node_id : str, optional
The ID of the node.
delimiter : str, optional
The delimiter used for parsing the URI.
Raises
------
ValueError
If the namespace is not found.
"""
# namespace = strip_name(uri, delimiter, get_what="namespace")
# name = strip_name(uri, delimiter, get_what="name")
term = OntoTerm(
uri,
namespace=namespace,
Expand All @@ -155,11 +213,24 @@ def add_term(

def add_path(self, triple):
"""
Add a triple as path. Note that all attributes of the triple should already
exist in the graph. The ontology itself is not modified. Only the graph
representation of it is.
The expected use is to bridge between two(or more) different ontologies.
Add a triple as path.
Note that all attributes of the triple should already exist in the graph.
The ontology itself is not modified. Only the graph representation of it is.
The expected use is to bridge between two (or more) different ontologies.
Therefore, mapping can only be between classes.
Parameters
----------
triple : tuple
A tuple representing the triple to be added. The tuple should contain three elements:
subject, predicate, and object.
Raises
------
ValueError
If the subject or object of the triple is not found in the attributes of the ontology.
"""
sub = triple[0]
pred = triple[1]
Expand Down Expand Up @@ -190,15 +261,38 @@ def add_path(self, triple):
else:
raise ValueError(f"{pred} not found in self.attributes")

def draw(
self,
def draw(self,
styledict={
"class": {"shape": "box"},
"object_property": {"shape": "ellipse"},
"data_property": {"shape": "ellipse"},
"literal": {"shape": "parallelogram"},
},
):
},):
"""
Draw the network graph using graphviz.
Parameters
----------
styledict : dict, optional
A dictionary specifying the styles for different node types.
The keys of the dictionary are the node types, and the values are dictionaries
specifying the shape for each node type. Defaults to None.
Returns
-------
graphviz.Digraph
The graph object representing the network graph.
Example
-------
styledict = {
"class": {"shape": "box"},
"object_property": {"shape": "ellipse"},
"data_property": {"shape": "ellipse"},
"literal": {"shape": "parallelogram"},
}
network.draw(styledict)
"""
dot = graphviz.Digraph()
node_list = list(self.g.nodes(data="node_type"))
edge_list = list(self.g.edges)
Expand All @@ -212,14 +306,44 @@ def draw(
return dot

def get_path_from_sample(self, target):
"""
Get the shortest path from the 'cmso:ComputationalSample' node to the target node.
Parameters
----------
target : OntoTerm
The target node to find the shortest path to.
Returns
-------
list
A list of triples representing the shortest path from 'cmso:ComputationalSample' to the target node.
"""
path = self.get_shortest_path(
source="cmso:ComputationalSample", target=target, triples=True
)
return path

def create_query(self, source, destinations, condition=None, enforce_types=True):
"""
values is a dict with keys value, operation
Create a SPARQL query string based on the given source, destinations, condition, and enforce_types.
Parameters
----------
source : Node
The source node from which the query starts.
destinations : list or Node
The destination node(s) to which the query should reach. If a single node is provided, it will be converted to a list.
condition : Condition, optional
The condition to be applied in the query. Defaults to None.
enforce_types : bool, optional
Whether to enforce the types of the source and destination nodes in the query. Defaults to True.
Returns
-------
str
The generated SPARQL query string.
"""
if not isinstance(destinations, list):
destinations = [destinations]
Expand Down
7 changes: 7 additions & 0 deletions atomrdf/network/ontology.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@


def read_ontology():
"""
Read in ontologies and perform necessary operations.
Returns
-------
combo: OntologyNetwork, Combined ontology network.
"""
# read in ontologies
file_location = os.path.dirname(__file__).split("/")
file_location = "/".join(file_location[:-1])
Expand Down
Loading

0 comments on commit 62d20ab

Please sign in to comment.