ragraph.io.xml
#
XML format support using the XML Metadata Interchange (XMI) standard.
Package Contents#
Classes#
Miscellaneous properties mapping such as tool-specific metadata. |
|
Metadata for graph elements. |
|
Generic node class. |
Functions#
|
Convert a string to a valid XMI id. |
|
Fetch metadata from object and append to element. |
|
Convert Annotations to XML elements. |
|
Convert a Node into an XML element. |
|
Convert an Edge to an XML element. |
|
Encode Graph to an XML element. |
|
Convert XML elements of type rc:Annotation to an Annotations object. |
|
Convert XML elements of rc:Weight type to a weights dictionary. |
|
Extract metadata from element. |
|
Convert an XML element to a Node (parent and children stored as strings). |
|
Convert an XML element to an Edge object. |
|
Resolve parent/child nodal string references from names to nodes. |
|
Decode XML file, string, or element into a Graph. |
Attributes#
- class ragraph.io.xml.Edge(source: ragraph.node.Node, target: ragraph.node.Node, name: Optional[str] = None, kind: str = 'edge', labels: Optional[List[str]] = None, weights: Optional[Dict[str, Union[int, float]]] = None, annotations: Union[ragraph.generic.Annotations, Dict[str, Any], None] = None, uuid: Optional[Union[str, uuid.UUID]] = None)#
Bases:
ragraph.generic.Metadata
Edge between a source
Node
and a targetNode
.- Parameters:
source – Source
Node
of this edge.target – Target
Node
of this edge.name – Instance name. Given a UUID if none provided.
kind – Kind or main category of this instance.
labels – Labels categorizing this instance.
weights – Dictionary of weights attached to this instance.
annotations – Miscellaneous properties of this instance.
uuid – Fixed UUID if desired, generated when left set to None.
- property source: ragraph.node.Node#
Edge source node.
- property target: ragraph.node.Node#
Edge target node.
- property json_dict: Dict[str, Any]#
JSON dictionary representation.
- Returns:
Source node UUID (not Node) as str. target: Target node UUID (not Node) as str. kind: Kind as str. labels: Labels as list of str. weights: Weights as dict. annotations: Annotations as a dictionary.
- Return type:
source
- __str__()#
Return str(self).
- __repr__()#
Return repr(self).
- as_dict(use_uuid: bool = False) Dict[str, Any] #
Return a copy as a (serializable) dictionary.
- Parameters:
use_uuid – Whether to use UUIDs instead of names.
- Returns:
Source node name or UUID (not Node) as str. target: Target node name or UUID (not Node) as str. kind: Kind as str. labels: Labels as list of str. weights: Weights as dict. annotations: Annotations as a dictionary. uuid: UUID as str if toggled.
- Return type:
source
- class ragraph.io.xml.Annotations(*args, **kwargs)#
Bases:
Mapping
Miscellaneous properties mapping such as tool-specific metadata.
- _protected = False#
- class ragraph.io.xml.Metadata(name: Optional[str] = None, kind: Optional[str] = None, labels: Optional[List[str]] = None, weights: Optional[Dict[str, Union[int, float]]] = None, annotations: Optional[Union[Annotations, Dict[str, Any]]] = None, uuid: Optional[Union[str, uuid.UUID]] = None)#
Metadata for graph elements.
- Parameters:
name – Instance name. Set to a copy of the UUID if
None
provided.kind – Kind or main category of this instance.
labels – Labels categorizing this instance.
weights – Dictionary of weights attached to this instance.
annotations – Miscellaneous properties of this instance.
uuid – UUID of this instance, generated when
None
provided.
- property uuid: uuid.UUID#
Instance UUID.
- property name: str#
Instance name. Given a UUID if None was provided.
- property kind: str#
Kind or main category of this instance.
- property labels: List[str]#
Labels categorizing this instance.
- property weights: Dict[str, Union[int, float]]#
Dictionary of weights attached to this instance.
- property weight: Union[int, float]#
Cumulative weight of this instance (read-only).
Returns the sum of
self.weights
.
- property annotations: Annotations#
Annotations of this instance.
Defaults to an empty
Annotations
instance.
- __copy__()#
- __deepcopy__(memo)#
- class ragraph.io.xml.Graph(nodes: Optional[Iterable[ragraph.node.Node]] = None, edges: Optional[Iterable[ragraph.edge.Edge]] = None, add_parents: bool = False, add_children: bool = False, name: Optional[str] = None, kind: Optional[str] = None, labels: Optional[List[str]] = None, weights: Optional[Dict[str, Union[int, float]]] = None, annotations: Optional[Union[ragraph.generic.Annotations, Dict[str, Any]]] = None, uuid: Optional[Union[str, uuid.UUID]] = None)#
Bases:
ragraph.generic.Metadata
Graph of
Node
objects andEdge
objects between them.- Parameters:
nodes – Iterable of graph nodes.
edges – Iterable of graph edges.
add_parents – Recursively add parent nodes of the provided nodes.
add_children – Recursively add child nodes of the provided nodes.
name – Instance name. Given a UUID if none provided.
kind – Kind or main category of this instance.
labels – Labels categorizing this instance.
weights – Dictionary of weights attached to this instance.
annotations – Miscellaneous properties of this instance.
uuid – Fixed UUID if desired, generated when left set to None.
- property nodes: List[ragraph.node.Node]#
Nodes as a list.
- property node_count: int#
Number of nodes in the graph.
- property node_list: List[ragraph.node.Node]#
Nodes as a list.
- property node_dict: Dict[str, ragraph.node.Node]#
Node dictionary by node name.
- property node_uuid_dict: Dict[uuid.UUID, ragraph.node.Node]#
Node dictionary by node UUID.
- property node_gen: Generator[ragraph.node.Node, None, None]#
Yield nodes.
- property edges: List[ragraph.edge.Edge]#
Edges as a list.
- property edge_list: List[ragraph.edge.Edge]#
Edges as a list.
- property edge_dict: Dict[str, ragraph.edge.Edge]#
Edge dictionary by edge name.
- property edge_uuid_dict: Dict[uuid.UUID, ragraph.edge.Edge]#
Edge dictionary by node UUID.
- property directed_edges: Dict[str, Dict[str, List[ragraph.edge.Edge]]]#
Nested edge dictionary from source name to target name to a list of edges.
- property reversed_edges: Dict[str, Dict[str, List[ragraph.edge.Edge]]]#
Nested edge dictionary from target name to source name to a list of edges.
- property edge_gen: Generator[ragraph.edge.Edge, None, None]#
Yield edges.
- property edge_count: int#
Number of edges in the graph.
- property node_kinds: List[str]#
List of unique node kinds in the graph.
- property edge_kinds: List[str]#
List of unique edge kinds in the graph.
- property node_weight_labels: List[str]#
List of unique node weight labels in the graph.
- property edge_weight_labels: List[str]#
List of unique edge weight labels in the graph.
- property node_labels: List[str]#
Alphabetically sorted list of unique node labels in the graph.
- property edge_labels: List[str]#
Alphabetically sorted list of unique edge labels in the graph.
- property roots: List[ragraph.node.Node]#
List of roots in the graph.
- property leafs: List[ragraph.node.Node]#
List of roots in the graph.
- property max_depth: int#
Maximum node depth in the graph.
- property json_dict: Dict[str, Any]#
JSON dictionary representation.
- __str__() str #
Return str(self).
- __repr__() str #
Return repr(self).
- __eq__(other) bool #
Return self==value.
- __getitem__(key: Union[str, uuid.UUID, Tuple[str, str]])#
- __contains__(key: Union[str, uuid.UUID, Tuple[str, str]])#
- __copy__()#
- __deepcopy__(memo)#
- add_node(node: ragraph.node.Node)#
Add a new node to this graph.
If the node instance already exists in the graph, it is ignored.
- Parameters:
node – Node to add.
- del_node(node: Union[ragraph.node.Node, str, uuid.UUID], inherit: bool = False)#
Remove a node and related edges from the graph by name or Node instance.
- Parameters:
node – Node to remove.
inherit – Whether to inherit hierarchy for underlying nodes to the parent.
- add_edge(edge: ragraph.edge.Edge)#
Add a new edge to the graph. Source and target need to exist in the graph.
- Parameters:
edge – Edge to add.
- Raises:
A ValueError if the source or target doesn't exist or the edge instance –
already does. –
- del_edge(edge: Union[ragraph.edge.Edge, str, uuid.UUID])#
Remove an edge from the graph.
- get_kinds(elements: Union[Iterable[ragraph.node.Node], Iterable[ragraph.edge.Edge]]) List[str] #
Get an alphabetically sorted list of unique node/edge kinds in the graph.
- get_nodes_by_kind(kind: str) List[ragraph.node.Node] #
Get nodes/edges by kind.
- get_edges_by_kind(kind: str) List[ragraph.edge.Edge] #
Get edges by kind.
- get_weight_labels(elements: Union[Iterable[ragraph.node.Node], Iterable[ragraph.edge.Edge]]) List[str] #
Get an alphabetically sorted list of unique labels of node/edge weights.
- edges_from(source: Union[str, ragraph.node.Node]) Generator[ragraph.edge.Edge, None, None] #
Yield edges originating from a given source node.
- targets_of(source: Union[str, ragraph.node.Node]) Generator[ragraph.node.Node, None, None] #
Yield target nodes of a given source node.
- edges_to(target: Union[str, ragraph.node.Node]) Generator[ragraph.edge.Edge, None, None] #
Yield edges towards a given target node.
- sources_of(target: Union[str, ragraph.node.Node]) Generator[ragraph.node.Node, None, None] #
Yield source nodes of a given target node.
- edges_between(source: Union[str, ragraph.node.Node], target: Union[str, ragraph.node.Node], inherit: bool = False, loops: bool = True) Generator[ragraph.edge.Edge, None, None] #
Yield edges between source and target node.
- Parameters:
sources – Source nodes.
targets – Target nodes.
inherit – Whether to include edges between descendants of given nodes.
loops – Whether to include self-loop edges.
- edges_between_all(sources: Iterable[Union[str, ragraph.node.Node]], targets: Iterable[Union[str, ragraph.node.Node]], inherit: bool = False, loops: bool = True) Generator[ragraph.edge.Edge, None, None] #
Yield all edges between a set of source and a set of target nodes.
- Parameters:
sources – Source nodes.
targets – Target nodes.
inherit – Whether to include edges between descendants of given nodes.
loops – Whether to include self-loop edges.
- get_graph_slice(nodes: Optional[Iterable[ragraph.node.Node]] = None, edges: Optional[Iterable[ragraph.edge.Edge]] = None, inherit: bool = False) Graph #
Return the graph slice with only the given nodes and the edges between those.
- Parameters:
nodes – Optional set of nodes to include in the new deep copy. Defaults to all.
edges – Optional set of edges to include in the new deep copy. Defaults to all between selected nodes.
inherit – Whether to include child nodes of the given nodes and edges between them (unless edges are explicitly specified).
Note
This returns a deepcopy, so the copied nodes and edges do NOT share any changes! All parent and child nodes not in the list are excluded.
- get_node_selection(node_kinds: Optional[List[str]] = None, edge_kinds: Optional[List[str]] = None, depth: int = 2, selection_mode: str = 'dependent') List[ragraph.node.Node] #
Select specific nodes from this graph in a structured order.
- Parameters:
node_kinds – The kind of nodes to be selected.
edge_kinds – The kind of edges to be selected.
depth – The maximum depth of node to be selected.
selection_mode – The selection mode. Either ‘dependent’ or ‘independent’.
Note
The selection mode argument determines how nodes of different kinds are selected. If the selection mode is set to ‘dependent’, the first node kind in the
node_kinds
list is considered to be the ‘lead node kind’. Nodes of different kind than the lead node kind, are only selected if they have a dependency with at least one of the selected nodes of the lead node kind. If the selection mode is set to ‘independent’ this dependency condition is dropped.
- get_edge_selection(nodes: Optional[List[ragraph.node.Node]] = None, edge_kinds: Optional[List[str]] = None) List[ragraph.edge.Edge] #
Select specific edges from this graph.
- Parameters:
nodes – The list of nodes between which the edges must be selected.
edge_kinds – The kinds of edges to be selected.
- Returns:
List of selected edges.
- get_node_and_edge_selection(node_kinds: Optional[List[str]] = None, edge_kinds: Optional[List[str]] = None, depth: int = 2, selection_mode: str = 'dependent') Tuple[List[ragraph.node.Node], List[ragraph.edge.Edge]] #
Select specific nodes and edges from this graph in a structured order.
- Parameters:
node_kinds – The kind of nodes to be selected.
edge_kinds – The kind of edges to be selected.
depth – The maximum depth of node to be selected.
selection_mode – The selection mode. Either ‘dependent’ or ‘independent’.
Note
The selection mode argument determines how nodes of different kinds are selected. If the selection mode is set to ‘dependent’, the first node kind in the
node_kinds
list is considered to be the ‘lead node kind’. Nodes of different kind than the lead node kind, are only selected if they have a dependency with at least one of the selected nodes of the lead node kind. If the selection mode is set to ‘independent’ this dependency condition is dropped.
- get_hierarchy_dict(roots: Optional[List[ragraph.node.Node]] = None, levels: Optional[int] = None)#
Return a dictionary of the (partial) hierarchical node structure.
- Parameters:
roots – Root nodes of the hierarchy to calculate.
levels – Number of levels to include below the roots.
- get_adjacency_matrix(nodes: Optional[Union[List[ragraph.node.Node], List[str]]] = None, inherit: bool = False, loops: bool = False, only: Optional[List[str]] = None) Union[numpy.ndarray, List[List[float]]] #
Convert graph data into a numerical adjacency matrix.
- Parameters:
nodes – Optional list of nodes for which to get the adjacency matrix.
inherit – Whether to count weights between children of the given nodes.
loops – Whether to calculate self-loops from a node to itself.
only – Optional subset of edge weights to consider. See
Edge
for default edge weight implementation.
- Returns:
Adjacency matrix as a 2D numpy array if numpy is present. Otherwise it will return a 2D nested list.
- get_mapping_matrix(rows: Optional[Union[List[ragraph.node.Node], List[str]]] = None, cols: Optional[Union[List[ragraph.node.Node], List[str]]] = None, inherit: bool = False, loops: bool = False, only: Optional[List[str]] = None) Union[numpy.ndarray, List[List[float]]] #
Convert graph data into a numerical mapping matrix.
- Parameters:
graph – Graph to fetch data from.
rows – Nodes representing the matrix rows.
cols – Nodes representing the matrix columns if different from the rows.
inherit – Whether to count weights between children of the given nodes.
loops – Whether to calculate self-loops from a node to itself.
only – Optional subset of edge weights to consider. See
Edge
for default edge weight implementation.
- Returns:
Adjacency matrix as a 2D numpy array if numpy is present. Otherwise it will return a 2D nested list.
- get_ascii_art(nodes: Optional[List[ragraph.node.Node]] = None, edge: str = 'X', diag: str = '■', show: bool = True) Optional[str] #
Get a unicode ASCII art representation of a binary adjacency matrix for a given set of nodes.
- Parameters:
nodes – Nodes to include in the art.
edge – Mark to use when there’s an edge between nodes. (X by default)
diag – Mark to use on the diagonal.
show – Whether to directly print the ASCII art.
- Returns:
ASCII art representation of this graph.
- as_dict(use_uuid: bool = False) Dict[str, Any] #
Return a copy as a (serializable) dictionary.
- Parameters:
use_uuid – Whether to use UUIDs instead of names.
- Returns:
Node names or UUIDs to Node dictionaries. kind: Kind as str. labels: Labels as list of str. weights: Weights as dict. annotations: Annotations as a dictionary. uuid: UUID as str if toggled.
- Return type:
nodes
- check_consistency(raise_error: bool = True) bool #
Check the consistency of this graph.
- Parameters:
raise_error – Whether to raise an error instead of returning a bool.
- Returns:
Whether nodes aren’t their own ancestor/descendant and if all their children and parents exist in the graph. Raises an error for inconsistencies if
raise_error
is set to True.
- class ragraph.io.xml.Node(name: Optional[str] = None, parent: Optional[Node] = None, children: Optional[Iterable[Node]] = None, is_bus: bool = False, kind: str = 'node', labels: Optional[List[str]] = None, weights: Optional[Dict[str, Union[int, float]]] = None, annotations: Union[ragraph.generic.Annotations, Dict[str, Any], None] = None, uuid: Optional[Union[str, uuid.UUID]] = None)#
Bases:
ragraph.generic.Metadata
Generic node class.
- Parameters:
name – Instance name. Given a UUID if none provided.
parent – Parent node.
children – List of child nodes.
kind – Kind or main category of this instance.
labels – Labels categorizing this instance.
weights – Dictionary of weights attached to this instance.
annotations – Miscellaneous properties of this instance.
uuid – Fixed UUID if desired, generated when left set to None.
- property is_bus#
Whether this node is a bus node for its parent.
- property depth: int#
Depth of this node, e.g. the number of levels from the node to the root.
- property height: int#
Height of this node, e.g. the longest simple path to a leaf node.
- property width: int#
Width of this node, e.g. the number of leaf nodes in this node’s branch.
- property is_leaf: bool#
Whether this node is a leaf node (has no children).
- property is_root: bool#
Whether this node is a root node (has no parent).
- property json_dict: Dict[str, Any]#
JSON dictionary representation.
- Returns:
Name as str. parent: Parent name (not Node) as str. children: Children names (not Nodes) as str. is_bus: is_bus as bool. kind: Kind as str. labels: Labels as a list of strings. weights: Weights as dict. annotations: Annotations as per
ragraph.generic.Mapping.as_dict()
.- Return type:
name
- __str__() str #
Return str(self).
- __repr__() str #
Return repr(self).
- as_dict(use_uuid: bool = False) Dict[str, Any] #
Return a copy as a (serializable) dictionary.
- Returns:
Name as str. parent: Parent name or UUID (not Node) as str. children: Children names (not Nodes) as str. is_bus: is_bus as bool. kind: Kind as str. labels: Labels as a list of strings. weights: Weights as dict. annotations: Annotations as per
ragraph.generic.Mapping.as_dict()
. uuid: UUID as str if toggled.- Return type:
name
- ragraph.io.xml.here#
- ragraph.io.xml.schema_doc#
- ragraph.io.xml.schema#
- ragraph.io.xml.schema_root#
- ragraph.io.xml.nsmap#
- ragraph.io.xml.q_id#
- ragraph.io.xml.q_graph#
- ragraph.io.xml.q_node#
- ragraph.io.xml.q_edge#
- ragraph.io.xml.q_weight#
- ragraph.io.xml.q_annotation#
- ragraph.io.xml._get_xmi_id(obj: ragraph.generic.Metadata, prefix: str) str #
Convert a string to a valid XMI id.
- ragraph.io.xml._metadata_to_subelements(elem: lxml.etree.Element, obj: ragraph.generic.Metadata)#
Fetch metadata from object and append to element.
- ragraph.io.xml._annotations_to_elements(annotations: ragraph.generic.Annotations) List[lxml.etree.Element] #
Convert Annotations to XML elements.
- ragraph.io.xml._node_to_element(node: ragraph.node.Node) lxml.etree.Element #
Convert a Node into an XML element.
- ragraph.io.xml._edge_to_element(edge: ragraph.edge.Edge) lxml.etree.Element #
Convert an Edge to an XML element.
- ragraph.io.xml.to_xml(graph: ragraph.graph.Graph, path: Optional[Union[str, pathlib.Path]] = None, elem: Optional[lxml.etree.Element] = None, tostring_args: Optional[Dict[str, Any]] = None, bundle_schemas: bool = False) str #
Encode Graph to an XML element.
- Parameters:
graph – Graph to convert to XML.
path – Optional file path to write XML to.
elem – Optional object to append the Graph to.
tostring_args – Optional argument overrides to
lxml.etree.tostring()
.bundle_schemas – When exporting to a file, bundle the .xsd schemas.
- Returns:
XML element.
- ragraph.io.xml._elements_to_annotations(elems: Iterable[lxml.etree.Element]) ragraph.generic.Annotations #
Convert XML elements of type rc:Annotation to an Annotations object.
- ragraph.io.xml._elements_to_weights(elems: Iterable[lxml.etree.Element]) Dict[str, Any] #
Convert XML elements of rc:Weight type to a weights dictionary.
- ragraph.io.xml._element_to_metadata(elem: lxml.etree.Element, obj: ragraph.generic.Metadata)#
Extract metadata from element.
- ragraph.io.xml._element_to_node(elem: lxml.etree.Element) ragraph.node.Node #
Convert an XML element to a Node (parent and children stored as strings).
- ragraph.io.xml._element_to_edge(elem: lxml.etree.Element, node_dict: Dict[str, Any]) ragraph.edge.Edge #
Convert an XML element to an Edge object.
- ragraph.io.xml._resolve_node_references(node_dict: Dict[str, ragraph.node.Node])#
Resolve parent/child nodal string references from names to nodes.
- ragraph.io.xml.from_xml(path: Optional[Union[str, pathlib.Path]] = None, enc: Optional[str] = None, elem: Optional[lxml.etree.Element] = None, validate: bool = True) ragraph.graph.Graph #
Decode XML file, string, or element into a Graph.
- Parameters:
path – XML file path.
enc – XML encoded string.
elem – XML Element.
validate – Whether to validate the XML input.
- Returns:
Graph object.
Note
You should only provide one of
path
,enc
, orelem
, which are handled in that order of precedence.