Welcome to KADMOS’s documentation!¶
See sidebar on the right for the table of contents.
Documentation for the Code¶
Below the simplified class diagram of the KADMOS package is shown (not all methods are included for clarity). The UML can als be downloaded as PDF here
.

Example scripts for using KADMOS are available in the examples/scripts folder. The following scripts are available there:
Sellar Problem
: Small two-disciplinary MDO problem based on MDO literature.TU Delft Wing Design
: The wing design case described here was developed at TU Delft and takes a variety of different disciplines into account.
Graph¶
Below the KADMOS KadmosGraph class and its subclasses are listed.
KadmosGraph¶
-
class
kadmos.graph.graph_kadmos.
KadmosGraph
(*args, **kwargs)¶ -
add_default_description
()¶ Method to add a default description attribute to a graph
Returns: graph with default attribute description Return type: KadmosGraph
-
add_default_name
()¶ Method to add a default name attribute to a graph
Returns: graph with default attribute name Return type: KadmosGraph
-
add_edges_from
(ebunch, **attr)¶ Add all the edges in ebunch.
- ebunch : container of edges
- Each edge given in the container will be added to the graph. The edges must be given as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a dictionary containing edge data.
- attr : keyword arguments, optional
- Edge data (or labels or objects) can be assigned using keyword arguments.
add_edge : add a single edge add_weighted_edges_from : convenient way to add weighted edges
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples >>> e = zip(range(0, 3), range(1, 4)) >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
Associate data to edges
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3) >>> G.add_edges_from([(3, 4), (1, 4)], label='WN2898')
-
add_equation
(edge_or_node, equation, language='Python')¶ Method to add an equation to an output edge.
Parameters: - edge_or_node (list, str) – graph edge or node under consideration.
- equation (str) – equation to be added
- language (str) – equation language used for the equation
-
add_equation_label
(edge, labeling_method='node_label', language='Python')¶ Method to add an equation label to a edge that can (safely) be used as reference in an equation.
Parameters: - edge (str) – graph edge under consideration
- labeling_method (str) – select method for automatic label string determination (node_id or node_label)
- language (str) – equation language used for the equation label
Returns: label
Return type: str
-
add_equation_labels
(nodes, language='Python', labeling_method='node_id')¶ Method to add equation labels automatically to all input edges connected to the specified list of nodes
Parameters: - nodes (list) – list of nodes
- language (str) – equation language used for the equation label
- labeling_method (str) – select method for automatic label string determination (node_id or node_label)
-
add_nodes_from
(nodes, **attr)¶ Add multiple nodes.
- nodes : iterable container
- A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
- attr : keyword arguments, optional (default= no attributes)
- Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple take precedence over attributes specified via keyword arguments.
add_node
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_nodes_from('Hello') >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)]) >>> G.add_nodes_from(K3) >>> sorted(G.nodes(), key=str) [0, 1, 2, 'H', 'e', 'l', 'o']
Use keywords to update specific node attributes for every node.
>>> G.add_nodes_from([1, 2], size=10) >>> G.add_nodes_from([3, 4], weight=0.4)
Use (node, attrdict) tuples to update attributes for specific nodes.
>>> G.add_nodes_from([(1, dict(size=11)), (2, {'color':'blue'})]) >>> G.nodes[1]['size'] 11 >>> H = nx.Graph() >>> H.add_nodes_from(G.nodes(data=True)) >>> H.nodes[1]['size'] 11
-
add_objective_function_by_nodes
(*args, **kwargs)¶ This function adds objective functions to the graph using lists of variable nodes.
Each list produces a separate objective function node in the graph. If the list if passed as a keyword argument, the keyword is taken as the name of the objective function node. Otherwise, a standard name will be given to the node. Each objective function node has one output variable, and takes the nodes given in the argument list as input nodes.
If the provided nodes do not exist in the graph, a warning is given to the user on whether to continue the addition of the objective function to the graph using valid nodes.
Example: unnamed_function = list(>>list of graph nodes<<) named_obj_fcn = list(>>list of graph nodes<<) MyGraph.add_objective_function_by_nodes(unnamed_function, My_obj_fcn_name = named_obj_fcn)
The added objective function nodes can be queried by the attribute Graph.node[node][“name”] == “Objective”.
Parameters: - args (list) – list of nodes (list elements must be strings)
- kwargs (list) – list of nodes (list elements must be strings)
Returns: list of Objective Functions added to Graph
Return type: list
-
add_weighted_edges_from
(ebunch, weight='weight', **attr)¶ Add all the weighted edges in ebunch with specified weights.
- ebunch : container of edges
- Each edge in the container is added to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number.
- weight : string, optional (default= ‘weight’)
- The attribute name for the edge weights to be added.
- attr : keyword arguments, optional (default= no attributes)
- Edge attributes to add/update for all edges.
add_edge : add a single edge add_edges_from : add multiple edges
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph, duplicate edges are stored.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
-
adj
¶ Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So G.adj[3][2][‘color’] = ‘blue’ sets the color of the edge (3, 2) to “blue”.
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in G[node].data(‘foo’, default=1): works.
For directed graphs, G.adj holds outgoing (successor) info.
-
adjacency
()¶ Return an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
- adj_iter : iterator
- An iterator over (node, adjacency dictionary) for all nodes in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [(n, nbrdict) for n, nbrdict in G.adjacency()] [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
-
adjlist_inner_dict_factory
¶ alias of
dict
-
adjlist_outer_dict_factory
¶ alias of
dict
-
change_graph_class
(graph_class)¶ Method to adjust the class of a graph.
-
check
(raise_error=False)¶ Method to check the graph for validity and completeness.
Several checks are performed. However the method does not guarantee the validity of the graph.
The checks are split into several categories and the methods _check_category_a, _check_category_b and _check_category_c are used to determine the overall validity and completeness. These sub methods are generally defined below and are then further refined in child classes.
Parameters: raise_error (bool) – determines if an error should be raised in case of an invalid graph Returns: result of the check Return type: bool
-
check_cmdows_integrity
(convention=True, mpg=None)¶ Method to check the integrity of the CMDOWS file that can be created with the save method.
The integrity check is graph specific and thus needs to be executed for every graph before saving as CMDOWS if one wants to be sure that the CMDOWS file is integer. Due to its relative long runtime this check is however not performed automatically when using the save method.
Parameters: - convention (bool) – option for applying a UID convention
- mpg (MdaoProcessGraph) – MPG to be saved together with graph
Returns: check result
Return type: bool
-
check_for_coupling
(function_order, only_feedback=False, raise_error_if_true=False)¶ Function to check for the presence of coupling in a graph for a list of analyses in a given analysis order.
Note that only the functions in the function_order list are checked for feedback.
Parameters: - function_order (list) – list with node names of functions
- only_feedback (bool) – Boolean on whether to check for feedback coupling only (this is useful for Gauss-Seidel)
- raise_error_if_true (bool) – Boolean on whether to raise an error if coupling exists
Returns: Boolean value on whether coupling exists
Return type: bool
-
clear
()¶ Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.clear() >>> list(G.nodes) [] >>> list(G.edges) []
-
copy
(as_view=False)¶ Return a copy of the graph.
The copy method by default returns a shallow copy of the graph and attributes. That is, if an attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for new containers.
If as_view is True then a view is returned instead of a copy.
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four types of copies of a graph that people might want.
Deepcopy – The default behavior is a “deepcopy” where the graph structure as well as all data attributes and any objects they might contain are copied. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s copy.deepcopy)
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph attribute dicts are references to those in the original graph. This saves time and memory but could cause confusion if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the attributes. That is, any attributes that are containers are shared between the new graph and the original. This is exactly what dict.copy() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5) >>> H = G.copy() >>> H = G.copy(as_view=False) >>> H = nx.Graph(G) >>> H = G.fresh_copy().__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not enabled. Instead use:
>>> H = G.fresh_copy() >>> H.add_nodes_from(G) >>> H.add_edges_from(G.edges)
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
- as_view : bool, optional (default=False)
- If True, the returned graph-view provides a read-only view of the original graph without actually copying any data.
- G : Graph
- A copy of the graph.
to_directed: return a directed copy of the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.copy()
-
copy_as
(graph_class, as_view=False)¶ Method to make a copy of a graph and make it into another KADMOS graph class.
Returns: copy of the graph Return type: KadmosGraph
-
copy_edge
(old_edge, new_edge)¶ Method to copy an edge so that attributes of the old edge are maintained.
Parameters: - old_edge (tuple) – edge to be copied
- new_edge (tuple) – edge to be created
Returns: created edge
Return type: tuple
-
copy_node_with_suffix
(node, suffix, label_extension, **kwargs)¶ Method to simply copy a node and its attributes by creating a new node with a suffix.
Parameters: - node (str) – node to be copied
- suffix (str) – suffix to be added to the node ID
- label_extension (str) – extension for labels
- kwargs (dict) – keyword arguments will be added as node attributes
Returns: new node name and enriched graph
Return type: str
-
count_function_nodes
()¶ This function counts the amount function nodes that are present in the graph.
Returns: amount of function nodes counted in graph Return type: int
-
create_dsm
(file_name, destination_folder=None, open_pdf=False, mpg=None, include_system_vars=True, summarize_vars=False, function_order=None, keep_tex_file=False, abbreviate_keywords=False, compile_pdf=True, colors_based_on='problem_roles')¶ Method to create a (X)DSM PDF file
Parameters: - file_name (str) – name of the file to be saved
- destination_folder (str) – destination folder for the file to be saved
- open_pdf (bool) – option for opening the created file directly
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG as XDSM (if None a DSM is created)
- include_system_vars (bool) – option for including system variables (only applicable for DSMs)
- summarize_vars (bool) – option for summarizing label
- function_order (list) – optional function order for the diagonal of the graph (only applicable for DSMs)
- keep_tex_file (bool) – optional argument to keep the tex file of the PDF
- abbreviate_keywords (bool) – optional argument to keep make keywords shorter (input -> inp., output -> outp.)
- compile_pdf (bool) – optional argument to compile the PDF
- colors_based_on (str) – option to base the colors either on the problem role or the partitions
-
deepcopy
()¶ Method to make a deep copy of a graph.
Returns: deepcopy of the graph Return type: KadmosGraph
-
deepcopy_as
(graph_class)¶ Method to make a deep copy of a graph and make it into another KADMOS graph class.
Returns: deepcopy of the graph Return type: KadmosGraph
-
degree
¶ A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- weight : string or None, optional (default=None)
- The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
If a single node is requested deg : int
Degree of the nodeOR if multiple nodes are requested nd_iter : iterator
The iterator returns two-tuples of (node, degree).in_degree, out_degree
>>> G = nx.DiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.degree(0) # node 0 with degree 1 1 >>> list(G.degree([0, 1, 2])) [(0, 1), (1, 2), (2, 2)]
-
disconnect_problematic_variables_from
(function, disconnect_collided_targets=True, disconnect_shared_sources=True, ignore_list=[])¶ Method to automatically disconnect certain problematic variables with respect to a given function.
If given as setting (disconnect_collided_targets=True) then the collided targets will be disconnected from this function. Also, if given as setting (disconnect_shared_sources=True), shared sources are also disconnected.
Parameters: - function (basestring) – function around which problematic variables are disconnected
- disconnect_collided_targets (bool) – setting to disconnect collided targets
- disconnect_shared_sources (list) – setting to disconnect shared sources
- disconnect_shared_sources – setting to ignore certain nodes
-
edge_attr_dict_factory
¶ alias of
dict
-
edge_subgraph
(edges)¶ Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
- edges : iterable
- An iterable of edges in this graph.
- G : Graph
- An edge-induced subgraph of this graph with the same edge attributes.
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
>>> G = nx.path_graph(5) >>> H = G.edge_subgraph([(0, 1), (3, 4)]) >>> list(H.nodes) [0, 1, 3, 4] >>> list(H.edges) [(0, 1), (3, 4)]
-
edges
¶ An OutEdgeView of the DiGraph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges.data(‘color’, default=’red’): iterates through all the edges yielding the color attribute with default ‘red’ if no color attribute exists.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- data : string or bool, optional (default=False)
- The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).
- default : value, optional (default=None)
- Value used for edges that dont have the requested attribute. Only relevant if data is not True or False.
- edges : OutEdgeView
- A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].
in_edges, out_edges
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
>>> G = nx.DiGraph() # or MultiDiGraph, etc >>> nx.add_path(G, [0, 1, 2]) >>> G.add_edge(2, 3, weight=5) >>> [e for e in G.edges] [(0, 1), (1, 2), (2, 3)] >>> G.edges.data() # default data is {} (empty dict) OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]) >>> G.edges.data('weight', default=1) OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)]) >>> G.edges([0, 2]) # only edges incident to these nodes OutEdgeDataView([(0, 1), (2, 3)]) >>> G.edges(0) # only edges incident to a single node (use G.adj[0]?) OutEdgeDataView([(0, 1)])
-
find_all_nodes
(category='all', subcategory='all', attr_cond=None, attr_include=None, attr_exclude=None, xpath_include=None, xpath_exclude=None, print_in_log=False, print_attributes='all')¶ Advanced search function to get nodes and their properties.
Parameters: - category (str) – category of the node (you can specify multiple in a list), see note for allowed values.
- subcategory (str) – subcategory of the node (you can specify multiple in a list), see note for allowed values.
- attr_cond (list) – conditional on the node attribute value (e.g. [‘execution time’,’>’,200])
- attr_include (list) – attributes to exclusively include in search
- attr_exclude (list) – attributes to exclude from search
- xpath_include (list) – xpaths to exclusively include in search
- xpath_exclude (list) – xpaths to exclude from search
- print_in_log (bool) – parameter to set printing in log on or off
- print_attributes (str or list) – attributes that should be printed in the log
Returns: list of all nodes that meet the search criteria
Return type: list
Note
The following categories are allowed:
- all
- variable
- variable group
- function
- architecture element
- RCE component
Note
The following subcategories are allowed:
GROUPS:
- all
- all variables
- all inputs
- all outputs
- all couplings
- all circular variables
- all PSG blocks
- all iterative blocks
- all design variables
VARIABLES:
- hole
- supplied input
- supplied shared input
- output
- collision
- coupling
- pure circular coupling
- shared coupling
- shared circular coupling
- collided coupling
- collided circular coupling
- collided shared coupling
- collided shared circular coupling
VARIABLE GROUPS:
- hole group
- supplied input group
- supplied shared input group
- output group
- coupling group
- shared coupling group
FUNCTIONS:
- hole
- inputless
- outputless
- complete
ARCHITECTURE ELEMENTS:
Action blocks:
- optimizer
- MDA
- optimizer function
- MDA analysis
- independent output function
Parameters:
- initial guess design variable
- final design variable
- final output variable
- MDA coupling variable
- initial guess MDA coupling variable
- final MDA coupling variable
- consistency constraint variable
RCE COMPONENTS:
- Input Provider
- XML Merger
- XML PyMerger
- CPACS Tool
- Converger
- Optimizer
- Consistency constraint function
Example usage: Just get all nodes of a graph in a list:
>>> all_nodes = self.find_all_nodes()
Get all input nodes in a list and print them in the log as well:
>>> all_nodes = self.find_all_nodes(category='all', subcategory='all inputs', print_in_log=True)
Get all input nodes with a certain attribute value:
>>> all_nodes = self.find_all_nodes(category='all', subcategory='all inputs', >>> attr_cond=['execution time', '>', 5], print_in_log=True)
Get all nodes with any of the listed attribute values:
>>> all_nodes = self.find_all_nodes(category='all', subcategory='all', >>> attr_include=[['problem_role'['constraint','objective']],['instance', 1]])
-
fresh_copy
()¶ Return a fresh copy graph with the same data structure.
A fresh copy has no nodes, edges or graph attributes. It is the same data structure as the current graph. This method is typically used to create an empty version of the graph.
If you subclass the base class you should overwrite this method to return your class of graph.
-
get_adjacency_matrix
(print_in_log=True)¶ Function to determine the adjacency matrix of a graph.
Parameters: print_in_log (bool) – option for printing the results Returns: different methods of storing the same adjacency matrix in one dictionary Return type: dict
-
get_architecture_node_ids
(mdao_architecture, number_of_groups=None)¶ Method to get the IDs of architecture nodes specific for a certain MDAO architecture.
Parameters: - mdao_architecture (basestring) – specified architecture (CO, BLISS-2000, etc)
- number_of_groups (int, None) – number of subgroups in distributed architectures
Returns: node IDs
Return type: tuple
-
get_architecture_node_labels
(mdao_architecture, number_of_groups=None)¶ Method to get the labels of architecture nodes specific for a certain MDAO architecture.
Parameters: - mdao_architecture (basestring) – specified architecture (CO, BLISS-2000, etc)
- number_of_groups (int, None) – number of subgroups in distributed architectures
Returns: node labels
Return type: tuple
-
get_categorized_nodes
(print_in_log=False)¶ Function that returns a dictionary with graph nodes grouped according to category and subcategory.
Parameters: print_in_log (bool) – option for printing the categories Returns: dictionary with analysis results Return type: dict
-
get_contracted_graph
(contraction_level)¶ This function contracts the nodes of a graph to the provided contraction level.
The contraction level refers to the xpath-level, which represents the position of the descendant with respect to its predecessors. The example below represents a level 3 node, with “cpacs” being at level zero.
/cpacs/aircraft/wings/wing
-cpacs |—-aircraft |——–wings |————wing
All nodes above the contraction level are removed from the graph and replaced by a “variable group” node, which groups the removed nodes in a node at contraction level. This allows for a “de-cluttering” of the graph, with the graph connections still being represented.
Parameters: contraction_level – int from 0 (highest level) to X (lowest level existing in XML schema) Returns: contracted_graph: graph with contracted nodes
-
get_direct_coupling_nodes
(*args, **kwargs)¶ This method returns the direct couplings between two nodes in a graph.
This method is specifically written (and tested) with function nodes in mind. Direct coupling is defined as coupling with between two nodes through a third node.
In this function, each combination between the provided arguments is tested for couplings (in pairs). First, the two nodes in each pair are checked for common neighbors. If they do, the edges of the common neighbors are iterated to determine whether the node-pair is connected to each other, or only the neighbor. The direction of the coupling is also checked.
Example:
The connection
F1 —> N1 —> F2
leads to
[(F1, F2, N1)]
Parameters: - args (str, list) – nodes to be checked for couplings; at least two must be provided
- kwargs (direction: str) – print_couplings: option for printing all couplings with coupling direction and node (optional)
- kwargs – direction: set only coupling in certain direction (optional)
Returns: couplings: list of tuples containing the coupled nodes and the coupling node
Return type: list
-
get_edge_data
(u, v, default=None)¶ Return the attribute dictionary associated with edge (u, v).
This is identical to G[u][v] except the default is returned instead of an exception is the edge doesn’t exist.
u, v : nodes default: any Python object (default=None)
Value to return if the edge (u, v) is not found.- edge_dict : dictionary
- The edge attribute dictionary.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G[0][1] {}
Warning: Assigning to G[u][v] is not permitted. But it is safe to assign attributes G[u][v][‘foo’]
>>> G[0][1]['weight'] = 7 >>> G[0][1]['weight'] 7 >>> G[1][0]['weight'] 7
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.get_edge_data(0, 1) # default edge data is {} {} >>> e = (0, 1) >>> G.get_edge_data(*e) # tuple form {} >>> G.get_edge_data('a', 'b', default=0) # edge not in graph, return 0 0
-
get_function_graph
(keep_objective_variables=False)¶ Method for replacing variable nodes by function connections.
This function removes all variable nodes from the graph and replaces the variable connections of each function with function connections, such that
F(1) —-> N(1) —-> F(2) —-> N(2) —-> F(3)
becomes
F(1) —-> F(2) —-> F(3),
where N(i) is a variable node, and F(i) a function node.
Param: keep_objective_variables: if given the objective variables will remain in graph Type: keep_objective_variables: bool Returns: new graph without variable nodes
-
get_function_metadata
(node)¶ Function to get the node metadata in a list (used in the dynamic visualization package).
Parameters: node (basestring) – function node to collect the metadata for. Returns: list with metadata Return type: list
-
get_function_nodes
()¶ This function returns a list of all function nodes in the graph.
-
get_graph_properties
(*args)¶ This function retrieves the properties of a graph.
If no argument is given, the standard list of properties GRAPH_PROPERTIES is analyzed and their values are returned in a dict. If arguments are given, only this list will be used as standard list of properties.
Param: args: specific properties to be retrieved (optional) Returns: dictionary containing the properties of the graph Return type: dict
-
get_node_attributes
(node, attr_list, print_in_log=False)¶ Function to get and print certain attributes of a node from the graph.
Parameters: - node (str) – node name
- attr_list (list) – list with attributes to be pulled
- print_in_log (bool) – option for printing to log
Returns: dictionary with node attributes
Return type: dict
-
get_node_subcategory
(node)¶ Method to analyse a node and to update the subcategory attribute of the node.
The following table illustrates how the subcategory is determined based on the category, indegree and outdegree:
CATEGORY OF NODE SUBCATEGORY INDEGREE OUTDEGREE variable hole 0 0 supplied input 0 1 supplied shared input 0 >1 output 1 0 collision >1 0 - coupling
- or
pure circular coupling
1 1 - shared coupling
- or
shared circular coupling
1 >1 - collided coupling
- or
collided circular coupling
>1 1 - collided shared coupling
- or
collided shared circular coupling
>1 >1 function hole 0 0 inputless 0 >0 outputless >0 0 complete >0 >0 Parameters: node (basestring) – node in the graph Returns: subcategory of the node Return type: basestring
-
get_nodes_based_on_strings
(*args, **kwargs)¶ This function enables the user to search graph nodes for specific strings.
Each provided string will be searched for, and if multiple node are found for each string, the user will be able to select the ones desired. The other matched nodes are disregarded.
Parameters: - args (str) – strings that graph nodes being searched for
- kwargs (include_all: bool) – include_all: If include_all is set to True, all matching nodes are added to returned list
Returns: matching nodes that user selected (all if include_all is True)
-
get_nodes_indegree
()¶ Function to get the indegree of all the graph nodes and store them in a dictionary.
Returns: dictionary with node name key and indegree integer value. Return type: dict
-
get_nodes_outdegree
()¶ Function to get the outdegree of all the graph nodes and store them in a dictionary.
Returns: dictionary with node name key and outdegree integer value. Return type: dict
-
get_nodes_subcategory
()¶ Method to analyse all nodes and to update the subcategory attributes of the nodes.
-
get_number_of_couplings
(node)¶ This function returns the number of couplings of a node in the graph.
Parameters: node – input node Returns: number of couplings for the input node Type: int
-
get_same_graph_class
(graph, copy_type='deep')¶ Method to reinstantiate a given graph according to the same graph class as the self.
Parameters: - graph (DiGraph) – graph object to be reinstantiated
- copy_type (basestring) – setting to have a deep or shallow copy of the graph
Returns: reinstantiated graph
Return type:
-
get_sources
(node)¶ Function to determine the sources of a given node.
Parameters: node (basestring) – node for which sources should be found Returns: list with sources Return type: list
-
get_subgraph_by_function_nodes
(*args, **kwargs)¶ This function retrieves a subgraph from the original graph only containing the argument nodes.
All arguments must be found in the graph.
Parameters: - args (list, str) – arbitrary amount of graph nodes
- kwargs (copy_type: str) – copy_type: type of copy (clean or deep)
Returns: sub-graph only containing nodes provided as arguments, and their edges
-
get_system_inputs
(*args, **kwargs)¶ This method checks whether there are system inputs in the graph using the function nodes provided.
The function nodes should be provided in the args. If system inputs exist they are returned.
Parameters: args – function nodes Returns: system input nodes dictionary Return type: dict
-
get_targets
(node)¶ Function to determine the targets of a given node.
Parameters: node (basestring) – node for which targets should be found Returns: list with targets Return type: list
-
has_edge
(u, v)¶ Return True if the edge (u, v) is in the graph.
This is the same as v in G[u] without KeyError exceptions.
- u, v : nodes
- Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects.
- edge_ind : bool
- True if edge is in the graph, False otherwise.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.has_edge(0, 1) # using two nodes True >>> e = (0, 1) >>> G.has_edge(*e) # e is a 2-tuple (u, v) True >>> e = (0, 1, {'weight':7}) >>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary) True
The following syntax are equivalent:
>>> G.has_edge(0, 1) True >>> 1 in G[0] # though this gives KeyError if 0 not in G True
-
has_node
(n)¶ Return True if the graph contains the node n.
Identical to n in G
n : node
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.has_node(0) True
It is more readable and simpler to use
>>> 0 in G True
-
has_nodes
(nodes)¶ Function that checks whether all nodes given in a list are present in the graph.
Parameters: nodes (list) – list of nodes to be checked Returns: boolean whether all nodes have been found Return type: bool
-
has_predecessor
(u, v)¶ Return True if node u has predecessor v.
This is true if graph has the edge u<-v.
-
has_successor
(u, v)¶ Return True if node u has successor v.
This is true if graph has the edge u->v.
-
in_degree
¶ An InDegreeView for (node, in_degree) or in_degree for single node.
The node in_degree is the number of edges pointing to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iteration over (node, in_degree) as well as lookup for the degree for a single node.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- weight : string or None, optional (default=None)
- The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
If a single node is requested deg : int
In-degree of the nodeOR if multiple nodes are requested nd_iter : iterator
The iterator returns two-tuples of (node, in-degree).degree, out_degree
>>> G = nx.DiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.in_degree(0) # node 0 with degree 0 0 >>> list(G.in_degree([0, 1, 2])) [(0, 0), (1, 1), (2, 1)]
-
in_edges
¶ An InEdgeView of the Graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, default=None):
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- data : string or bool, optional (default=False)
- The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).
- default : value, optional (default=None)
- Value used for edges that dont have the requested attribute. Only relevant if data is not True or False.
- in_edges : InEdgeView
- A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].
edges
-
inspect
()¶ Method to print an overview of the graph.
-
inspect_node
(node)¶ Method to print a node with details.
Parameters: node (str) – node
-
inspect_nodes
(list_of_nodes)¶ Method to inspect a list of nodes with details.
Parameters: list_of_nodes (list) – node list
-
is_directed
()¶ Return True if graph is directed, False otherwise.
-
is_multigraph
()¶ Return True if graph is a multigraph, False otherwise.
-
make_all_variables_valid
()¶ Method to analyze all variables in a graph and make any problematic variables valid.
Problematic variable are holes and splittables. Splittable variables are split and holes will simply be removed.
-
merge_function_modes
(*args, **kwargs)¶ Function to contract certain modes of the same function.
Parameters: - args (str) – function (first arg) and then followed by modes to be contracted.
- kwargs (dict or str) – new_label to specify new node label manually (optional)
Returns: contracted graph
Return type:
-
merge_function_nodes_based_on_modes
(merge_funcs=None)¶ This class method merges all execution modes of the same function into a single node.
Mainly used for illustration purposes since information on the execution modes gets lost.
Parameters: merge_funcs – List of tuple of functions to merge. If empty (default), all functions are merged. Functions must be present in graph. :type merge_funcs: list, tuple :return: merged graph
-
merge_functions
(*args, **kwargs)¶ Function to merge a collection of functions.
Parameters: - args (node_ids) – functions to be merged
- kwargs (dict) – new_label to specify new node label manually (optional)
-
merge_parallel_functions
(*args, **kwargs)¶ Function to merge a list of functions
Parameters: - args (node_ids) – functions to be merged
- kwargs (dict) – new_label to specify new node label manually (optional)
-
merge_sequential_functions
(*args, **kwargs)¶ Function to merge a collection of functions.
It is assumed that the merged functions are actually executed in the sequence in which they are given to this function.
Parameters: - args (node_ids) – functions to be merged in the given sequence
- kwargs (str) – new_label to specify new node label manually (optional)
-
name
¶ String identifier of the graph.
This graph attribute appears in the attribute dict G.graph keyed by the string “name”. as well as an attribute (technically a property) G.name. This is entirely user controlled.
-
nbunch_iter
(nbunch=None)¶ Return an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- niter : iterator
- An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate over all nodes in the graph.
- NetworkXError
- If nbunch is not a node or or sequence of nodes. If a node in nbunch is not hashable.
Graph.__iter__
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a
NetworkXError
is raised. Also, if any object in nbunch is not hashable, aNetworkXError
is raised.
-
neighbors
(n)¶ Return an iterator over successor nodes of n.
neighbors() and successors() are the same.
-
node
¶ A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for set-like operations. Can also be used as G.nodes(data=’color’, default=None) to return a NodeDataView which reports specific node data but no set operations. It presents a dict-like interface as well with G.nodes.items() iterating over (node, nodedata) 2-tuples and G.nodes[3][‘foo’] providing the value of the foo attribute for node 3. In addition, a view G.nodes.data(‘foo’) provides a dict-like interface to the foo attribute of each node. G.nodes.data(‘foo’, default=1) provides a default for nodes that do not have attribute foo.
- data : string or bool, optional (default=False)
- The node attribute returned in 2-tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.
- default : value, optional (default=None)
- Value used for nodes that dont have the requested attribute. Only relevant if data is not True or False.
- NodeView
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.
If your node data is not needed, it is simpler and equivalent to use the expression
for n in G
, orlist(G)
.There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time='5pm') >>> G.nodes[0]['foo'] = 'bar' >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes.data()) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data='foo')) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes.data('foo')) [(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time')) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes.data('time')) [(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data='time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')] >>> list(G.nodes.data('time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data='weight', default=1)) {0: 1, 1: 2, 2: 3}
-
node_dict_factory
¶ alias of
dict
-
node_is_function
(node)¶ Function that checks whether a node is a function node or not.
Parameters: node (str) – node in graph Returns: check result Return type: bool
-
node_is_hole
(node)¶ Function that checks whether a node is a hole (unconnected).
Parameters: node (str) – node in graph Returns: check result Return type: bool
-
node_is_objective_function
(node)¶ This function checks whether the provided node is a objective function.
- This function checks whether the provided node:
- exists in graph
- has name-attribute “Objective”
- has an out-degree of 1
- has an outgoing node with an out-degree of zero # TODO: THIS IS WRONG!
Only if all checks are satisfied, is the node a valid objective function node.
Parameters: node (str) – graph node to be tested Returns: check result Return type: bool
-
node_is_output
(node)¶ Function that checks whether a node is a system output.
Parameters: node (str) – node in graph Returns: check result Return type: bool
-
node_is_variable
(node)¶ Function that checks whether a node is a variable node or not.
Parameters: node (str) – node in graph Returns: check result Return type: bool
-
nodes
¶ A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for set-like operations. Can also be used as G.nodes(data=’color’, default=None) to return a NodeDataView which reports specific node data but no set operations. It presents a dict-like interface as well with G.nodes.items() iterating over (node, nodedata) 2-tuples and G.nodes[3][‘foo’] providing the value of the foo attribute for node 3. In addition, a view G.nodes.data(‘foo’) provides a dict-like interface to the foo attribute of each node. G.nodes.data(‘foo’, default=1) provides a default for nodes that do not have attribute foo.
- data : string or bool, optional (default=False)
- The node attribute returned in 2-tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.
- default : value, optional (default=None)
- Value used for nodes that dont have the requested attribute. Only relevant if data is not True or False.
- NodeView
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.
If your node data is not needed, it is simpler and equivalent to use the expression
for n in G
, orlist(G)
.There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time='5pm') >>> G.nodes[0]['foo'] = 'bar' >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes.data()) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data='foo')) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes.data('foo')) [(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time')) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes.data('time')) [(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data='time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')] >>> list(G.nodes.data('time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data='weight', default=1)) {0: 1, 1: 2, 2: 3}
-
number_of_edges
(u=None, v=None)¶ Return the number of edges between two nodes.
- u, v : nodes, optional (default=all edges)
- If u and v are specified, return the number of edges between u and v. Otherwise return the total number of all edges.
- nedges : int
- The number of edges in the graph. If nodes u and v are specified return the number of edges between those nodes. If the graph is directed, this only returns the number of edges from u to v.
size
For undirected graphs, this method counts the total number of edges in the graph:
>>> G = nx.path_graph(4) >>> G.number_of_edges() 3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1) 1
For directed graphs, this method can count the total number of directed edges from u to v:
>>> G = nx.DiGraph() >>> G.add_edge(0, 1) >>> G.add_edge(1, 0) >>> G.number_of_edges(0, 1) 1
-
number_of_nodes
()¶ Return the number of nodes in the graph.
- nnodes : int
- The number of nodes in the graph.
order, __len__ which are identical
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> len(G) 3
-
order
()¶ Return the number of nodes in the graph.
- nnodes : int
- The number of nodes in the graph.
number_of_nodes, __len__ which are identical
-
out_degree
¶ An OutDegreeView for (node, out_degree)
The node out_degree is the number of edges pointing out of the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator over (node, out_degree) as well as lookup for the degree for a single node.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- weight : string or None, optional (default=None)
- The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
If a single node is requested deg : int
Out-degree of the nodeOR if multiple nodes are requested nd_iter : iterator
The iterator returns two-tuples of (node, out-degree).degree, in_degree
>>> G = nx.DiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.out_degree(0) # node 0 with degree 1 1 >>> list(G.out_degree([0, 1, 2])) [(0, 1), (1, 1), (2, 1)]
-
out_edges
¶ An OutEdgeView of the DiGraph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges.data(‘color’, default=’red’): iterates through all the edges yielding the color attribute with default ‘red’ if no color attribute exists.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- data : string or bool, optional (default=False)
- The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).
- default : value, optional (default=None)
- Value used for edges that dont have the requested attribute. Only relevant if data is not True or False.
- edges : OutEdgeView
- A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].
in_edges, out_edges
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
>>> G = nx.DiGraph() # or MultiDiGraph, etc >>> nx.add_path(G, [0, 1, 2]) >>> G.add_edge(2, 3, weight=5) >>> [e for e in G.edges] [(0, 1), (1, 2), (2, 3)] >>> G.edges.data() # default data is {} (empty dict) OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]) >>> G.edges.data('weight', default=1) OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)]) >>> G.edges([0, 2]) # only edges incident to these nodes OutEdgeDataView([(0, 1), (2, 3)]) >>> G.edges(0) # only edges incident to a single node (use G.adj[0]?) OutEdgeDataView([(0, 1)])
-
plot_adjacency_matrix
(fig_num=1, fig_size=(7, 7), show_now=True)¶ Draw the adjacency matrix in a plot window.
Parameters: - fig_num – figure number
- fig_size – figure size
- show_now – Boolean whether to plot directly (pausing the execution until the plot is closed), or not.
-
plot_graph
(fig_num=1, color_setting='default', positioning='circular', save_as=None, show_now=True, title=None, edge_label=False)¶ Function to plot a graph.
Note that you need to add matplotlib.pyplot.show() at the end of your code to see the plot window.
Parameters: - fig_num – figure number
- fig_size – size of figure window
- color_setting – choose from ‘default’, ‘sinks’, ‘categories’, ‘partitions’
- positioning – choose from ‘circular’, ‘spring’
- save_as – save plot as figure file
- show_now – Boolean whether to plot directly (pausing the execution until the plot is closed), or not.
- title – title string of the graph
- edge_label – edge attribute that will be shown for each edge in graph
Returns: window with plot
-
pred
¶ Graph adjacency object holding the predecessors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So G.pred[2][3][‘color’] = ‘blue’ sets the color of the edge (3, 2) to “blue”.
Iterating over G.pred behaves like a dict. Useful idioms include for nbr, datadict in G.pred[n].items():. A data-view not provided by dicts also exists: for nbr, foovalue in G.pred[node].data(‘foo’): A default can be set via a default argument to the data method.
-
predecessors
(n)¶ Return an iterator over predecessor nodes of n.
-
print_graph
(use_pretty_print=False)¶ Function to print the full graph.
Parameters: use_pretty_print (bool) – Boolean on whether to use pretty print for node and edge attributes
-
relabel_function_nodes
(mapping=None)¶ Method to relabel all function nodes so that they meet the CMDOWS convention ID[modeID][instanceID][version]
-
remove_edge
(u, v)¶ Remove the edge between u and v.
- u, v : nodes
- Remove the edge between nodes u and v.
- NetworkXError
- If there is not an edge between u and v.
remove_edges_from : remove a collection of edges
>>> G = nx.Graph() # or DiGraph, etc >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.remove_edge(0, 1) >>> e = (1, 2) >>> G.remove_edge(*e) # unpacks e from an edge tuple >>> e = (2, 3, {'weight':7}) # an edge with attribute data >>> G.remove_edge(*e[:2]) # select first part of edge tuple
-
remove_edges_from
(ebunch)¶ Remove all edges specified in ebunch.
- ebunch: list or container of edge tuples
Each edge given in the list or container will be removed from the graph. The edges can be:
- 2-tuples (u, v) edge between u and v.
- 3-tuples (u, v, k) where k is ignored.
remove_edge : remove a single edge
Will fail silently if an edge in ebunch is not in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> ebunch = [(1, 2), (2, 3)] >>> G.remove_edges_from(ebunch)
-
remove_function_nodes
(*args)¶ Function that removes a function node
Also the input and output variables that only have links to this specific function node are deleted. A simple remove_node of a function node might lead to unconnected variables in the graph.
Parameters: args (str or list) – function node id(s)
-
remove_node
(n)¶ Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
- n : node
- A node in the graph
- NetworkXError
- If n is not in the graph.
remove_nodes_from
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> list(G.edges) [(0, 1), (1, 2)] >>> G.remove_node(1) >>> list(G.edges) []
-
remove_nodes_from
(nodes)¶ Remove multiple nodes.
- nodes : iterable container
- A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it is silently ignored.
remove_node
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = list(G.nodes) >>> e [0, 1, 2] >>> G.remove_nodes_from(e) >>> list(G.nodes) []
-
reverse
(copy=True)¶ Return the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
- copy : bool optional (default=True)
- If True, return a new DiGraph holding the reversed edges. If False, the reverse graph is created using a view of the original graph.
-
save
(file_name, file_type='kdms', graph_check_critical=True, destination_folder=None, mpg=None, description='', creator='', version='1.0', timestamp=datetime.datetime(2018, 3, 29, 18, 16, 26, 304335), keep_empty_elements=False, pretty_print=False, convention=True, integrity=False)¶ Method to save the graph.
Different output file types are implemented for saving graphs. They are listed in the following. kdms: the most simple file type which makes use of pickling cmdows: the most versatile file type especially suited for file exchange with other tools graphml: another file type especially suited for file exchange with other tools based on graphs
Parameters: - file_name (str) – name of the file to be saved
- file_type (str) – file_type
- graph_check_critical (bool) – option for raising errors in case of an invalid graph
- destination_folder (str) – destination folder for the file to be saved
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG
- description (str) – description of the file (only applicable for the cmdows file type)
- creator (str) – name of the creator of the file (only applicable for the cmdows file type)
- version (str | float | int) – version of the file (only applicable for the cmdows file type)
- timestamp (datetime) – timestamp to be saved in the file (only applicable for the cmdows file type)
- keep_empty_elements (bool) – option for keeping empty XML elements (only applicable for the cmdows file type)
- pretty_print (bool) – option for pretty XML printing (only applicable for the cmdows file type)
- convention (bool) – option for appyling a UID convention (only applicable for the cmdows file type)
- integrity (bool) – option for doing an integrity file check (only applicable for the cmdows file type)
-
select_objectives_from_graph
(*args)¶ This functions lets the user select one or more objective functions from the graph.
Only functions can be selected as objectives. If no arguments are provided, user is prompted to select an objective from all functions in graph.
Param: args: objective functions to choose from Returns: list of objective functions
-
size
(weight=None)¶ Return the number of edges or total of all edge weights.
- weight : string or None, optional (default=None)
- The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.
- size : numeric
The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are more general).
number_of_edges
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.size() 3
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge('a', 'b', weight=2) >>> G.add_edge('b', 'c', weight=4) >>> G.size() 2 >>> G.size(weight='weight') 6.0
-
split_variables
(*args, **kwargs)¶ Method to split a problematic variable node into multiple separate valid nodes.
The following variables are considered problematic and will be handled by this function:
- pure circular coupling
- shared circular coupling
- collided coupling
- collision
- collided circular coupling
- collided shared coupling
- collided shared circular coupling
PURE CIRCULAR COUPLING x1 <====> F1
Which will be resolved into: x1 ====> F1 ====> x1__i2
SHARED CIRCULAR COUPLING F1 <====> x1 ====> F2, F3, etc.
Which will be resolved into: x1 ====> F1 ====> x1__i2 ====> F2, F3, etc.
COLLIDED (SHARED) COUPLING F1,F3 ====> x1 ====> F2, F4
Which will, with a function order of [F1,F2,F3,F4], be resolved into: F1 ====> x1 ====> F2 F3 ====> x1__i2 ====> F4
COLLISION F1,F2 ====> x1
Which will, with a function order of [F1,F2], be resolved into: F1 ====> x1 F2 ====> x1__i2
COLLIDED CIRCULAR COUPLING F1 <====> x1 <==== F2, F3
Which will be resolved into: x1 ====> F1 ====> x1__i2
F2 ====> x1__i3 F3 ====> x1__i4COLLIDED SHARED CIRCULAR COUPLING F3,F5 <====> x1 <==== F2
/F1,F4,F6
Which will, with a function order of [F1,F2,F3,F4,F5,F6], be resolved into: x1 ====> F2 ====> (…) x1__i2 ====> F1,F3 ====> (…) x1__i3 ====> F4,F5 ====> (…) x1__i4 ====> F6
Parameters: args (basestring, list) – problematic node in the graph
-
subgraph
(nodes)¶ Return a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
- nodes : list, iterable
- A container of nodes which will be iterated through once.
- G : SubGraph View
- A subgraph view of the graph. The graph structure cannot be changed but node/edge attributes can and are shared with the original graph.
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: G.subgraph(nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G if n not in set(nodes)])
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.subgraph([0, 1, 2]) >>> list(H.edges) [(0, 1), (1, 2)]
-
succ
¶ Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So G.succ[3][2][‘color’] = ‘blue’ sets the color of the edge (3, 2) to “blue”.
Iterating over G.succ behaves like a dict. Useful idioms include for nbr, datadict in G.succ[n].items():. A data-view not provided by dicts also exists: for nbr, foovalue in G.succ[node].data(‘foo’): and a default can be set via a default argument to the data method.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in G[node].data(‘foo’, default=1): works.
For directed graphs, G.adj is identical to G.succ.
-
successors
(n)¶ Return an iterator over successor nodes of n.
neighbors() and successors() are the same.
-
to_directed
(as_view=False)¶ Return a directed representation of the graph.
- G : DiGraph
- A directed graph with the same name, same nodes, and with each edge (u, v, data) replaced by two directed edges (u, v, data) and (v, u, data).
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not transfer to the DiGraph created by this method.
>>> G = nx.Graph() # or MultiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)]
If already directed, return a (deep) copy
>>> G = nx.DiGraph() # or MultiDiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1)]
-
to_undirected
(reciprocal=False, as_view=False)¶ Return an undirected representation of the digraph.
- reciprocal : bool (optional)
- If True only keep edges that appear in both directions in the original digraph.
- as_view : bool (optional, default=False)
- If True return an undirected view of the original directed graph.
- G : Graph
- An undirected graph with the same name and nodes and with edge (u, v, data) if either (u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is different, only one edge is created with an arbitrary choice of which edge data to use. You must check and correct for this manually if desired.
Graph, copy, add_edge, add_edges_from
If edges in both directions (u, v) and (v, u) exist in the graph, attributes for the new undirected edge will be a combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that the edges are encountered. For more customized control of the edge attributes use add_edge().
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar G=DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not transfer to the Graph created by this method.
>>> G = nx.path_graph(2) # or MultiGraph, etc >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1)]
-
vistoms_add
(vistoms_dir, mpg=None, function_order=None, reference_file=None, compress=False, remove_after_compress=True, graph_id=None, replacement_id=None, xml_file=None)¶ Function to add a graph to a existing VISTOMS instance.
In one VISTOMS instance different graphs can be shown. For example it is possible to include different architectures for the same problem in one VISTOMS instance.
Parameters: - vistoms_dir (str) – directory of the VISTOMS directory to be used for addition
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG as XDSM (if None a DSM is created)
- function_order (list) – optional function order for the diagonal of the graph (only applicable for DSMs)
- reference_file (str) – file from which reference values are extracted (either full path or file in same folder)
- compress (bool) – setting whether to compress the final VISTOMS instance folder to a zip file
- remove_after_compress (bool) – setting whether to remove the original folder after compression
- replacement_id (basestr) – indentifier of the graph to be replaced
- xml_file (file) – Name of the CMDOWS xml-file
-
vistoms_create
(vistoms_dir, vistoms_version=None, mpg=None, function_order=None, reference_file=None, compress=False, remove_after_compress=True, graph_id=None, use_png_figs=False, file_refs=None, xml_file=None)¶ Function to create a new VISTOMS instance from a graph.
Parameters: - vistoms_dir (str) – directory of the VISTOMS directory to be created
- vistoms_version – version of the VISTOMS instance to be used (as stored in the package itself)
- vispack_version – str
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG as XDSM (if None a DSM is created)
- function_order (list) – optional function order for the diagonal of the graph (only applicable for DSMs)
- reference_file (str) – file from which reference values are extracted (either full path or file in same folder)
- compress (bool) – setting whether to compress the final VISTOMS instance folder to a zip file
- remove_after_compress (bool) – setting whether to remove the original folder after compression
- graph_id (basestring) – identifier of the new graph
- use_png_figs (bool) – setting whether to use the PNG figures instead of the SVG figures for local execution
- file_refs (dict) – setting to provide file references manually (to use VISTOMS on a server)
- xml_file (file) – Name of the CMDOWS xml file
-
DataGraph¶
-
class
kadmos.graph.graph_data.
DataGraph
(*args, **kwargs)¶ -
add_default_description
()¶ Method to add a default description attribute to a graph
Returns: graph with default attribute description Return type: KadmosGraph
-
add_default_name
()¶ Method to add a default name attribute to a graph
Returns: graph with default attribute name Return type: KadmosGraph
-
add_edges_from
(ebunch, **attr)¶ Add all the edges in ebunch.
- ebunch : container of edges
- Each edge given in the container will be added to the graph. The edges must be given as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a dictionary containing edge data.
- attr : keyword arguments, optional
- Edge data (or labels or objects) can be assigned using keyword arguments.
add_edge : add a single edge add_weighted_edges_from : convenient way to add weighted edges
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples >>> e = zip(range(0, 3), range(1, 4)) >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
Associate data to edges
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3) >>> G.add_edges_from([(3, 4), (1, 4)], label='WN2898')
-
add_equation
(edge_or_node, equation, language='Python')¶ Method to add an equation to an output edge.
Parameters: - edge_or_node (list, str) – graph edge or node under consideration.
- equation (str) – equation to be added
- language (str) – equation language used for the equation
-
add_equation_label
(edge, labeling_method='node_label', language='Python')¶ Method to add an equation label to a edge that can (safely) be used as reference in an equation.
Parameters: - edge (str) – graph edge under consideration
- labeling_method (str) – select method for automatic label string determination (node_id or node_label)
- language (str) – equation language used for the equation label
Returns: label
Return type: str
-
add_equation_labels
(nodes, language='Python', labeling_method='node_id')¶ Method to add equation labels automatically to all input edges connected to the specified list of nodes
Parameters: - nodes (list) – list of nodes
- language (str) – equation language used for the equation label
- labeling_method (str) – select method for automatic label string determination (node_id or node_label)
-
add_nodes_from
(nodes, **attr)¶ Add multiple nodes.
- nodes : iterable container
- A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
- attr : keyword arguments, optional (default= no attributes)
- Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple take precedence over attributes specified via keyword arguments.
add_node
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_nodes_from('Hello') >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)]) >>> G.add_nodes_from(K3) >>> sorted(G.nodes(), key=str) [0, 1, 2, 'H', 'e', 'l', 'o']
Use keywords to update specific node attributes for every node.
>>> G.add_nodes_from([1, 2], size=10) >>> G.add_nodes_from([3, 4], weight=0.4)
Use (node, attrdict) tuples to update attributes for specific nodes.
>>> G.add_nodes_from([(1, dict(size=11)), (2, {'color':'blue'})]) >>> G.nodes[1]['size'] 11 >>> H = nx.Graph() >>> H.add_nodes_from(G.nodes(data=True)) >>> H.nodes[1]['size'] 11
-
add_objective_function_by_nodes
(*args, **kwargs)¶ This function adds objective functions to the graph using lists of variable nodes.
Each list produces a separate objective function node in the graph. If the list if passed as a keyword argument, the keyword is taken as the name of the objective function node. Otherwise, a standard name will be given to the node. Each objective function node has one output variable, and takes the nodes given in the argument list as input nodes.
If the provided nodes do not exist in the graph, a warning is given to the user on whether to continue the addition of the objective function to the graph using valid nodes.
Example: unnamed_function = list(>>list of graph nodes<<) named_obj_fcn = list(>>list of graph nodes<<) MyGraph.add_objective_function_by_nodes(unnamed_function, My_obj_fcn_name = named_obj_fcn)
The added objective function nodes can be queried by the attribute Graph.node[node][“name”] == “Objective”.
Parameters: - args (list) – list of nodes (list elements must be strings)
- kwargs (list) – list of nodes (list elements must be strings)
Returns: list of Objective Functions added to Graph
Return type: list
-
add_weighted_edges_from
(ebunch, weight='weight', **attr)¶ Add all the weighted edges in ebunch with specified weights.
- ebunch : container of edges
- Each edge in the container is added to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number.
- weight : string, optional (default= ‘weight’)
- The attribute name for the edge weights to be added.
- attr : keyword arguments, optional (default= no attributes)
- Edge attributes to add/update for all edges.
add_edge : add a single edge add_edges_from : add multiple edges
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph, duplicate edges are stored.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
-
adj
¶ Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So G.adj[3][2][‘color’] = ‘blue’ sets the color of the edge (3, 2) to “blue”.
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in G[node].data(‘foo’, default=1): works.
For directed graphs, G.adj holds outgoing (successor) info.
-
adjacency
()¶ Return an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
- adj_iter : iterator
- An iterator over (node, adjacency dictionary) for all nodes in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [(n, nbrdict) for n, nbrdict in G.adjacency()] [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
-
adjlist_inner_dict_factory
¶ alias of
dict
-
adjlist_outer_dict_factory
¶ alias of
dict
-
change_graph_class
(graph_class)¶ Method to adjust the class of a graph.
-
check
(raise_error=False)¶ Method to check the graph for validity and completeness.
Several checks are performed. However the method does not guarantee the validity of the graph.
The checks are split into several categories and the methods _check_category_a, _check_category_b and _check_category_c are used to determine the overall validity and completeness. These sub methods are generally defined below and are then further refined in child classes.
Parameters: raise_error (bool) – determines if an error should be raised in case of an invalid graph Returns: result of the check Return type: bool
-
check_cmdows_integrity
(convention=True, mpg=None)¶ Method to check the integrity of the CMDOWS file that can be created with the save method.
The integrity check is graph specific and thus needs to be executed for every graph before saving as CMDOWS if one wants to be sure that the CMDOWS file is integer. Due to its relative long runtime this check is however not performed automatically when using the save method.
Parameters: - convention (bool) – option for applying a UID convention
- mpg (MdaoProcessGraph) – MPG to be saved together with graph
Returns: check result
Return type: bool
-
check_for_coupling
(function_order, only_feedback=False, raise_error_if_true=False)¶ Function to check for the presence of coupling in a graph for a list of analyses in a given analysis order.
Note that only the functions in the function_order list are checked for feedback.
Parameters: - function_order (list) – list with node names of functions
- only_feedback (bool) – Boolean on whether to check for feedback coupling only (this is useful for Gauss-Seidel)
- raise_error_if_true (bool) – Boolean on whether to raise an error if coupling exists
Returns: Boolean value on whether coupling exists
Return type: bool
-
clear
()¶ Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.clear() >>> list(G.nodes) [] >>> list(G.edges) []
-
copy
(as_view=False)¶ Return a copy of the graph.
The copy method by default returns a shallow copy of the graph and attributes. That is, if an attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for new containers.
If as_view is True then a view is returned instead of a copy.
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four types of copies of a graph that people might want.
Deepcopy – The default behavior is a “deepcopy” where the graph structure as well as all data attributes and any objects they might contain are copied. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s copy.deepcopy)
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph attribute dicts are references to those in the original graph. This saves time and memory but could cause confusion if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the attributes. That is, any attributes that are containers are shared between the new graph and the original. This is exactly what dict.copy() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5) >>> H = G.copy() >>> H = G.copy(as_view=False) >>> H = nx.Graph(G) >>> H = G.fresh_copy().__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not enabled. Instead use:
>>> H = G.fresh_copy() >>> H.add_nodes_from(G) >>> H.add_edges_from(G.edges)
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
- as_view : bool, optional (default=False)
- If True, the returned graph-view provides a read-only view of the original graph without actually copying any data.
- G : Graph
- A copy of the graph.
to_directed: return a directed copy of the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.copy()
-
copy_as
(graph_class, as_view=False)¶ Method to make a copy of a graph and make it into another KADMOS graph class.
Returns: copy of the graph Return type: KadmosGraph
-
copy_edge
(old_edge, new_edge)¶ Method to copy an edge so that attributes of the old edge are maintained.
Parameters: - old_edge (tuple) – edge to be copied
- new_edge (tuple) – edge to be created
Returns: created edge
Return type: tuple
-
copy_node_with_suffix
(node, suffix, label_extension, **kwargs)¶ Method to simply copy a node and its attributes by creating a new node with a suffix.
Parameters: - node (str) – node to be copied
- suffix (str) – suffix to be added to the node ID
- label_extension (str) – extension for labels
- kwargs (dict) – keyword arguments will be added as node attributes
Returns: new node name and enriched graph
Return type: str
-
count_function_nodes
()¶ This function counts the amount function nodes that are present in the graph.
Returns: amount of function nodes counted in graph Return type: int
-
create_dsm
(file_name, destination_folder=None, open_pdf=False, mpg=None, include_system_vars=True, summarize_vars=False, function_order=None, keep_tex_file=False, abbreviate_keywords=False, compile_pdf=True, colors_based_on='problem_roles')¶ Method to create a (X)DSM PDF file
Parameters: - file_name (str) – name of the file to be saved
- destination_folder (str) – destination folder for the file to be saved
- open_pdf (bool) – option for opening the created file directly
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG as XDSM (if None a DSM is created)
- include_system_vars (bool) – option for including system variables (only applicable for DSMs)
- summarize_vars (bool) – option for summarizing label
- function_order (list) – optional function order for the diagonal of the graph (only applicable for DSMs)
- keep_tex_file (bool) – optional argument to keep the tex file of the PDF
- abbreviate_keywords (bool) – optional argument to keep make keywords shorter (input -> inp., output -> outp.)
- compile_pdf (bool) – optional argument to compile the PDF
- colors_based_on (str) – option to base the colors either on the problem role or the partitions
-
deepcopy
()¶ Method to make a deep copy of a graph.
Returns: deepcopy of the graph Return type: KadmosGraph
-
deepcopy_as
(graph_class)¶ Method to make a deep copy of a graph and make it into another KADMOS graph class.
Returns: deepcopy of the graph Return type: KadmosGraph
-
degree
¶ A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- weight : string or None, optional (default=None)
- The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
If a single node is requested deg : int
Degree of the nodeOR if multiple nodes are requested nd_iter : iterator
The iterator returns two-tuples of (node, degree).in_degree, out_degree
>>> G = nx.DiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.degree(0) # node 0 with degree 1 1 >>> list(G.degree([0, 1, 2])) [(0, 1), (1, 2), (2, 2)]
-
disconnect_problematic_variables_from
(function, disconnect_collided_targets=True, disconnect_shared_sources=True, ignore_list=[])¶ Method to automatically disconnect certain problematic variables with respect to a given function.
If given as setting (disconnect_collided_targets=True) then the collided targets will be disconnected from this function. Also, if given as setting (disconnect_shared_sources=True), shared sources are also disconnected.
Parameters: - function (basestring) – function around which problematic variables are disconnected
- disconnect_collided_targets (bool) – setting to disconnect collided targets
- disconnect_shared_sources (list) – setting to disconnect shared sources
- disconnect_shared_sources – setting to ignore certain nodes
-
edge_attr_dict_factory
¶ alias of
dict
-
edge_subgraph
(edges)¶ Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
- edges : iterable
- An iterable of edges in this graph.
- G : Graph
- An edge-induced subgraph of this graph with the same edge attributes.
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
>>> G = nx.path_graph(5) >>> H = G.edge_subgraph([(0, 1), (3, 4)]) >>> list(H.nodes) [0, 1, 3, 4] >>> list(H.edges) [(0, 1), (3, 4)]
-
edges
¶ An OutEdgeView of the DiGraph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges.data(‘color’, default=’red’): iterates through all the edges yielding the color attribute with default ‘red’ if no color attribute exists.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- data : string or bool, optional (default=False)
- The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).
- default : value, optional (default=None)
- Value used for edges that dont have the requested attribute. Only relevant if data is not True or False.
- edges : OutEdgeView
- A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].
in_edges, out_edges
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
>>> G = nx.DiGraph() # or MultiDiGraph, etc >>> nx.add_path(G, [0, 1, 2]) >>> G.add_edge(2, 3, weight=5) >>> [e for e in G.edges] [(0, 1), (1, 2), (2, 3)] >>> G.edges.data() # default data is {} (empty dict) OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]) >>> G.edges.data('weight', default=1) OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)]) >>> G.edges([0, 2]) # only edges incident to these nodes OutEdgeDataView([(0, 1), (2, 3)]) >>> G.edges(0) # only edges incident to a single node (use G.adj[0]?) OutEdgeDataView([(0, 1)])
-
find_all_nodes
(category='all', subcategory='all', attr_cond=None, attr_include=None, attr_exclude=None, xpath_include=None, xpath_exclude=None, print_in_log=False, print_attributes='all')¶ Advanced search function to get nodes and their properties.
Parameters: - category (str) – category of the node (you can specify multiple in a list), see note for allowed values.
- subcategory (str) – subcategory of the node (you can specify multiple in a list), see note for allowed values.
- attr_cond (list) – conditional on the node attribute value (e.g. [‘execution time’,’>’,200])
- attr_include (list) – attributes to exclusively include in search
- attr_exclude (list) – attributes to exclude from search
- xpath_include (list) – xpaths to exclusively include in search
- xpath_exclude (list) – xpaths to exclude from search
- print_in_log (bool) – parameter to set printing in log on or off
- print_attributes (str or list) – attributes that should be printed in the log
Returns: list of all nodes that meet the search criteria
Return type: list
Note
The following categories are allowed:
- all
- variable
- variable group
- function
- architecture element
- RCE component
Note
The following subcategories are allowed:
GROUPS:
- all
- all variables
- all inputs
- all outputs
- all couplings
- all circular variables
- all PSG blocks
- all iterative blocks
- all design variables
VARIABLES:
- hole
- supplied input
- supplied shared input
- output
- collision
- coupling
- pure circular coupling
- shared coupling
- shared circular coupling
- collided coupling
- collided circular coupling
- collided shared coupling
- collided shared circular coupling
VARIABLE GROUPS:
- hole group
- supplied input group
- supplied shared input group
- output group
- coupling group
- shared coupling group
FUNCTIONS:
- hole
- inputless
- outputless
- complete
ARCHITECTURE ELEMENTS:
Action blocks:
- optimizer
- MDA
- optimizer function
- MDA analysis
- independent output function
Parameters:
- initial guess design variable
- final design variable
- final output variable
- MDA coupling variable
- initial guess MDA coupling variable
- final MDA coupling variable
- consistency constraint variable
RCE COMPONENTS:
- Input Provider
- XML Merger
- XML PyMerger
- CPACS Tool
- Converger
- Optimizer
- Consistency constraint function
Example usage: Just get all nodes of a graph in a list:
>>> all_nodes = self.find_all_nodes()
Get all input nodes in a list and print them in the log as well:
>>> all_nodes = self.find_all_nodes(category='all', subcategory='all inputs', print_in_log=True)
Get all input nodes with a certain attribute value:
>>> all_nodes = self.find_all_nodes(category='all', subcategory='all inputs', >>> attr_cond=['execution time', '>', 5], print_in_log=True)
Get all nodes with any of the listed attribute values:
>>> all_nodes = self.find_all_nodes(category='all', subcategory='all', >>> attr_include=[['problem_role'['constraint','objective']],['instance', 1]])
-
fresh_copy
()¶ Return a fresh copy graph with the same data structure.
A fresh copy has no nodes, edges or graph attributes. It is the same data structure as the current graph. This method is typically used to create an empty version of the graph.
If you subclass the base class you should overwrite this method to return your class of graph.
-
get_adjacency_matrix
(print_in_log=True)¶ Function to determine the adjacency matrix of a graph.
Parameters: print_in_log (bool) – option for printing the results Returns: different methods of storing the same adjacency matrix in one dictionary Return type: dict
-
get_architecture_node_ids
(mdao_architecture, number_of_groups=None)¶ Method to get the IDs of architecture nodes specific for a certain MDAO architecture.
Parameters: - mdao_architecture (basestring) – specified architecture (CO, BLISS-2000, etc)
- number_of_groups (int, None) – number of subgroups in distributed architectures
Returns: node IDs
Return type: tuple
-
get_architecture_node_labels
(mdao_architecture, number_of_groups=None)¶ Method to get the labels of architecture nodes specific for a certain MDAO architecture.
Parameters: - mdao_architecture (basestring) – specified architecture (CO, BLISS-2000, etc)
- number_of_groups (int, None) – number of subgroups in distributed architectures
Returns: node labels
Return type: tuple
-
get_categorized_nodes
(print_in_log=False)¶ Function that returns a dictionary with graph nodes grouped according to category and subcategory.
Parameters: print_in_log (bool) – option for printing the categories Returns: dictionary with analysis results Return type: dict
-
get_contracted_graph
(contraction_level)¶ This function contracts the nodes of a graph to the provided contraction level.
The contraction level refers to the xpath-level, which represents the position of the descendant with respect to its predecessors. The example below represents a level 3 node, with “cpacs” being at level zero.
/cpacs/aircraft/wings/wing
-cpacs |—-aircraft |——–wings |————wing
All nodes above the contraction level are removed from the graph and replaced by a “variable group” node, which groups the removed nodes in a node at contraction level. This allows for a “de-cluttering” of the graph, with the graph connections still being represented.
Parameters: contraction_level – int from 0 (highest level) to X (lowest level existing in XML schema) Returns: contracted_graph: graph with contracted nodes
-
get_coupling_dictionary
()¶ Function to get a coupling dictionary. For each function node, the dictionary indicates from which function nodes it gets its input and the number of variables it gets.
F2 ==> x1, x2 ==> F1 F3 ==> x3 ==> F1
Will give: {F1: {F2: 2, F3: 1}}
Returns: coupling dictionary Return type: dict
-
get_coupling_matrix
(function_order_method='manual', node_selection=None)¶ Function to determine the role of the different functions in the FPG.
Parameters: - function_order_method (basestring) – algorithm to be used for the order in which the functions are executed.
- node_selection (list) – selection of nodes for which the coupling matrix will be calculated only
Returns: graph with enriched function node attributes and function problem role dictionary
Return type:
-
get_direct_coupling_nodes
(*args, **kwargs)¶ This method returns the direct couplings between two nodes in a graph.
This method is specifically written (and tested) with function nodes in mind. Direct coupling is defined as coupling with between two nodes through a third node.
In this function, each combination between the provided arguments is tested for couplings (in pairs). First, the two nodes in each pair are checked for common neighbors. If they do, the edges of the common neighbors are iterated to determine whether the node-pair is connected to each other, or only the neighbor. The direction of the coupling is also checked.
Example:
The connection
F1 —> N1 —> F2
leads to
[(F1, F2, N1)]
Parameters: - args (str, list) – nodes to be checked for couplings; at least two must be provided
- kwargs (direction: str) – print_couplings: option for printing all couplings with coupling direction and node (optional)
- kwargs – direction: set only coupling in certain direction (optional)
Returns: couplings: list of tuples containing the coupled nodes and the coupling node
Return type: list
-
get_edge_data
(u, v, default=None)¶ Return the attribute dictionary associated with edge (u, v).
This is identical to G[u][v] except the default is returned instead of an exception is the edge doesn’t exist.
u, v : nodes default: any Python object (default=None)
Value to return if the edge (u, v) is not found.- edge_dict : dictionary
- The edge attribute dictionary.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G[0][1] {}
Warning: Assigning to G[u][v] is not permitted. But it is safe to assign attributes G[u][v][‘foo’]
>>> G[0][1]['weight'] = 7 >>> G[0][1]['weight'] 7 >>> G[1][0]['weight'] 7
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.get_edge_data(0, 1) # default edge data is {} {} >>> e = (0, 1) >>> G.get_edge_data(*e) # tuple form {} >>> G.get_edge_data('a', 'b', default=0) # edge not in graph, return 0 0
-
get_feedback_info
(function_order, coupling_dict)¶ Function to determine the number of feedback loops for a given function order
Parameters: function_order (list) – function order of the nodes :return number of feedback loops :rtype int
-
get_function_graph
(keep_objective_variables=False)¶ Method for replacing variable nodes by function connections.
This function removes all variable nodes from the graph and replaces the variable connections of each function with function connections, such that
F(1) —-> N(1) —-> F(2) —-> N(2) —-> F(3)
becomes
F(1) —-> F(2) —-> F(3),
where N(i) is a variable node, and F(i) a function node.
Param: keep_objective_variables: if given the objective variables will remain in graph Type: keep_objective_variables: bool Returns: new graph without variable nodes
-
get_function_metadata
(node)¶ Function to get the node metadata in a list (used in the dynamic visualization package).
Parameters: node (basestring) – function node to collect the metadata for. Returns: list with metadata Return type: list
-
get_function_nodes
()¶ This function returns a list of all function nodes in the graph.
-
get_graph_properties
(*args)¶ This function retrieves the properties of a graph.
If no argument is given, the standard list of properties GRAPH_PROPERTIES is analyzed and their values are returned in a dict. If arguments are given, only this list will be used as standard list of properties.
Param: args: specific properties to be retrieved (optional) Returns: dictionary containing the properties of the graph Return type: dict
-
get_highest_instance
(node)¶ Method to get the highest instance of a node.
Parameters: node – Returns: Return type:
-
get_node_attributes
(node, attr_list, print_in_log=False)¶ Function to get and print certain attributes of a node from the graph.
Parameters: - node (str) – node name
- attr_list (list) – list with attributes to be pulled
- print_in_log (bool) – option for printing to log
Returns: dictionary with node attributes
Return type: dict
-
get_node_subcategory
(node)¶ Method to analyse a node and to update the subcategory attribute of the node.
The following table illustrates how the subcategory is determined based on the category, indegree and outdegree:
CATEGORY OF NODE SUBCATEGORY INDEGREE OUTDEGREE variable hole 0 0 supplied input 0 1 supplied shared input 0 >1 output 1 0 collision >1 0 - coupling
- or
pure circular coupling
1 1 - shared coupling
- or
shared circular coupling
1 >1 - collided coupling
- or
collided circular coupling
>1 1 - collided shared coupling
- or
collided shared circular coupling
>1 >1 function hole 0 0 inputless 0 >0 outputless >0 0 complete >0 >0 Parameters: node (basestring) – node in the graph Returns: subcategory of the node Return type: basestring
-
get_nodes_based_on_strings
(*args, **kwargs)¶ This function enables the user to search graph nodes for specific strings.
Each provided string will be searched for, and if multiple node are found for each string, the user will be able to select the ones desired. The other matched nodes are disregarded.
Parameters: - args (str) – strings that graph nodes being searched for
- kwargs (include_all: bool) – include_all: If include_all is set to True, all matching nodes are added to returned list
Returns: matching nodes that user selected (all if include_all is True)
-
get_nodes_indegree
()¶ Function to get the indegree of all the graph nodes and store them in a dictionary.
Returns: dictionary with node name key and indegree integer value. Return type: dict
-
get_nodes_outdegree
()¶ Function to get the outdegree of all the graph nodes and store them in a dictionary.
Returns: dictionary with node name key and outdegree integer value. Return type: dict
-
get_nodes_subcategory
()¶ Method to analyse all nodes and to update the subcategory attributes of the nodes.
-
get_number_of_couplings
(node)¶ This function returns the number of couplings of a node in the graph.
Parameters: node – input node Returns: number of couplings for the input node Type: int
-
get_possible_function_order
(method, multi_start=None, check_graph=False)¶ Method to find a possible function order, in the order: pre-coupled, coupled, post-coupled functions
Parameters: - method (str) – algorithm which will be used to minimize the feedback loops
- multi_start (int) – start the algorithm from multiple starting points
- check_graph (bool) – check whether graph has problematic variables
:return Possible function order :rtype list
-
get_same_graph_class
(graph, copy_type='deep')¶ Method to reinstantiate a given graph according to the same graph class as the self.
Parameters: - graph (DiGraph) – graph object to be reinstantiated
- copy_type (basestring) – setting to have a deep or shallow copy of the graph
Returns: reinstantiated graph
Return type:
-
get_sources
(node)¶ Function to determine the sources of a given node.
Parameters: node (basestring) – node for which sources should be found Returns: list with sources Return type: list
-
get_subgraph_by_function_nodes
(*args, **kwargs)¶ This function retrieves a subgraph from the original graph only containing the argument nodes.
All arguments must be found in the graph.
Parameters: - args (list, str) – arbitrary amount of graph nodes
- kwargs (copy_type: str) – copy_type: type of copy (clean or deep)
Returns: sub-graph only containing nodes provided as arguments, and their edges
-
get_system_inputs
(*args, **kwargs)¶ This method checks whether there are system inputs in the graph using the function nodes provided.
The function nodes should be provided in the args. If system inputs exist they are returned.
Parameters: args – function nodes Returns: system input nodes dictionary Return type: dict
-
get_targets
(node)¶ Function to determine the targets of a given node.
Parameters: node (basestring) – node for which targets should be found Returns: list with targets Return type: list
-
has_edge
(u, v)¶ Return True if the edge (u, v) is in the graph.
This is the same as v in G[u] without KeyError exceptions.
- u, v : nodes
- Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects.
- edge_ind : bool
- True if edge is in the graph, False otherwise.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.has_edge(0, 1) # using two nodes True >>> e = (0, 1) >>> G.has_edge(*e) # e is a 2-tuple (u, v) True >>> e = (0, 1, {'weight':7}) >>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary) True
The following syntax are equivalent:
>>> G.has_edge(0, 1) True >>> 1 in G[0] # though this gives KeyError if 0 not in G True
-
has_node
(n)¶ Return True if the graph contains the node n.
Identical to n in G
n : node
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.has_node(0) True
It is more readable and simpler to use
>>> 0 in G True
-
has_nodes
(nodes)¶ Function that checks whether all nodes given in a list are present in the graph.
Parameters: nodes (list) – list of nodes to be checked Returns: boolean whether all nodes have been found Return type: bool
-
has_predecessor
(u, v)¶ Return True if node u has predecessor v.
This is true if graph has the edge u<-v.
-
has_successor
(u, v)¶ Return True if node u has successor v.
This is true if graph has the edge u->v.
-
in_degree
¶ An InDegreeView for (node, in_degree) or in_degree for single node.
The node in_degree is the number of edges pointing to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iteration over (node, in_degree) as well as lookup for the degree for a single node.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- weight : string or None, optional (default=None)
- The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
If a single node is requested deg : int
In-degree of the nodeOR if multiple nodes are requested nd_iter : iterator
The iterator returns two-tuples of (node, in-degree).degree, out_degree
>>> G = nx.DiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.in_degree(0) # node 0 with degree 0 0 >>> list(G.in_degree([0, 1, 2])) [(0, 0), (1, 1), (2, 1)]
-
in_edges
¶ An InEdgeView of the Graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, default=None):
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- data : string or bool, optional (default=False)
- The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).
- default : value, optional (default=None)
- Value used for edges that dont have the requested attribute. Only relevant if data is not True or False.
- in_edges : InEdgeView
- A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].
edges
-
inspect
()¶ Method to print an overview of the graph.
-
inspect_node
(node)¶ Method to print a node with details.
Parameters: node (str) – node
-
inspect_nodes
(list_of_nodes)¶ Method to inspect a list of nodes with details.
Parameters: list_of_nodes (list) – node list
-
is_directed
()¶ Return True if graph is directed, False otherwise.
-
is_multigraph
()¶ Return True if graph is a multigraph, False otherwise.
-
make_all_variables_valid
()¶ Method to analyze all variables in a graph and make any problematic variables valid.
Problematic variable are holes and splittables. Splittable variables are split and holes will simply be removed.
-
mark_as_constraint
(node, operator, reference_value, remove_unused_outputs=False)¶ Method to mark a node as a constraint.
Parameters: - node – node to be marked (on the left side of the operator
- operator (str or string list) – constraint operator or list of constraint operators
- reference_value (numbers.Number or list) – value on the right side of the operator or list of values corresponding to the list of operators
-
mark_as_constraints
(nodes, operators, reference_values, remove_unused_outputs=False)¶ Method to mark multiple nodes as constraints.
Parameters: - nodes – list of nodes to be marked.
- operators – operators to be implemented (as list per node or as single operator for all)
- reference_values – reference values to be used (as list of values per node or as single value for all)
Returns: graph with enriched constraint nodes
-
mark_as_design_variable
(node, lower_bound=None, upper_bound=None, samples=None, nominal_value=0.0, ignore_outdegree=False)¶ Method to mark a single node as a design variable and add the required metadata for its definition.
Parameters: - node –
- lower_bound –
- upper_bound –
- samples –
Returns:
-
mark_as_design_variables
(nodes, lower_bounds=None, upper_bounds=None, samples=None, nominal_values=None)¶ Method to mark a list of nodes as design variable and add metadata.
Parameters: - nodes (list or str) – list of nodes present in the graph
- lower_bounds (list or numbers.Number) – list of lower bound values
- upper_bounds (list or numbers.Number) – list of upper bounds
- samples (list) – nested list of kadmos values
- nominal_values (list or numbers.Number) – list of nominal values
-
mark_as_objective
(node, remove_unused_outputs=False)¶ Method to mark a single node as objective.
Parameters: node (basestring) – variable node
-
mark_as_qois
(nodes, remove_unused_outputs=False)¶ Function to mark a list of nodes as quantity of interest.
Parameters: nodes (list) – list of nodes present in the graph
-
merge_function_modes
(*args, **kwargs)¶ Function to contract certain modes of the same function.
Parameters: - args (str) – function (first arg) and then followed by modes to be contracted.
- kwargs (dict or str) – new_label to specify new node label manually (optional)
Returns: contracted graph
Return type:
-
merge_function_nodes_based_on_modes
(merge_funcs=None)¶ This class method merges all execution modes of the same function into a single node.
Mainly used for illustration purposes since information on the execution modes gets lost.
Parameters: merge_funcs – List of tuple of functions to merge. If empty (default), all functions are merged. Functions must be present in graph. :type merge_funcs: list, tuple :return: merged graph
-
merge_functions
(*args, **kwargs)¶ Function to merge a collection of functions.
Parameters: - args (node_ids) – functions to be merged
- kwargs (dict) – new_label to specify new node label manually (optional)
-
merge_parallel_functions
(*args, **kwargs)¶ Function to merge a list of functions
Parameters: - args (node_ids) – functions to be merged
- kwargs (dict) – new_label to specify new node label manually (optional)
-
merge_sequential_functions
(*args, **kwargs)¶ Function to merge a collection of functions.
It is assumed that the merged functions are actually executed in the sequence in which they are given to this function.
Parameters: - args (node_ids) – functions to be merged in the given sequence
- kwargs (str) – new_label to specify new node label manually (optional)
-
minimize_feedback
(nodes, method, multi_start=None, get_evaluations=False)¶ Function to find the function order with minimum feedback
Parameters: - nodes (list) – nodes for which the feedback needs to be minimized
- method (str) – algorithm used to find optimal function order
- multi_start (int) – start the algorithm from multiple starting points
- get_evaluations (bool) – option to give the number of evaluations as output
:return function order :rtype list :return number of evaluations :rtype int
-
name
¶ String identifier of the graph.
This graph attribute appears in the attribute dict G.graph keyed by the string “name”. as well as an attribute (technically a property) G.name. This is entirely user controlled.
-
nbunch_iter
(nbunch=None)¶ Return an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- niter : iterator
- An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate over all nodes in the graph.
- NetworkXError
- If nbunch is not a node or or sequence of nodes. If a node in nbunch is not hashable.
Graph.__iter__
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a
NetworkXError
is raised. Also, if any object in nbunch is not hashable, aNetworkXError
is raised.
-
neighbors
(n)¶ Return an iterator over successor nodes of n.
neighbors() and successors() are the same.
-
node
¶ A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for set-like operations. Can also be used as G.nodes(data=’color’, default=None) to return a NodeDataView which reports specific node data but no set operations. It presents a dict-like interface as well with G.nodes.items() iterating over (node, nodedata) 2-tuples and G.nodes[3][‘foo’] providing the value of the foo attribute for node 3. In addition, a view G.nodes.data(‘foo’) provides a dict-like interface to the foo attribute of each node. G.nodes.data(‘foo’, default=1) provides a default for nodes that do not have attribute foo.
- data : string or bool, optional (default=False)
- The node attribute returned in 2-tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.
- default : value, optional (default=None)
- Value used for nodes that dont have the requested attribute. Only relevant if data is not True or False.
- NodeView
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.
If your node data is not needed, it is simpler and equivalent to use the expression
for n in G
, orlist(G)
.There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time='5pm') >>> G.nodes[0]['foo'] = 'bar' >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes.data()) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data='foo')) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes.data('foo')) [(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time')) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes.data('time')) [(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data='time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')] >>> list(G.nodes.data('time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data='weight', default=1)) {0: 1, 1: 2, 2: 3}
-
node_dict_factory
¶ alias of
dict
-
node_is_function
(node)¶ Function that checks whether a node is a function node or not.
Parameters: node (str) – node in graph Returns: check result Return type: bool
-
node_is_hole
(node)¶ Function that checks whether a node is a hole (unconnected).
Parameters: node (str) – node in graph Returns: check result Return type: bool
-
node_is_objective_function
(node)¶ This function checks whether the provided node is a objective function.
- This function checks whether the provided node:
- exists in graph
- has name-attribute “Objective”
- has an out-degree of 1
- has an outgoing node with an out-degree of zero # TODO: THIS IS WRONG!
Only if all checks are satisfied, is the node a valid objective function node.
Parameters: node (str) – graph node to be tested Returns: check result Return type: bool
-
node_is_output
(node)¶ Function that checks whether a node is a system output.
Parameters: node (str) – node in graph Returns: check result Return type: bool
-
node_is_variable
(node)¶ Function that checks whether a node is a variable node or not.
Parameters: node (str) – node in graph Returns: check result Return type: bool
-
nodes
¶ A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for set-like operations. Can also be used as G.nodes(data=’color’, default=None) to return a NodeDataView which reports specific node data but no set operations. It presents a dict-like interface as well with G.nodes.items() iterating over (node, nodedata) 2-tuples and G.nodes[3][‘foo’] providing the value of the foo attribute for node 3. In addition, a view G.nodes.data(‘foo’) provides a dict-like interface to the foo attribute of each node. G.nodes.data(‘foo’, default=1) provides a default for nodes that do not have attribute foo.
- data : string or bool, optional (default=False)
- The node attribute returned in 2-tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.
- default : value, optional (default=None)
- Value used for nodes that dont have the requested attribute. Only relevant if data is not True or False.
- NodeView
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.
If your node data is not needed, it is simpler and equivalent to use the expression
for n in G
, orlist(G)
.There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time='5pm') >>> G.nodes[0]['foo'] = 'bar' >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes.data()) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data='foo')) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes.data('foo')) [(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time')) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes.data('time')) [(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data='time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')] >>> list(G.nodes.data('time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data='weight', default=1)) {0: 1, 1: 2, 2: 3}
-
number_of_edges
(u=None, v=None)¶ Return the number of edges between two nodes.
- u, v : nodes, optional (default=all edges)
- If u and v are specified, return the number of edges between u and v. Otherwise return the total number of all edges.
- nedges : int
- The number of edges in the graph. If nodes u and v are specified return the number of edges between those nodes. If the graph is directed, this only returns the number of edges from u to v.
size
For undirected graphs, this method counts the total number of edges in the graph:
>>> G = nx.path_graph(4) >>> G.number_of_edges() 3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1) 1
For directed graphs, this method can count the total number of directed edges from u to v:
>>> G = nx.DiGraph() >>> G.add_edge(0, 1) >>> G.add_edge(1, 0) >>> G.number_of_edges(0, 1) 1
-
number_of_nodes
()¶ Return the number of nodes in the graph.
- nnodes : int
- The number of nodes in the graph.
order, __len__ which are identical
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> len(G) 3
-
order
()¶ Return the number of nodes in the graph.
- nnodes : int
- The number of nodes in the graph.
number_of_nodes, __len__ which are identical
-
out_degree
¶ An OutDegreeView for (node, out_degree)
The node out_degree is the number of edges pointing out of the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator over (node, out_degree) as well as lookup for the degree for a single node.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- weight : string or None, optional (default=None)
- The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
If a single node is requested deg : int
Out-degree of the nodeOR if multiple nodes are requested nd_iter : iterator
The iterator returns two-tuples of (node, out-degree).degree, in_degree
>>> G = nx.DiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.out_degree(0) # node 0 with degree 1 1 >>> list(G.out_degree([0, 1, 2])) [(0, 1), (1, 1), (2, 1)]
-
out_edges
¶ An OutEdgeView of the DiGraph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges.data(‘color’, default=’red’): iterates through all the edges yielding the color attribute with default ‘red’ if no color attribute exists.
- nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges incident to these nodes.
- data : string or bool, optional (default=False)
- The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).
- default : value, optional (default=None)
- Value used for edges that dont have the requested attribute. Only relevant if data is not True or False.
- edges : OutEdgeView
- A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].
in_edges, out_edges
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
>>> G = nx.DiGraph() # or MultiDiGraph, etc >>> nx.add_path(G, [0, 1, 2]) >>> G.add_edge(2, 3, weight=5) >>> [e for e in G.edges] [(0, 1), (1, 2), (2, 3)] >>> G.edges.data() # default data is {} (empty dict) OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]) >>> G.edges.data('weight', default=1) OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)]) >>> G.edges([0, 2]) # only edges incident to these nodes OutEdgeDataView([(0, 1), (2, 3)]) >>> G.edges(0) # only edges incident to a single node (use G.adj[0]?) OutEdgeDataView([(0, 1)])
-
plot_adjacency_matrix
(fig_num=1, fig_size=(7, 7), show_now=True)¶ Draw the adjacency matrix in a plot window.
Parameters: - fig_num – figure number
- fig_size – figure size
- show_now – Boolean whether to plot directly (pausing the execution until the plot is closed), or not.
-
plot_graph
(fig_num=1, color_setting='default', positioning='circular', save_as=None, show_now=True, title=None, edge_label=False)¶ Function to plot a graph.
Note that you need to add matplotlib.pyplot.show() at the end of your code to see the plot window.
Parameters: - fig_num – figure number
- fig_size – size of figure window
- color_setting – choose from ‘default’, ‘sinks’, ‘categories’, ‘partitions’
- positioning – choose from ‘circular’, ‘spring’
- save_as – save plot as figure file
- show_now – Boolean whether to plot directly (pausing the execution until the plot is closed), or not.
- title – title string of the graph
- edge_label – edge attribute that will be shown for each edge in graph
Returns: window with plot
-
pred
¶ Graph adjacency object holding the predecessors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So G.pred[2][3][‘color’] = ‘blue’ sets the color of the edge (3, 2) to “blue”.
Iterating over G.pred behaves like a dict. Useful idioms include for nbr, datadict in G.pred[n].items():. A data-view not provided by dicts also exists: for nbr, foovalue in G.pred[node].data(‘foo’): A default can be set via a default argument to the data method.
-
predecessors
(n)¶ Return an iterator over predecessor nodes of n.
-
print_graph
(use_pretty_print=False)¶ Function to print the full graph.
Parameters: use_pretty_print (bool) – Boolean on whether to use pretty print for node and edge attributes
-
relabel_function_nodes
(mapping=None)¶ Method to relabel all function nodes so that they meet the CMDOWS convention ID[modeID][instanceID][version]
-
remove_edge
(u, v)¶ Remove the edge between u and v.
- u, v : nodes
- Remove the edge between nodes u and v.
- NetworkXError
- If there is not an edge between u and v.
remove_edges_from : remove a collection of edges
>>> G = nx.Graph() # or DiGraph, etc >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.remove_edge(0, 1) >>> e = (1, 2) >>> G.remove_edge(*e) # unpacks e from an edge tuple >>> e = (2, 3, {'weight':7}) # an edge with attribute data >>> G.remove_edge(*e[:2]) # select first part of edge tuple
-
remove_edges_from
(ebunch)¶ Remove all edges specified in ebunch.
- ebunch: list or container of edge tuples
Each edge given in the list or container will be removed from the graph. The edges can be:
- 2-tuples (u, v) edge between u and v.
- 3-tuples (u, v, k) where k is ignored.
remove_edge : remove a single edge
Will fail silently if an edge in ebunch is not in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> ebunch = [(1, 2), (2, 3)] >>> G.remove_edges_from(ebunch)
-
remove_function_nodes
(*args)¶ Function that removes a function node
Also the input and output variables that only have links to this specific function node are deleted. A simple remove_node of a function node might lead to unconnected variables in the graph.
Parameters: args (str or list) – function node id(s)
-
remove_node
(n)¶ Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
- n : node
- A node in the graph
- NetworkXError
- If n is not in the graph.
remove_nodes_from
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> list(G.edges) [(0, 1), (1, 2)] >>> G.remove_node(1) >>> list(G.edges) []
-
remove_nodes_from
(nodes)¶ Remove multiple nodes.
- nodes : iterable container
- A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it is silently ignored.
remove_node
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = list(G.nodes) >>> e [0, 1, 2] >>> G.remove_nodes_from(e) >>> list(G.nodes) []
-
remove_unused_outputs
()¶ Function to remove output nodes from an FPG which do not have a problem role.
Returns: the nodes that were removed Return type: list
-
reverse
(copy=True)¶ Return the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
- copy : bool optional (default=True)
- If True, return a new DiGraph holding the reversed edges. If False, the reverse graph is created using a view of the original graph.
-
save
(file_name, file_type='kdms', graph_check_critical=True, destination_folder=None, mpg=None, description='', creator='', version='1.0', timestamp=datetime.datetime(2018, 3, 29, 18, 16, 26, 304335), keep_empty_elements=False, pretty_print=False, convention=True, integrity=False)¶ Method to save the graph.
Different output file types are implemented for saving graphs. They are listed in the following. kdms: the most simple file type which makes use of pickling cmdows: the most versatile file type especially suited for file exchange with other tools graphml: another file type especially suited for file exchange with other tools based on graphs
Parameters: - file_name (str) – name of the file to be saved
- file_type (str) – file_type
- graph_check_critical (bool) – option for raising errors in case of an invalid graph
- destination_folder (str) – destination folder for the file to be saved
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG
- description (str) – description of the file (only applicable for the cmdows file type)
- creator (str) – name of the creator of the file (only applicable for the cmdows file type)
- version (str | float | int) – version of the file (only applicable for the cmdows file type)
- timestamp (datetime) – timestamp to be saved in the file (only applicable for the cmdows file type)
- keep_empty_elements (bool) – option for keeping empty XML elements (only applicable for the cmdows file type)
- pretty_print (bool) – option for pretty XML printing (only applicable for the cmdows file type)
- convention (bool) – option for appyling a UID convention (only applicable for the cmdows file type)
- integrity (bool) – option for doing an integrity file check (only applicable for the cmdows file type)
-
select_objectives_from_graph
(*args)¶ This functions lets the user select one or more objective functions from the graph.
Only functions can be selected as objectives. If no arguments are provided, user is prompted to select an objective from all functions in graph.
Param: args: objective functions to choose from Returns: list of objective functions
-
size
(weight=None)¶ Return the number of edges or total of all edge weights.
- weight : string or None, optional (default=None)
- The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.
- size : numeric
The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are more general).
number_of_edges
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.size() 3
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge('a', 'b', weight=2) >>> G.add_edge('b', 'c', weight=4) >>> G.size() 2 >>> G.size(weight='weight') 6.0
-
sort_nodes_for_process
(nodes)¶ Method to sort function nodes such that the process order is optimized, while not increasing the number of feedback loops
Parameters: nodes (list) – function nodes to sort :return nodes in sorted order :rtype list
-
split_variables
(*args, **kwargs)¶ Method to split a problematic variable node into multiple separate valid nodes.
The following variables are considered problematic and will be handled by this function:
- pure circular coupling
- shared circular coupling
- collided coupling
- collision
- collided circular coupling
- collided shared coupling
- collided shared circular coupling
PURE CIRCULAR COUPLING x1 <====> F1
Which will be resolved into: x1 ====> F1 ====> x1__i2
SHARED CIRCULAR COUPLING F1 <====> x1 ====> F2, F3, etc.
Which will be resolved into: x1 ====> F1 ====> x1__i2 ====> F2, F3, etc.
COLLIDED (SHARED) COUPLING F1,F3 ====> x1 ====> F2, F4
Which will, with a function order of [F1,F2,F3,F4], be resolved into: F1 ====> x1 ====> F2 F3 ====> x1__i2 ====> F4
COLLISION F1,F2 ====> x1
Which will, with a function order of [F1,F2], be resolved into: F1 ====> x1 F2 ====> x1__i2
COLLIDED CIRCULAR COUPLING F1 <====> x1 <==== F2, F3
Which will be resolved into: x1 ====> F1 ====> x1__i2
F2 ====> x1__i3 F3 ====> x1__i4COLLIDED SHARED CIRCULAR COUPLING F3,F5 <====> x1 <==== F2
/F1,F4,F6
Which will, with a function order of [F1,F2,F3,F4,F5,F6], be resolved into: x1 ====> F2 ====> (…) x1__i2 ====> F1,F3 ====> (…) x1__i3 ====> F4,F5 ====> (…) x1__i4 ====> F6
Parameters: args (basestring, list) – problematic node in the graph
-
subgraph
(nodes)¶ Return a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
- nodes : list, iterable
- A container of nodes which will be iterated through once.
- G : SubGraph View
- A subgraph view of the graph. The graph structure cannot be changed but node/edge attributes can and are shared with the original graph.
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: G.subgraph(nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G if n not in set(nodes)])
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.subgraph([0, 1, 2]) >>> list(H.edges) [(0, 1), (1, 2)]
-
succ
¶ Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So G.succ[3][2][‘color’] = ‘blue’ sets the color of the edge (3, 2) to “blue”.
Iterating over G.succ behaves like a dict. Useful idioms include for nbr, datadict in G.succ[n].items():. A data-view not provided by dicts also exists: for nbr, foovalue in G.succ[node].data(‘foo’): and a default can be set via a default argument to the data method.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in G[node].data(‘foo’, default=1): works.
For directed graphs, G.adj is identical to G.succ.
-
successors
(n)¶ Return an iterator over successor nodes of n.
neighbors() and successors() are the same.
-
to_directed
(as_view=False)¶ Return a directed representation of the graph.
- G : DiGraph
- A directed graph with the same name, same nodes, and with each edge (u, v, data) replaced by two directed edges (u, v, data) and (v, u, data).
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not transfer to the DiGraph created by this method.
>>> G = nx.Graph() # or MultiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)]
If already directed, return a (deep) copy
>>> G = nx.DiGraph() # or MultiDiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1)]
-
to_undirected
(reciprocal=False, as_view=False)¶ Return an undirected representation of the digraph.
- reciprocal : bool (optional)
- If True only keep edges that appear in both directions in the original digraph.
- as_view : bool (optional, default=False)
- If True return an undirected view of the original directed graph.
- G : Graph
- An undirected graph with the same name and nodes and with edge (u, v, data) if either (u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is different, only one edge is created with an arbitrary choice of which edge data to use. You must check and correct for this manually if desired.
Graph, copy, add_edge, add_edges_from
If edges in both directions (u, v) and (v, u) exist in the graph, attributes for the new undirected edge will be a combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that the edges are encountered. For more customized control of the edge attributes use add_edge().
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar G=DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not transfer to the Graph created by this method.
>>> G = nx.path_graph(2) # or MultiGraph, etc >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1)]
-
unmark_variable
(node)¶ Function to unmark any marked variable.
Parameters: node (basestring) – variable node to be unmarked
-
vistoms_add
(vistoms_dir, mpg=None, function_order=None, reference_file=None, compress=False, remove_after_compress=True, graph_id=None, replacement_id=None, xml_file=None)¶ Function to add a graph to a existing VISTOMS instance.
In one VISTOMS instance different graphs can be shown. For example it is possible to include different architectures for the same problem in one VISTOMS instance.
Parameters: - vistoms_dir (str) – directory of the VISTOMS directory to be used for addition
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG as XDSM (if None a DSM is created)
- function_order (list) – optional function order for the diagonal of the graph (only applicable for DSMs)
- reference_file (str) – file from which reference values are extracted (either full path or file in same folder)
- compress (bool) – setting whether to compress the final VISTOMS instance folder to a zip file
- remove_after_compress (bool) – setting whether to remove the original folder after compression
- replacement_id (basestr) – indentifier of the graph to be replaced
- xml_file (file) – Name of the CMDOWS xml-file
-
vistoms_create
(vistoms_dir, vistoms_version=None, mpg=None, function_order=None, reference_file=None, compress=False, remove_after_compress=True, graph_id=None, use_png_figs=False, file_refs=None, xml_file=None)¶ Function to create a new VISTOMS instance from a graph.
Parameters: - vistoms_dir (str) – directory of the VISTOMS directory to be created
- vistoms_version – version of the VISTOMS instance to be used (as stored in the package itself)
- vispack_version – str
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG as XDSM (if None a DSM is created)
- function_order (list) – optional function order for the diagonal of the graph (only applicable for DSMs)
- reference_file (str) – file from which reference values are extracted (either full path or file in same folder)
- compress (bool) – setting whether to compress the final VISTOMS instance folder to a zip file
- remove_after_compress (bool) – setting whether to remove the original folder after compression
- graph_id (basestring) – identifier of the new graph
- use_png_figs (bool) – setting whether to use the PNG figures instead of the SVG figures for local execution
- file_refs (dict) – setting to provide file references manually (to use VISTOMS on a server)
- xml_file (file) – Name of the CMDOWS xml file
-
RepositoryConnectivityGraph¶
-
class
kadmos.graph.graph_data.
RepositoryConnectivityGraph
(*args, **kwargs)¶ -
create_mathematical_problem
(n_disciplines, coupling_strength=None, n_global_var=None, n_local_var=None, n_coupling_var=None, n_local_constraints=None, n_global_constraints=None, B=None, C=None, D=None, E=None, F=None, G=None, H=None, I=None, J=None, r=None, s=None, write_problem_to_textfile=False)¶ Function to get a mathematical problem according to the variable complexity problem as described in: Zhang D., Song B., Wang P. and He Y. ‘Performance Evaluation of MDO Architectures within a Variable Complexity Problem’, Mathematical Problems in Engineering, 2017.
Parameters: - n_disciplines – Number of disciplines
- coupling_strength – percentage of couplings, 0 no couplings, 1 all possible couplings
- n_global_var – Number of global design variables
- n_local_var – Number of local design variables for each discipline
- n_coupling_var – Number of output variables for each discipline
- n_local_constraints – Number of local constraints
- n_global_constraints – Number of global constraints
- B – relation between the coupling variables
- C – relation between the global design variables and coupling variables
- D – relation between the local design variables and coupling variables
- E – relation between the global design variables and local constraints
- F – relation between the local design variables and local constraints
- G – relation between the coupling variables and local constraints
- H – relation between the global design variables and global constraints
- I – relation between the local design variables and global constraints
- J – relation between the coupling variables and global constraints
- r – positive scalars to be used for the local constraints
- s – positive scalars to be used for the global constraints
- write_problem_to_textfile – option to write generated problem to a textfile
-
get_fpg_based_on_function_nodes
(*args, **kwargs)¶ Function to get the Fundamental Problem Graph based on a list of (or a single) function.
Parameters: - args (str) – node names of functions of interest
- kwargs (name: str) – name: name of the graph to be generated
Returns: Fundamental Problem Graph object
Return type:
-
get_fpg_based_on_list_functions
(list_of_functions, name='FPG')¶ Function to get a Fundamental Problem Graph based on a list of functions.
Parameters: - list_of_functions (list) – list with strings that specify the desired functions
- name (str) – name of the graph to be generated
Returns: Fundamental Problem Graph object
Return type:
-
get_fpg_based_on_sinks
(list_of_sinks, name='FPG')¶ Function to get the a Fundamental Problem Graph based on a list of sinks/required output variables.
Parameters: - list_of_sinks (list) – list with strings that specify the desired output
- name (str) – name of the graph to be generated
Returns: Fundamental Problem Graph object
Return type:
-
get_fpg_by_function_nodes
(*args)¶ This function creates a new (FPG)-graph based on the selected function nodes.
Returns: new fpg graph Return type: FundamentalProblemGraph
-
get_function_paths_by_objective
(*args, **kwargs)¶ This function takes an arbitrary amount of objective nodes as graph sinks and returns all path combinations of tools.
If no arguments are given, user is prompted to select objectives from the graph.
The tool combinations are found using the function itertools.product() and can lead to significant computation times for large graphs. If this is the case, the user is prompted whether to continue or not.
A variety of filters can be applied to the search of possible tools combinations, some of which reduce the computation time.
kwargs: obj_vars_covered - ensures that all objective variables are used in tool configurations ignore_funcs - ignores functions for the config source - source node; if provided, must be in config
Parameters: - args – arbitrary amount of objective nodes
- kwargs – filter options to limit possible path combinations
Returns: all possible FPG path combinations for the provided objective nodes
-
get_path_combinations
(*args, **kwargs)¶ This function takes lists of subsets and generates all possible combinations between them.
This is done by using the itertools.product() function. If the amount of expected evaluations exceeds a pre-set minimum, the user will be asked if to continue or not; because the process can take a long time and use up many resources.
Optional arguments: min_func: minimum amount of functions in each configuration max_func: maximum amount of functions in each configuration
Parameters: args (list) – lists of subsets that will be used to find configurations Returns: set of all unique path combinations
-
select_function_combination_from
(*args, **kwargs)¶ This function takes all provided workflow configurations and lists them according to their characteristics.
The user can then choose the workflow configuration from the list. A warning is given to the user if the amount of total configurations exceeds n = 1e4. Print limit is set to [0-20] by default. sort_by must be one of [“couplings”, “system_inputs”, “edges”, “nodes”].
-
FundamentalProblemGraph¶
-
class
kadmos.graph.graph_data.
FundamentalProblemGraph
(*args, **kwargs)¶ -
add_function_problem_roles
(function_order_method='manual')¶ Method to add the function problem roles (pre-coupled, coupled, post-coupled functions).
Parameters: function_order_method (basestring) – algorithm to be used for the order in which the functions are executed.
-
create_mdg
(mg_function_ordering, name='MDG')¶ Function to automatically create an MDG based on an FPG.
Parameters: - mg_function_ordering (dict) – dictionary with MDAO graph function ordering
- name (basestring) – name for the MDG graph
Returns: baseline MDG (only added additional action blocks, no changed connections)
Return type: MdaoDataGraph
-
create_mpg
(mg_function_ordering, name='MPG')¶ Function to automatically create a MPG based on a FPG.
Parameters: - mg_function_ordering (dict) – dictionary with MDAO graph function ordering
- name (basestring) – name for the MPG graph
Returns: unconnected FPG (only action blocks and their diagonal position)
Return type:
-
determine_scope_constraint_functions
(cnstrnt_vars=None, coupled_functions_groups=None, post_coupling_functions=None)¶ Method to determine the scope (global, local) of the contraint functions based on the constraint variables and to determine on which coupled function groups the constraint function depends.
Parameters: - cnstrnt_vars (list) – (optional) constraint variables to be determined
- coupled_functions_groups (list) – (optional) list of lists with coupled functions groups
- post_coupling_functions (list) – (optional) list with post-coupling functionss
Returns: global constraint variables and functions, local constraint variables and functions, groups indices per
constraint function :rtype: tuple
-
determine_scope_design_variables
(des_vars=None, coupled_functions_groups=None, pre_coupling_functions=None)¶ Method to determine the scope (global, local) of the design variables and to determine to which coupled function groups the design variable belongs.
Parameters: - des_vars (list) – list of design variables (if not given, it is taken from the graph)
- coupled_functions_groups (list) – list with list of coupled function groups
Returns: list of global design variables, list of local design variables, dictionary with dependencies
Return type: tuple
-
get_mdg
(name='MDG')¶ Create the MDAO data graph for a given FPG.
Parameters: name (basestring) – name of the new graph Returns: MDAO data graph Return type: MdaoDataGraph
-
get_mg_function_ordering
()¶ Method to determine the function ordering for MDAO graphs (FPG and MDG) based on an FPG.
Function ordering has to be adjusted when design variables are used. In that case, the pre-coupling functions have to be divided in two parts: the first part does not use the design variables yet, while the second does.
Returns: function ordering dictionary Return type: dict
-
get_objective_node
()¶ Method to get the single (or non-existent) objective node from a graph.
Returns: objective node or None if no objective node is present Return type: str, None
-
get_partition_info
(partitions, include_run_time=False)¶ Function to get the number of feedback variables in the partitions and the number system variables (feedback and feedforward variables between partitions)
Parameters: - partitions (dict) – dictionary which indicates which nodes are in which partition
- include_run_time (bool) –
Return partition_variables: Rtype partition_variables: list of sets
Return system_variables: Rtype system_variables: set
-
impose_mdao_architecture
()¶ Method to directly get both the MDG and MPG of an FPG.
Returns: MdaoDataGraph and MdaoProcessGraph Return type: tuple
-
partition_graph
(n_parts, include_run_time=False, tpwgts=None, recursive=True, contig=False)¶ Partition a graph using the Metis algorithm (http://glaros.dtc.umn.edu/gkhome/metis/metis/overview).
Note that partitioning can only be performed on undirected graphs. Therefore every graph input is translated into an undirected graph.
Parameters: - n_parts (int) – number of partitions requested (algorithm might provide less)
- include_run_time (bool) –
- tpwgts (list) – list of target partition weights
- recursive (bool) – option to use the recursive bisection or k-way partitioning algorithm
- contig (bool) – Metis option
-
select_distributed_architecture
()¶ Function for easy selection of a distributed architecture for a partitioned graph.
:return Extended problem formulation
-
select_number_of_partitions
(partition_range, include_run_time=False, plot_pareto_front=False)¶ Function to evaluate the properties of different number of partitions and to select the best one.
Parameters: - partition_range (list) – range of number of partitions that need to be evaluated
- include_run_time –
- plot_pareto_front (bool) – Option to plot the characteristics of different number of partitions
Returns:
-
MdaoProcessGraph¶
-
class
kadmos.graph.graph_process.
MdaoProcessGraph
(*args, **kwargs)¶ -
add_process
(sequence, start_step, mdg, end_in_iterative_node=None)¶ Method to add a process to a list of functions.
The sequence is assumed to be the order of the functions in the input list. The sequence is considered simple, since it is not analyzed for the possibility to run functions in parallel.
Parameters: - sequence (list) – list of functions in the required sequence
- start_step (int) – process step number for the first element in the sequence
- mdg (MdaoDataGraph) – data graph to be used for execution dependencies
- end_in_iterative_node (basestring) – (optional) iterative node to which the last function should go
-
add_process_partitions
(previous_sequence, partitions, next_sequence, process_step, mdg, end_in_iterative_node=None)¶ Function to add the process in the partitions
-
connect_nested_iterators
(master, slave, direction='slave->master')¶ Method to connect a slave iterator to a master iterator in a nested configuration.
An example is if a converger inside an optimizer in MDF needs to be linked back.
Parameters: - master (basestring) – upper iterator node in the nested configuration
- slave (basestring) – lower iterator node in the nested configuration
-
get_lowest_psn
(cycle)¶ Method to retrieve the lowest process step number (PSN) of a list of nodes in a cycle.
Parameters: cycle (list) – list with nodes on a cycle Returns: the minimal PSN and the index of the first element having this PSN Return type: tuple
-
get_node_text
(node)¶ Method to determine the text of a function node (for use in a XDSM diagram).
Parameters: node (basestring) – node Returns: node text for in the XDSM function box Return type: basestring
-
get_ordered_cycles
()¶ Method to get the cycles of a process graph ordered according to process step number.
Returns: list with the cycles of a graph ordered based on PSN Return type: list
-
get_process_hierarchy
()¶ Method to assess the hierarchy of the process based on the process lines in a ProcessGraph.
Returns: nested list with process hierarchy, e.g. [COOR, A, [OPT, [CONV, D1, D2], F1, G1, G2]] Return type: list
-
get_process_list
(use_d3js_node_ids=False)¶ Method to get the xdsm workflow process list (for use in dynamic visualizations).
Parameters: use_d3js_node_ids (bool) – setting whether node names should be changed into node ids according to D3js notation. Returns: process list Return type: list
-
inspect_process
()¶ Method to print the MPG.
-
MdaoMixin¶
-
class
kadmos.graph.mixin_mdao.
MdaoMixin
¶ -
insert_node_on_diagonal
(node, diagonal_pos, attr_dict=None)¶ Function to insert a node on the diagonal with functions.
Parameters: - node (str) – node identifier
- diagonal_pos (int) – integer with diagonal position (>= 0)
- attr_dict (dict) – dictionary with node attributes
-
remove_node_from_diagonal
(node)¶ Function to remove a node from the diagonal with functions.
Parameters: node (str) – node identifier
-
EquationMixin¶
-
class
kadmos.graph.mixin_equation.
EquationMixin
¶ -
add_equation
(edge_or_node, equation, language='Python')¶ Method to add an equation to an output edge.
Parameters: - edge_or_node (list, str) – graph edge or node under consideration.
- equation (str) – equation to be added
- language (str) – equation language used for the equation
-
add_equation_label
(edge, labeling_method='node_label', language='Python')¶ Method to add an equation label to a edge that can (safely) be used as reference in an equation.
Parameters: - edge (str) – graph edge under consideration
- labeling_method (str) – select method for automatic label string determination (node_id or node_label)
- language (str) – equation language used for the equation label
Returns: label
Return type: str
-
add_equation_labels
(nodes, language='Python', labeling_method='node_id')¶ Method to add equation labels automatically to all input edges connected to the specified list of nodes
Parameters: - nodes (list) – list of nodes
- language (str) – equation language used for the equation label
- labeling_method (str) – select method for automatic label string determination (node_id or node_label)
-
VistomsMixin¶
-
class
kadmos.graph.mixin_vistoms.
VistomsMixin
¶ -
vistoms_add
(vistoms_dir, mpg=None, function_order=None, reference_file=None, compress=False, remove_after_compress=True, graph_id=None, replacement_id=None, xml_file=None)¶ Function to add a graph to a existing VISTOMS instance.
In one VISTOMS instance different graphs can be shown. For example it is possible to include different architectures for the same problem in one VISTOMS instance.
Parameters: - vistoms_dir (str) – directory of the VISTOMS directory to be used for addition
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG as XDSM (if None a DSM is created)
- function_order (list) – optional function order for the diagonal of the graph (only applicable for DSMs)
- reference_file (str) – file from which reference values are extracted (either full path or file in same folder)
- compress (bool) – setting whether to compress the final VISTOMS instance folder to a zip file
- remove_after_compress (bool) – setting whether to remove the original folder after compression
- replacement_id (basestr) – indentifier of the graph to be replaced
- xml_file (file) – Name of the CMDOWS xml-file
-
vistoms_create
(vistoms_dir, vistoms_version=None, mpg=None, function_order=None, reference_file=None, compress=False, remove_after_compress=True, graph_id=None, use_png_figs=False, file_refs=None, xml_file=None)¶ Function to create a new VISTOMS instance from a graph.
Parameters: - vistoms_dir (str) – directory of the VISTOMS directory to be created
- vistoms_version – version of the VISTOMS instance to be used (as stored in the package itself)
- vispack_version – str
- mpg (MdaoProcessGraph) – optional MPG graph to be saved with MDG as XDSM (if None a DSM is created)
- function_order (list) – optional function order for the diagonal of the graph (only applicable for DSMs)
- reference_file (str) – file from which reference values are extracted (either full path or file in same folder)
- compress (bool) – setting whether to compress the final VISTOMS instance folder to a zip file
- remove_after_compress (bool) – setting whether to remove the original folder after compression
- graph_id (basestring) – identifier of the new graph
- use_png_figs (bool) – setting whether to use the PNG figures instead of the SVG figures for local execution
- file_refs (dict) – setting to provide file references manually (to use VISTOMS on a server)
- xml_file (file) – Name of the CMDOWS xml file
-
CMDOWS¶
Below the CMDOWS file operations library is listed.
-
class
kadmos.cmdows.cmdows.
CMDOWS
(file_path=None, element=None)¶ Class for with various methods for checking and manipulating CMDOWS files
-
add_actor
(contact_uid, role)¶ Method to add a role element to the organization branch.
-
add_contact
(name, email, uid, company=None, department=None, function=None, address=None, telephone=None, country=None, roles=None)¶ Method to add a contact element to the organization branch.
-
add_dc
(uid, id, mode_id, instance_id, version, label)¶ Method to add a designCompetence element to the designCompetences branch.
-
add_dc_general_info
(dc_uid, description, status=None, creation_date=None, owner_uid=None, creator_uid=None, operator_uid=None, model_definition=None)¶ Method to add a general info element to a dc branch.
-
add_dc_inputs_element
(dc_uid, inputs_element)¶ Method to add a inputs element to a DC element.
-
add_dc_outputs_element
(dc_uid, outputs_element)¶ Method to add a outputs element to a DC element.
-
add_dc_performance_info
(dc_uid, precision=None, fidelity_level=None, run_time=None, verification=None)¶ Method to add a performance info element to a DC branch.
-
add_dc_remote_component_info
(dc_uid, single_or_multi_execution, job_name, remote_engineer, notification_message, data_exchange_dict=None)¶ Method to add a remote execution info element to a dc branch.
-
add_dc_verification
(dc_uid, method, verifier, result, date, version)¶ Method to add a verification to a DC
-
add_element_to_element_of_uid
(uid, element_to_add, expected_tag_uid_el=None, expected_tag_new_el=None)¶ Generic method to add a subelement to an element with a certain UID.
-
add_header
(creator, description, timestamp=None, fileVersion='0.0', cmdowsVersion='0.7')¶ Method to add a header to a CMDOWS file.
-
add_new_parameters_from_element
(parameters_element)¶ Method to add the new parameters based on a parameters element.
-
assert_element_tag
(el, expected_tag)¶ Method to assert that the tag of an element is as expected.
-
check
()¶ Method to execute all checks
-
check_references
()¶ Method to check if references are actually pointing to a uID in a CMDOWS file
-
check_schema
()¶ Method to check if a CMDOWS file adheres to its schema
-
check_uids
()¶ Method to check if all uIDs are actually unique in a CMDOWS file
-
ensure_abs_xpath
(xpath)¶ Method to ensure that the elements given by an absolute XPath exist.
-
get_design_competences_uids
()¶ Method to get a list of all the design competences UIDs present in the file.
-
get_element_of_uid
(uid, expected_tag=None)¶ Method to get the element based on a UID value.
-
get_executable_blocks_uids
()¶ Method to get a list of all the executable block UIDs present in the file.
-
get_inputs_uids
(exblock_uid)¶ Method to collect the inputs of a CMDOWS file executableBlock entry
-
get_mathematical_functions_uids
()¶ Method to get a list of all the mathematical functions UIDs present in the file.
-
get_outputs_uids
(exblock_uid)¶ Method to collect the outputs of a CMDOWS file executableBlock entry
-
get_parameters_uids
()¶ Method to get a list of all the parameter UIDs present in the file.
-
get_used_parameter_uids
()¶ Method to get a list of all the parameter UIDs used in the file.
-
get_xpath_of_uid
(uid, expected_tag=None)¶ Method to get the xpath based on a UID value.
-
remove_children_of_uid
(uid, children_to_remove='__all__', children_to_keep='__none__')¶ Method to remove the children of a CMDOWS file element based on a UID.
-
remove_children_of_xpath
(xpath, children_to_remove='__all__', children_to_keep='__none__')¶ Method to remove the children of a CMDOWS file element based on an XPath.
-
remove_contact
(contact_uid)¶ Method to remove a contact based on its UID.
-
remove_data_graph_element
()¶ Method to remove a dataGraph element from a CMDOWS file.
-
remove_element_based_on_uid
(uid, expected_tag=None)¶ Method to remove an element based on its UID.
-
remove_element_based_on_xpath
(xpath, expected_amount=None, expected_text=None, higher_level_removal=None)¶ Method to remove an element based on its XPath.
-
remove_in_and_outputs
(exblock_uid)¶ Method to remove the in- and outputs of a CMDOWS file executableBlock entry
-
remove_inputs
(exblock_uid)¶ Method to remove the inputs of a CMDOWS file executableBlock entry
-
remove_outputs
(exblock_uid)¶ Method to remove the outputs of a CMDOWS file executableBlock entry
-
remove_parameter
(param_uid)¶ Method to remove a parameter based on its UID.
-
remove_parameters
(params_uids)¶ Method to remove a list of parameters based on their UID.
-
remove_parameters_element
()¶ Method to remove a parameters element from a CMDOWS file.
-
remove_process_graph_element
()¶ Method to remove a processGraph element from a CMDOWS file.
-
remove_unused_contacts
()¶ Method to check if there are uID in CMDOWS file which are not refered to and remove them
-
remove_workflow_element
()¶ Method to remove a workflow element from a CMDOWS file.
-
resolve_uids
()¶ Method to rename duplicate UIDs in a CMDOWS file
-
save
(file_path=None, pretty_print=False, method='xml', xml_declaration=True, encoding='UTF-8')¶ Method to save a manipulated CMDOWS file
-
schema
()¶ Method to retrieve a schema either belonging to the CMDOWS file
-
simplify
()¶ Method to simplify everything
-
simplify_equations
()¶ Method to replace duplicate equations elements by a single equations element and refs to this element
-
version
()¶ Method to retrieve the version of the CMDOWS file
-
Utilities¶
Below the utilities used by KADMOS are listed.
General¶
-
kadmos.utilities.general.
assert_dict_keys
(dic, expected_keys, all_keys_required=False)¶ Method to assert that a dictionary has the expected keys and (optionally) to check if is has all the keys.
-
kadmos.utilities.general.
color_list
()¶ A list of distinguisable colors.
Returns: list with HTML Hex colors
-
kadmos.utilities.general.
convert_bytes
(num)¶ this function will convert bytes to MB…. GB… etc
-
kadmos.utilities.general.
dict_to_ord_dict
(dic, key_order)¶ Method to transform a Python dictionary into a Python ordered dictionary. Note that the key_order list can have items that are not present in the given dictionary. All keys of the dictionary should be in the order though.
-
kadmos.utilities.general.
export_as_json
(data, filename, indent=None, sort_keys=True, cwd=None)¶ Function to export a data object to a json file.
Parameters: - data (dict or list) – object with the data to be exported
- filename (basestring) – name of the json file
- indent (int) – number of spaces for one indentation
- sort_keys (bool) – option for sorting keys
- cwd (None, str) – current working directory
Returns: json file
Return type: file
-
kadmos.utilities.general.
file_size
(file_path)¶ this function will return the file size
-
kadmos.utilities.general.
file_size_MB
(file_path)¶ this function will return the file size
-
kadmos.utilities.general.
filter_group_vars
(group_dict, current_group_idx, filter_setting)¶ Method to get the variables of a local group.
Parameters: - group_dict –
- group_idx –
- filter_setting –
Returns: Return type:
-
kadmos.utilities.general.
format_string_for_latex
(string, prefix='', suffix='')¶ Function to format a string such that it can be used in LaTeX.
Parameters: - string (str) – string to be formatted
- prefix (basestring) – prefix to be placed in front of the string
- suffix (basestring) – suffix to be appended to the string
Returns: formatted string
Return type: basestring
-
kadmos.utilities.general.
format_string_for_vistoms
(string, prefix='', suffix='')¶ Function to format a string such that it can be used in VISTOMS.
Parameters: - string (str) – string to be formatted
- prefix (basestring) – prefix to be placed in front of the string
- suffix (basestring) – suffix to be appended to the string
Returns: formatted string
Return type: basestring
-
kadmos.utilities.general.
get_element_dict
(xpath, var_value=None, var_dim=None, include_reference_data=False)¶ Function to create a D3.js-type dictionary for a nested tree based on an xpath.
Parameters: - xpath – xpath for the element
- var_value – value of the element in a reference file
- var_dim – dimension of the element in a reference file
- include_reference_data – setting on whether reference data should be include in the path
Returns: nested dictionary
-
kadmos.utilities.general.
get_friendly_id
(uid_length)¶ Create an ID string we can recognise. (Think Italian or Japanese or Native American.)
-
kadmos.utilities.general.
get_group_vars
(sa, current_group_idx)¶ Method to get the variables with respect to t subgroup.
Parameters: - sa (dict) – system analysis dictionary
- current_group_idx (int) – index of the subgroup
Returns: multiple lists with variables
Return type: tuple
-
kadmos.utilities.general.
get_list_entries
(*args)¶ Utility to return only certain values of a given list based on the indices.
Parameters: args (list and int) – list and indices Returns: list with requested values at indices Return type: list
-
kadmos.utilities.general.
get_mdao_setup
(mdao_setup)¶ Simple function to specify the MDAO architecture and convergence type based on a single string.
Parameters: mdao_setup (str) – MDF-GS, MDF-J, IDF Returns: mdo_architecture, mda_type, allow_unconverged_couplings Return type: str
-
kadmos.utilities.general.
get_uid
(preference, uids)¶ Simple function to determine a valid uid which is not part of the uids list
Parameters: - preference (str) – preferred name for the uid
- uids (list) – list of existing uids
Returns: a valid uid which
Return type: str
-
kadmos.utilities.general.
get_unique_friendly_id
(used_ids, uid_length)¶ Return an ID that is not in our list of already used IDs.
-
kadmos.utilities.general.
hex_to_rgb
(value)¶ Function to translate a hex color string to an RGB color tuple.
Parameters: value (str) – HTML hex color Returns: RGB colors Return type: tuple
-
kadmos.utilities.general.
make_camel_case
(string, make_plural_option=False)¶ Function to make a string camelCase.
Parameters: - string (str) – non-camelcase string
- make_plural_option (bool) – pluralize camelcase string
Returns: camelcase string
Return type: str
-
kadmos.utilities.general.
make_plural
(string)¶ Function to convert a string to its plural form.
Parameters: string (str) – initial string Returns: plural string Return type: str
-
kadmos.utilities.general.
make_singular
(string)¶ Function to convert a string to its singular form.
Parameters: string (str) – initial string Returns: singular string Return type: str
-
kadmos.utilities.general.
open_file
(filename)¶ Utility to open a file cross-platform.
Parameters: filename – Filename including extension and path, e.g. ‘sampledir/samplefile.pdf’ Returns: An opened file
-
kadmos.utilities.general.
remove_if_exists
(input_list, entries_to_remove)¶ Utility to remove certain values from a list.
Parameters: - input_list (list) – initial list
- entries_to_remove (list) – values to remove
Returns: list with removed entries
Return type: list
-
kadmos.utilities.general.
test_attr_cond
(attr_value, operator, test_value)¶ Function to check a given conditional statement and return True or False.
Parameters: - attr_value (str, float, int) – value of the actual attribute
- operator (str) – conditional operator to be used (‘<’,’<=’,’==’,’!=’,’>=’,’>’, ‘in’)
- test_value (str, float, int) – value to which the attribute value should be compared.
Returns: result of the conditional statement.
Return type: bool
-
kadmos.utilities.general.
transform_data_into_strings
(data, keys_to_be_removed=[])¶ Utility function to transform certain data types in a dictionary into strings.
Parameters: - data (dict) – dictionary with data
- keys_to_be_removed (list) – list of keys that have to be removed from the dict
Returns: adjusted dictionary
Return type: dict
-
kadmos.utilities.general.
transform_string_into_format
(data, keys_to_be_removed=[])¶ Utility function to transform certain strings back into their original data format (NoneType, list, etc.).
Parameters: - data (dict) – dictionary with data
- keys_to_be_removed (list) – list of keys that have to be removed from the dict
Returns: adjusted dictionary
Return type: dict
-
kadmos.utilities.general.
translate_dict_keys
(dictionary, translations)¶ Utility to (recursively) translate all keys in a dictionary with a translation dictionary.
Parameters: - dictionary – dictionary to be translated
- translations – dictionary used for the translation
Returns: translated dictionary
-
kadmos.utilities.general.
translate_list
(l, dictionary)¶ Utility to quickly translate all elements in a list with a dictionary.
Parameters: - l – list to be translated
- dictionary – dictionary used for the translation
Returns: translated list
-
kadmos.utilities.general.
unmake_camel_case
(string, separator='_')¶ Function to make camelCase a string with separator (e.g. underscores).
Parameters: - string (str) – camelCase string
- separator – symbol/symbols used as separator
Returns: string with separator
Return type: str
XML¶
-
kadmos.utilities.xml.
Element
()¶ makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
Creates a new element associated with this parser.
-
kadmos.utilities.xml.
get_element_details
(tree, xpath)¶ Function to determine the value and dimension of an UXPath element in a reference file.
Parameters: - tree – ElementTree object used for finding the XPath
- xpath – XPath
Returns: element value and dimension
-
kadmos.utilities.xml.
get_uid_search_xpath
(uid)¶ Method to get the XPath expression for a UID which might contain quote characters.
Parameters: uid (str) – uID string Returns: XPath expression Return type: str
-
kadmos.utilities.xml.
merge
(a, b)¶ Recursive function to merge a nested tree dictionary (D3.js convention) into a full tree dictionary.
Parameters: - a (dict) – full dictionary in which a new element is merged
- b (dict) – element dictionary of the new element
Returns: merged dictionary
Return type: dict
-
kadmos.utilities.xml.
recursively_empty
(element)¶ Utility function to check recursively if a ElementTree object is empty.
Parameters: element – Input ElementTree object Returns: Result of the check
-
kadmos.utilities.xml.
recursively_stringify
(tree)¶ Utility function to recursively stringify a ElementTree object (for file comparison).
Parameters: tree – Input ElementTree object Returns: List of strings representing the ElementTree object
-
kadmos.utilities.xml.
recursively_unique_attribute
(element, attribute='uID')¶ Utility function to check recursively if the values of an attribute of an ElementTree object are unique.
Parameters: - element – Input ElementTree object
- attribute – Name of the attribute being checked for uniqueness
Returns: Result of the check
Strings¶
Printing¶
-
kadmos.utilities.printing.
print_in_table
(print_container, **kwargs)¶ This function prints a table using the provided data and the headers. The “tabulate” library is used.
print_container: container for iterables –> [[row1], [row2], …]
Returns:
-
kadmos.utilities.printing.
print_indexed_list
(*args, **kwargs)¶ This function prints an indexed column of the given arguments in the console. The provided message is printed above the indexed column. Can be used in combination with user_prompt_select_options().
example use: print_indexed_list(message = “These are the tools: “, index_bracket = “round”, *list_of_tools)
Parameters: - kwargs – message: Message printed above indexed column
- kwargs – index_bracket: Type of bracket used for indeces in list (“round” or “squared”), default is round
- args – Arguments listed in column by index
Returns:
KnowledgeBase¶
!! N.B. This class will be deprecated in future versions. !!
Below the full KADMOS KnowledgeBase class description can be found.
-
class
kadmos.knowledgebase.knowledgebase.
KnowledgeBase
(kb_dir_path, knowledge_base, ignoreFunctions=None)¶ Class that imports the data stored in a knowledge base. This is a start point for graph visualizations.
-
get_function_dependencies
(funcName, mode, inOut=None)¶ This function builds a directed graph (KadmosGraph object) for the specified function using the “networkx” package. If inOut argument is specified, only the input or output of the function will be included in the graph, otherwise both.
Param: funcName: function name for which the graph is generated; must be present in knowledge base. Param: inOut: default = None; if specified, must be “input” or “output” string. Specification of this argument enables the generation of the function graph with only input or output variables. Returns: functionGraph
-
get_function_graph
(funcName, inOut=None)¶ This function builds a directed graph (KadmosGraph object) for the specified function using the “networkx” package. If inOut argument is specified, only the input or output of the function will be included in the graph, otherwise both.
Param: funcName: function name for which the graph is generated; must be present in knowledge base. Param: inOut: default = None; if specified, must be “input” or “output” string. Specification of this argument enables the generation of the function graph with only input or output variables. Returns: functionGraph
-
get_kb_graphs
()¶ This class method generates all graphs for all present functions in the knowledge base.
Returns: self.functionGraphs
-
get_rcg
(name='RCG')¶ Function to create Maximal Connectivity Graph (Pate, 2014) by composing a list of graphs.
Returns: maximal connectivity graph (RCG)
-
print_circular_connections_in_log
()¶ This function prints the circular connections present in the graph.
Param: self.circularConnections: Dict with circular connections per tool Returns: print to console
-