Ideal Flow Package
Module contents
Submodules
IdealFlow.Command module
- class IdealFlow.Command.CommandLine
Bases:
Classifier
CommandLine class for executing training, prediction, and generation commands via command-line interface. Inherits from clf.Classifier.
This class processes command-line arguments for training, predicting, and generating data using the IFN classifier.
- ifnc
An instance of the clf.Classifier class to handle classification.
- Type:
clf.Classifier
- controller(argv: list) int
Processes command-line arguments and directs commands for training, prediction, and generation.
- __str_help__() str
Returns a help message explaining how to use the command-line interface.
Example
>>> ifnc = CommandLine() >>> ifnc.controller(["-t", "test", "y1", "x1 x2", 3]) >>> ifnc.controller(["-p", "test", "x1"])
- controller(argv: list) int
Processes command-line arguments and directs the appropriate commands for training, prediction, or generation.
Commands: -t : Training command -p : Prediction command -g : Generation command
- Parameters:
argv (list) – List of command-line arguments. Should include the command, classifier name, data, and optional parameters.
- Returns:
1 on success, 0 on failure.
- Return type:
int
- Raises:
IndexError – If there are insufficient command-line arguments.
Exception – For any general error during command execution.
Example
>>> ifnc = CommandLine() >>> ifnc.controller(["-t", "test", "y1", "x1 x2", "3"]) >>> ifnc.controller(["-p", "test", "x1"]) >>> ifnc.controller(["-g", "test", "y1"])
IdealFlow.Network module
Ideal Flow Network
@author: Kardi Teknomo (http://people.revoledu.com/kardi/)
- IFN Class
Representation of an expandable Ideal Flow Network.
The Network class provides various methods for analyzing and manipulating nodes, links, adjacency lists, matrices, and performing network analysis and metric, including path finding, cycles analysis, analyzing connectivity, signature, and more. This class is designed to handle flow networks and their properties through mathematical operations and context.
- Example:
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> n.add_link("New York","Chicago",1000) >>> n.add_link("Chicago","Denver",1000) >>> n.add_link("New York","Toronto",800) >>> n.add_link("New York","Denver",1900) >>> print(n) >>> n.show();
© 2018-2024 Kardi Teknomo
version 1.15
first build: Sep 3, 2018 last update: Oct 29,2024
- class IdealFlow.Network.IFN(name='')
Bases:
object
Represents an Ideal Flow Network (IFN).
This class provides methods for managing and visualizing a directed flow network.
- static abs_diff_capacity_flow(C: list, F: list, w1: float = 1, w2: float = 1) float
Return scalar cost of the total change between capacity and flow matrix.
- Parameters:
C (list) – The capacity matrix.
F (list) – The flow matrix.
w1 (float) – Weight for negative difference. Default is 1.
w2 (float) – Weight for positive difference. Default is 1.
- Returns:
The total cost.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> C = [[0, 2], [3, 0]] >>> F = [[0, 1], [2, 0]] >>> n = net.IFN() >>> cost = n.abs_diff_capacity_flow(C, F) >>> print(cost) 2.0
- add_first_link(startNode: str, endNode: str) None
Shortcut to add the first link in a training trajectory.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The ending node.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_first_link('a', 'b') >>> print(n.get_links) [['#z#', 'a'], ['a', 'b']]
- add_last_link(startNode: str, endNode: str) None
Shortcut to add the last link in a training trajectory.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The ending node.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_last_link('a', 'b') >>> print(n.get_links) [['a', 'b'], ['b', '#z#']]
- add_link(startNode: str, endNode: str, weight: float = 1) None
Creates a link between two nodes with the specified weight. If the link exists, the weight is updated.
- Parameters:
startNode (str) – The starting node of the link.
endNode (str) – The ending node of the link.
weight (float) – The weight of the link. Defaults to 1.
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> n.add_link('a', 'b', 5) >>> print(n.get_link_flow('a', 'b')) 5.0
- add_node(nodeName)
Adds a new node to the network if it does not already exist. Useful for adding an isolated node
- Parameters:
node (str) – The name or identifier of the node to be added.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_node('a') >>> print('a' in n.listNodes) True
- static add_random_ones(A: ndarray, m: int = 6) ndarray
Add random ones to a matrix until the total number of ones is equal to m.
Add 1 to the matrix A at random cell location such that the total 1 in the matrix is equal to m. If total number of 1 is less than m, it will not be added. It will not add anything if the current number of ones is already larger than m
- Parameters:
A (np.ndarray) – The input square matrix.
m (int) – The number of ones to add. Default is 6.
- Returns:
The updated matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> A = np.zeros((3, 3)) >>> updated_A = n.add_random_ones(A, 4) >>> print(updated_A) [[0 1 0] [1 0 0] [0 1 1]]
- static adj_list_to_matrix(adjL: dict) ndarray
Convert an adjacency list to a weighted square matrix.
- Parameters:
adjL (dict) – The adjacency list.
- Returns:
The weighted square matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> adjL = {'a': {'b': 1, 'c': 2}, 'b': {'c': 3}, 'c': {}} >>> matrix = n.adj_list_to_matrix(adjL) >>> print(matrix) [[0 1 2] [0 0 3] [0 0 0]]
- static adjacency_to_ideal_flow(A: list, kappa: float = 1) list
Convert adjacency matrix to ideal flow matrix.
- Parameters:
A (list) – The adjacency matrix.
kappa (float) – The kappa parameter.
- Returns:
The ideal flow matrix.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> A = [[0, 2], [3, 0]] >>> n = net.IFN() >>> ideal_flow = n.adjacency_to_ideal_flow(A) >>> print(ideal_flow)
- static adjacency_to_stochastic(A: list) list
Convert adjacency matrix to stochastic matrix of equal outflow distribution.
- Parameters:
A (list) – The adjacency matrix.
- Returns:
The stochastic matrix.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> A = [[0, 2], [3, 0]] >>> n = net.IFN() >>> stochastic_matrix = n.adjacency_to_stochastic(A) >>> print(stochastic_matrix) [[0, 1], [1, 0]]
- all_shortest_path() tuple
Return the matrix of all shortest paths using the Floyd-Warshall algorithm. note: this is min weight path, not min number of links.
- Returns:
A tuple containing the shortest path matrix and the list of nodes.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.all_shortest_path() (array([[0., 1., 2.], [inf, 0., 1.], [inf, inf, 0.]]), ['a', 'b', 'c'])
- static alphabet_list(n: int) list
Convert an integer to its corresponding ASCII character. Useful to generate list of nodes.
- Parameters:
n (int) – The number of characters to generate.
- Returns:
A list of characters from ‘a’ to the n-th character.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> alphabet = n.alphabet_list(3) >>> print(alphabet) ['a', 'b', 'c']
- assign(trajectory: list) None
Assign a trajectory to the network by updating link weights.
- Alias:
set_path(rajectory,1)
- Parameters:
trajectory (list) – A list of nodes representing the trajectory (node sequence) to be assigned.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.assign(['a', 'b', 'c'])
- static assign_adjacency_list(value: float, trajectory: str, is_cycle: bool = True) dict
Assign a value to a sequence of nodes, creating an adjacency list.
- Parameters:
value (float) – The value to assign to the edges in the sequence.
trajectory (str) – The sequence of nodes.
is_cycle (bool) – Whether the sequence represents a cycle (default is True).
- Returns:
The adjacency list representation of the trajectory.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.assign_adjacency_list(1.0, "abc") {'a': {'b': 1.0}, 'b': {'c': 1.0}, 'c': {'a': 1.0}}
- static assign_cycle_to_matrix(F: ndarray, cycle: list, value: int) None
Assign a value to the edges in a cycle within the flow matrix. return F by reference
- Parameters:
F (np.ndarray) – The flow matrix.
cycle (list) – The cycle as a list of node indices.
value (number) – The value to assign to the edges.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = np.zeros((3, 3), dtype=int) >>> n.assign_cycle_to_matrix(F, [0, 1, 2], 5) >>> F array([[0, 5, 0], [0, 0, 5], [5, 0, 0]]) >>> F = [[0, 0], [0, 0]] >>> cycle = [0, 1] >>> n.assign_cycle_to_matrix(F, cycle, 1) [[0, 1], [1, 0]]
- association_predict_actor_net(netActor, netSystem)
- static association_predict_trajectory(trajectory: list, net: dict) tuple
Predict associations of itemset from a trajectory based on the network’s direct links.
Given a trajectory and IFN, predict the association of itemset based on direct link from trajectory complete graph to the IFN that is not in the complete graph.
- Parameters:
trajectory (list) – A list of nodes representing the trajectory.
net (dict) – The IFN.
- Returns:
A dictionary of predictions (item -> flow), total support, and total confidence.
prediction = sorted dictionary of item: flow supp=count of flow in trajectory items conf=count of flow in all direct links
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.association_predict_trajectory(['a', 'b'], {})
- static association_train(trajectory: list, net: dict) dict
Train the IFN for association based on a trajectory by creating a complete graph and overlaying it onto the IFN. It assumes to have two ways link permutation.
- Parameters:
trajectory (list) – A list of nodes representing the trajectory.
net (dict) – The initial IFN (or an empty IFN).
- Returns:
The updated IFN.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.association_train(['a', 'b', 'c'], {})
- property average_flow: float
Return the internal average flow in the network
Example
>>> import IdealFlow.Network as net >>> C = [[1, 2], [3, 4]] >>> n = net.IFN() >>> n.set_matrix(C,['a','b']) >>> print(n.average_flow)
- static average_flow_matrix(F: list) float
Compute the average flow value of a flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The average flow value.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[1, 2], [3, 4]] >>> n = net.IFN() >>> avg_flow_value = n.average_flow_matrix(F) >>> print(avg_flow_value)
- property average_node_entropy: float
Compute average node entropy from stochastic matrix.
- Parameters:
S (list) – The stochastic matrix.
- Returns:
The average node entropy.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[0, 2], [2, 1]] >>> n = net.IFN() >>> n.set_matrix(F,['a','b']) >>> avg_entropy = n.average_node_entropy >>> print(avg_entropy)
- static average_node_entropy_matrix(F: list) float
Compute average node entropy for a given flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The average node entropy.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[2, 3], [1, 4]] >>> n = net.IFN() >>> avg_entropy = n.average_node_entropy_matrix(F) >>> print(avg_entropy)
- property average_node_entropy_ratio: float
Return the internal average node entropy ratio of flows in the network
Example
>>> import IdealFlow.Network as net >>> C = [[1, 2], [3, 4]] >>> n = net.IFN() >>> n.set_matrix(C,['a','b']) >>> print(n.average_node_entropy_ratio)
- static average_node_entropy_ratio_matrix(F: list) float
Compute average node entropy ratio for a given flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The average node entropy ratio.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[2, 3], [1, 4]] >>> n = net.IFN() >>> ratio = n.average_node_entropy_ratio_matrix(F) >>> print(ratio)
- backtracking(startNode: str, endNode: str) list
Perform DFS traversal with backtracking to find a path from startNode to endNode.
This method is specifically designed to find a valid path between two nodes. It explores routes, and if it encounters a dead-end or an invalid path, it backtracks to explore other possible routes.
Use this method when you want to find an exact path between two nodes, potentially with constraints.
- Parameters:
startNode (str) – The starting node of the path.
endNode (str) – The target node to reach.
- Returns:
A list of nodes forming the valid path from startNode to endNode using backtracking.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.add_link('a', 'd', 1) >>> n.backtracking('a', 'c') ['a', 'b', 'c']
- backtracking_cycle_limit(startNode, endNode, max_internal_cycle, visited_nodes, cycles, path=None)
Perform DFS traversal with backtracking to find a path from startNode to endNode, limiting the number of internal cycles.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The target node.
max_internal_cycle (int) – The maximum number of internal cycles allowed.
visited_nodes (set) – The set of nodes already visited in the path.
cycles (dict) – A dictionary containing the current cycle count.
path (list) – The current path.
- Returns:
A list of nodes forming the path from startNode to endNode.
- Return type:
list
- bfs(startNode: str) list
Perform Breadth-First Search (BFS) traversal starting from startNode.
- Parameters:
startNode (str) – The starting node.
- Returns:
A list of nodes visited during BFS traversal.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.bfs('a') ['a', 'b', 'c']
- bfs_until(startNode: str, endNode: str) list
Perform Breadth-First Search (BFS) traversal starting from startNode until endNode is reached.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The target node.
- Returns:
A list of nodes visited during BFS traversal until endNode is reached.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.bfs_until('a', 'c') ['a', 'b', 'c']
- static binarized_matrix(M: list) list
Convert the matrix to a binary (0, 1) matrix.
- Parameters:
M (list) – The input matrix.
- Returns:
The binarized (0, 1) version of the matrix.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> matrix = [[0, 2], [1, 0]] >>> bin_matrix = n.binarized_matrix(matrix) >>> print(bin_matrix) [[0, 1], [1, 0]]
- static canonize(cycle: str) str
Canonize a string cycle by rotating it to its lexicographically smallest form.
- Parameters:
cycle (str) – The string cycle, each letter represent a node.
- Returns:
The canonized string cycle.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> cycle = 'bca' >>> canonized = n.canonize(cycle) abc >>> n.canonize("fde") def
- static canonize_cycle_dict(cycle_dict: dict) dict
Canonize a cycle dictionary by sorting and normalizing the cycles.
- Parameters:
cycle_dict (dict) – The cycle dictionary.
- Returns:
The canonized cycle dictionary.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> cycle_dict = {'bca': 1, 'cab': 2} >>> n.canonize_cycle_dict(cycle_dict) {'abc': 3}
- static canonize_signature(signature: str) str
Canonize a network signature by relabeling the nodes and sorting the cycles.
- Parameters:
signature (str) – The network signature.
- Returns:
The canonized signature.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "bca + cab" >>> n.canonize_signature(signature) 2abc
- static capacity_to_adjacency(matrix)
Convert a non-negative matrix to a binary (0, 1) adjacency matrix.
- Parameters:
matrix (list of list of int/float) – The input matrix.
- Returns:
The adjacency matrix.
- Return type:
np.array
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> C = [[1, 2], [3, 4]] >>> n.capacity_to_adjacency(C)
Alias of
to_adjacency_matrix()
See also
- static capacity_to_balance_inflow_outflow(C, lambda_=0.5)
Return ideal flow matrix balancing inflow and outflow from capacity matrix.
- Parameters:
C (list of list of int/float) – The capacity matrix.
lambda (float) – The lambda parameter to balance inflow and outflow.
- Returns:
The balanced ideal flow matrix.
- Return type:
list of list of int/float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> C = [[1, 2], [0, 1]] >>> n.capacity_to_balance_inflow_outflow(C)
- static capacity_to_congestion(C: list, kappa: float, capacity_multiplier: float) list
Compute congestion matrix from capacity matrix and kappa.
- Parameters:
C (list) – The capacity matrix.
kappa (float) – The kappa parameter.
capacity_multiplier (float) – The capacity multiplier.
- Returns:
The congestion matrix.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> C = [[3, 2], [5, 0]] >>> n = net.IFN() >>> congestion = n.capacity_to_congestion(C, 1.5, 0.75) >>> print(congestion)
- static capacity_to_ideal_flow(C: ndarray, kappa: float = 1) ndarray
Convert a capacity matrix into an ideal flow matrix.
- Parameters:
C (np.ndarray) – The capacity matrix.
kappa (float) – The total flow. Default is 1.
- Returns:
The ideal flow matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> C = np.array([[0, 2], [3, 0]]) >>> F = n.capacity_to_ideal_flow(C) >>> print(F) [[0.4 0.6] [0.5 0.5]]
- static capacity_to_stochastic(C, method='row', alpha=1, beta=1e-05, epsilon=1e-10)
Convert a capacity matrix into a stochastic matrix using various methods.
- Parameters:
C (list of list of int/float or 2D np.array) – The capacity matrix.
method (str) – Method for conversion: ‘row’, ‘col’, ‘alpha_beta_row’, ‘alpha_beta_col’.
are (Options) –
‘row’: Converts to a row stochastic matrix.
’col’: Converts to a column stochastic matrix.
’alpha_beta_row’: Uses the alpha and beta parameters for row-wise transformation.
’alpha_beta_col’: Uses the alpha and beta parameters for column-wise transformation.
alpha (float) – The alpha parameter, used only for ‘alpha_beta’ and ‘alpha_beta_col’ methods.
beta (float) – The beta parameter, used only for ‘alpha_beta’ and ‘alpha_beta_col’ methods.
epsilon (float) – A small value to avoid division by zero, used in ‘row’ and ‘col’ methods.
- Returns:
The resulting stochastic matrix.
- Return type:
np.array
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> C = [[1, 2], [3, 4]] >>> n.capacity_to_stochastic(C, method='row')
- static cardinal_ifn_signature(A: list) str
Find the cardinal IFN signature, which represents the minimal set of cycles that can fully describe the network.
- Parameters:
A (list of list of float) – The input matrix representing the flow between nodes.
- Returns:
The cardinal IFN signature.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> A = [[0, 1, 0], [0, 0, 1], [1, 0, 0]] >>> n.cardinal_ifn_signature(A) 'abc'
- static change_flow_in_cycle(F: list, cycle: tuple, change: float = 1) list
Add or subtract flow matrix based on the cycle.
- Parameters:
F (list) – The flow matrix.
cycle (tuple or str) – tuple of indices in a cycle or string cycle term
change (float) – The amount to change the flow. Default is 1.
- Returns:
The updated flow matrix.
- Return type:
list
See also
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F=[[0, 3, 0], [2, 0, 1], [1, 0, 0]] >>> adjL=n.flow_matrix_to_adj_list(F) >>> n.find_all_cycles_in_adj_list(adjL) [(0, 1), (0, 1, 2)] >>> cycle =(0, 1, 2) >>> F = n.change_flow_in_cycle(F, cycle, change=2) >>> print(F) [[0, 5, 0], [2, 0, 3], [3, 0, 0]] >>> cycle =(0, 1) >>> F = n.change_flow_in_cycle(F, cycle, change=2) print(F) [[0, 7, 0], [4, 0, 3], [3, 0, 0]]
- color_graph(M: list, color: list, pos: int, c: int) bool
Determines if the adjacency matrix can be colored into two colors (bipartite).
- Parameters:
M (list of list) – The adjacency matrix representing the graph.
color (list) – The color array, with -1 representing uncolored nodes.
pos (int) – The current node position.
c (int) – The color to assign (0 or 1).
- Returns:
True if the graph can be colored with two colors, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> M = [[0, 1], [1, 0]] >>> n.set_matrix(M,['a','b']) >>> color = [-1] * len(M) >>> n.color_graph(M, color, 0, 0) True
- static combinations(N: int) list
Generates all combinations of the letters ‘a’ through ‘z’ up to length N.
- Parameters:
N (int) – The length of the desired combinations.
- Returns:
The list of combinations.
- Return type:
list of str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.combinations(2) ['a', 'b', 'ab'] >>> n.combinations(3) ['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
- static complement(net: IFN) IFN
Return the complement of the given network (complete graph minus the network).
- Parameters:
net (IFN) – The network to complement.
- Returns:
The complement of the network.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> result_net = n.complement(n)
- static complete_graph(trajectory: list, weight: int = 1) IFN
Create a complete graph from a trajectory list, with two-way links. If trajectory has only one item, create a node. A complete graph weight 1 is always an IFN.
- Parameters:
trajectory (list) – List of nodes.
weight (int) – The weight of each link. Default is 1.
- Returns:
A new complete graph.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> trajectory = ['A', 'B', 'C'] >>> complete_net = n.complete_graph(trajectory)
- static compose(signature: str) list
Compose a flow matrix from a network signature.
- Parameters:
signature (str) – The network signature.
- Returns:
The composed flow matrix.
- Return type:
list of list of int/float
See also
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "abc" >>> n.compose(signature) array([[0., 1., 0.], [0., 0., 1.], [1., 0., 0.]]) >>> n.compose('ab+ba+cab') array([[0., 3., 0.], [2., 0., 1.], [1., 0., 0.]])
- static congestion(F: ndarray, C: ndarray) ndarray
Compute the congestion matrix from flow and capacity matrices. congestion matrix is element wise division of flow/capacity, except zero remain zero
- Parameters:
F (np.ndarray) – The flow matrix.
C (np.ndarray) – The capacity matrix.
- Returns:
The congestion matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = np.array([[1, 2], [2, 1]]) >>> C = np.array([[2, 2], [2, 2]]) >>> congestion_matrix = n.congestion(F, C) >>> print(congestion_matrix) [[0.5 1. ] [1. 0.5]]
- static copy_dict(dic: dict) dict
Create a shallow copy of a nested dictionary.
- Parameters:
dic (dict) – The dictionary to copy.
- Returns:
A copy of the dictionary.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> d = {'a': [1, 2], 'b': {'c': 3}} >>> copy_d = n.copy_dict(d) >>> copy_d == d True >>> copy_d is d False
- property cov_flow: float
Compute the internal coefficient of variation of flows in the network.
- Returns:
The coefficient of variation of flow.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> C = [[1, 2], [3, 4]] >>> n = net.IFN() >>> n.set_matrix(C,['a','b']) >>> print(n.cov_flow)
- static cov_flow_matrix(F: list) float
Compute the coefficient of variation of flow values in a flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The coefficient of variation.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[1, 2], [3, 4]] >>> n = net.IFN() >>> coef_var = n.cov_flow_matrix(F) >>> print(coef_var)
- static create_node_mapping(net_signature: str) dict
Create a node mapping for a network signature. When the signature contains jump of nodes, we need to create node mapping.
- Parameters:
net_signature (str) – The network signature.
- Returns:
The node mapping.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "abc + bcd" >>> mapping = n.create_node_mapping(signature) >>> print(mapping)
- static cycle_dict_to_signature(cycle_dict: dict) str
Convert a cycle dictionary to a network signature. The keys of cycle_dict input must be in canonical cycle. The signature is a string of the form “abc + bcd” where a, b, c, d are nodes.
- Parameters:
cycle_dict (dict) – The canonical cycle dictionary.
- Returns:
The network signature.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> cycle_dict = {'abc': 1, 'bcd': -1} >>> signature = n.cycle_dict_to_signature(cycle_dict) >>> print(signature) 'abc + (-bcd)' >>> cycle_dict = {'ac': 1, 'acd': 3, 'bc': 2} >>> n.cycle_dict_to_signature(cycle_dict) 'ac + 3acd + 2bc'
- cycle_length(cycle: list) int
Return the number of edges in the cycle if it forms a valid cycle, otherwise return 0.
- Parameters:
cycle (list) – A sequence of nodes forming a cycle.
- Returns:
The number of edges in the cycle, or 0 if not a cycle.
- Return type:
int
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.cycle_length(['a', 'b', 'a']) 0 >>> n.add_link('b', 'a', 1) >>> n.cycle_length(['a', 'b', 'a']) 2
- cycle_sum_weight(cycle: list) float
Return the sum of weights in the cycle if it forms a valid cycle, otherwise return 0.
- Parameters:
cycle (list) – A sequence of nodes forming a cycle.
- Returns:
The sum of weights in the cycle, or 0 if not a cycle.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'a', 2) >>> n.cycle_sum_weight(['a', 'b', 'a']) 3
- static decimal_to_fraction(decimal: float, tolerance: float = 1e-06) tuple
Converts a decimal to its closest fraction using a form of the Stern-Brocot tree approach.
- Parameters:
decimal (float) – The decimal number to convert.
tolerance (float) – Precision tolerance. (default: use 6 decimal digits to make it precise)
- Returns:
The numerator and denominator of the fraction.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.decimal_to_fraction(0.75) (3, 4) >>> n.decimal_to_fraction(0.333333) (1, 3) >>> n.decimal_to_fraction(0.111111) (1, 9) >>> import numpy as np >>> n.decimal_to_fraction(np.pi) (355, 113)
- static decompose(matrix: list) str
Decompose a ideal flow matrix into a network signature.
- Parameters:
F (list of list of int/float) – The flow matrix.
- Returns:
The decomposed network signature.
- Return type:
str
- Raises:
ValueError – If F is not an ideal flow matrix.
See also
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = [[3, 1], [1, 0]] >>> signature = n.decompose(F) >>> print(signature) 3a + ab >>> F=[[0, 3, 0], [2, 0, 1], [1, 0, 0]] >>> n.decompose(F) abc + 2ab
- delete_link(startNode: str, endNode: str) None
Deletes a link between two nodes. If the starting node becomes isolated, it is removed.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The ending node.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.delete_link('a', 'b') >>> print(n.get_link_flow('a', 'b')) nan
- delete_node(nodeName)
Deletes a node from the network and all connected links.
- Parameters:
node (str) – The name or identifier of the node to be deleted.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a','b') >>> n.add_link('c','b') >>> n.delete_node('b') >>> print(n)
- property density: float
Calculate the density of the graph, which is the ratio of the number of edges to the number of possible edges in a complete graph. It measures how close a given graph is to a complete graph. The maximal density is 1, if a graph is complete.
- Returns:
The density of the graph.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('a', 'c', 2) >>> n.density 0.6666666666666666
- dfs(startNode: str) list
Perform Depth-First Search (DFS) traversal starting from startNode. This method explores the graph by visiting a node, then recursively visiting its unvisited neighbors. The traversal continues until all reachable nodes from startNode are visited. It doesn’t look for a specific destination.
Use this method when you want to visit all connected nodes. It will visit nodes until all have been explored (order may vary based on graph structure).
- Parameters:
startNode (str) – The starting node.
- Returns:
A list of nodes visited during DFS traversal.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b') >>> n.add_link('b', 'c') >>> n.add_link('a', 'd') >>> n.dfs('a') ['a', 'd', 'b', 'c']
- static dfs_adj_list(v, start, visited, stack, adj_list, cycles, nodes)
Perform DFS to find cycles in the adjacency list.
- dfs_until(startNode: str, endNode: str) list
Perform Depth-First Search (DFS) traversal starting from startNode until endNode is reached.
This method behaves like DFS but halts as soon as the specified endNode is encountered. It’s useful when you want to find a node but don’t need to explore the entire graph.
Use this method when you’re looking for a node and want to stop traversal once you find it.
- Parameters:
startNode (str) – The starting node for the DFS traversal.
endNode (str) – The target node at which the traversal stops.
- Returns:
A list of nodes visited during DFS traversal until the endNode is reached.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.add_link('a', 'd', 1) >>> n.dfs_until('a', 'c') ['a', 'b', 'c']
- property diameter: int
Compute the diameter of the network, which is the longest shortest path between any pair of nodes. The diameter d of a graph is defined as the maximum eccentricity of any vertex in the graph. The diameter is the length of the shortest path between the most distanced nodes. To determine the diameter of a graph, first find the shortest path between each pair of vertices. The greatest length of any of these paths is the diameter of the graph.
- Returns:
The diameter of the network.
- Return type:
int
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('a', 'c', 2) >>> n.diameter 1
- static difference(net2: IFN, net1: IFN) IFN
Subtract the link flow of net1 from net2.
Reduce link flow of net2 based on net1 = set difference (net2-net1)
- Parameters:
- Returns:
The updated network after the subtraction.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> base_net, diff_net = net.IFN(), net.IFN() >>> result_net = n.difference(base_net, diff_net)
- duplicate() IFN
Create a duplicate of the current network. (not the same reference)
- Returns:
A new network that is a deep copy of the current one.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> duplicate_net = n.duplicate()
- static equivalent_ifn(F: ndarray, scaling: float, is_rounded: bool = False) ndarray
Compute an equivalent ideal flow network with the given scaling.
- Parameters:
F (np.ndarray) – The flow matrix.
scaling (float) – The scaling factor.
is_rounded (bool) – Whether to round the result. Default is False.
- Returns:
The equivalent ideal flow matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = np.array([[0.2, 0.3], [0.4, 0.1]]) >>> scaled_F = n.equivalent_ifn(F, scaling=2) >>> print(scaled_F) [[0.4 0.6] [0.8 0.2]]
- static excel_col_to_num(col: str) int
Convert an Excel-style column label to a number.
- Parameters:
col (str) – The column label (e.g., ‘a’, ‘aa’).
- Returns:
The corresponding number.
- Return type:
int
- Raises:
ValueError – If the column contains non-alphabetic characters.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.excel_col_to_num('a') 1 >>> n.excel_col_to_num('aa') 27
- static extract_first_k_terms(cycle_str: str, k: int) str
Extracts the first k terms from a cycle string.
- Parameters:
cycle_str (str) – The cycle string with terms separated by ‘ + ‘.
k (int) – The number of terms to extract.
- Returns:
A new cycle string with the first k terms.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.extract_first_k_terms('a + b + c + d', 2) 'a + b'
- static extract_last_k_terms(cycle_str: str, k: int) str
Extracts the last k terms from a cycle string.
- Parameters:
cycle_str (str) – The cycle string with terms separated by ‘ + ‘.
k (int) – The number of terms to extract.
- Returns:
A new cycle string with the last k terms.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.extract_last_k_terms('a + b + c + d', 2) 'c + d'
- static find_a_cycle(start_node: str, target_node: str, adjL: dict) str
Find a cycle in the adjacency list starting from a given node.
- Parameters:
start_node (str) – The starting node.
target_node (str) – The target node to find the cycle.
adjL (dict) – The adjacency list, where keys are nodes and values are dictionaries of neighbors.
- Returns:
The cycle found as a string, or None if no cycle is found.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> adjL = {'a': {'b': 1}, 'b': {'a': 1, 'c': 1}, 'c': {'b': 1}} >>> n.find_a_cycle('a', 'c', adjL) 'abc'
- static find_all_cycles_in_adj_list(adjL: dict) list
Find all cycles in a given adjacency list.
- Parameters:
adjL (dict) – The adjacency list.
- Returns:
The list of cycles found in the adjacency list.
- Return type:
list of str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> adjL = {'a': {'b': 1}, 'b': {'c': 1}, 'c': {'a': 1}} >>> cycles = n.find_all_cycles_in_adj_list(adjL) >>> print(cycles) [('a', 'b', 'c')] >>> adj_list={0: {1: 3}, 1: {0: 2, 2: 1}, 2: {0: 1}} >>> n.find_all_cycles_in_adj_list(adj_list) [(0, 1), (0, 1, 2)] >>> adjL={0: {0: 3, 1: 1}, 1: {0: 1}} >>> n.find_all_cycles_in_adj_list(adjL) [(0,), (0, 1)]
- static find_all_cycles_in_matrix(matrix: list) list
Return list of all possible cycles from the weighted adjacency matrix as cycle terms.
- Parameters:
matrix (list of list of int/float) – The input matrix.
- Returns:
A list of cycles terms found in the matrix.
- Return type:
list of tuple of str
See also
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> matrix = [[0, 3, 0],[2, 0, 1],[1, 0, 0]] >>> n.find_all_cycles_in_matrix(matrix) ['ab', 'abc']
- find_all_paths(startNode: str, endNode: str, path: list = []) list
Find all possible paths from the startNode to the endNode.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The target node.
path (list) – The current path (used for recursion).
- Returns:
A list of all possible paths from startNode to endNode.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.find_all_paths('a', 'c') [['a', 'b', 'c']]
- static find_all_permutation_cycles(matrix: list) set
List all cycles in the adjacency matrix as strings, considering all permutations of cycles.
- Parameters:
matrix (list of list of int/float) – The adjacency matrix of the graph.
- Returns:
A set of cycles as strings.
- Return type:
set
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> matrix = [[0, 1], [1, 0]] >>> n.find_all_permutation_cycles(matrix) {'ab', 'ba'}
- static find_all_walks_in_matrix(matrix: list) list
Find all walks in a given matrix.
- Parameters:
matrix (list of list of int/float) – The input matrix.
- Returns:
A list of walks found in the matrix.
- Return type:
list of str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> matrix = [[1, 1], [1, 0]] >>> walks = n.find_all_walks_in_matrix(matrix) >>> print(walks) # Output: ['ab']
- static find_cardinal_ifn_signature_exhaustive(A: list) str
Find the cardinal IFN signature using exhaustive search.
- Parameters:
A (list of list of float) – The input matrix representing the flow between nodes.
- Returns:
The cardinal IFN signature.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> A = [[0, 1, 0], [0, 0, 1], [1, 0, 0]] >>> n.find_cardinal_ifn_signature_exhaustive(A) 'abc'
- static find_cycles(matrix: list) list
Finds all cycles in a given adjacency matrix and returns them in canonical form.
- Parameters:
matrix (list of list) – Adjacency matrix representing the digraph.
- Returns:
List of unique cycles in canonical form.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> matrix = [[0, 1], [1, 0]] >>> n.find_cycles(matrix) ['ab']
- static find_element_in_list(element, list_element: list) list
Find all indices of an element in a list.
- Parameters:
element – The element to find.
list_element (list) – The list to search in.
- Returns:
List of indices where the element is found.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.find_element_in_list(1, [1, 2, 1, 3]) [0, 2]
- static find_key_in_dict(val, dic: dict) str
Find the first key in a dictionary that matches a given value.
- Parameters:
val – The value to search for.
dic (dict) – The dictionary to search in.
- Returns:
The key corresponding to the given value, or None if not found.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> d = {'a': 1, 'b': 2} >>> n.find_key_in_dict(2, d) 'b' >>> n.find_key_in_dict(2, {'a': 1, 'e': 2, 'c': 2}) 'e'
- find_path(startNode: str, endNode: str, path: list = []) list
Find a path from the startNode to the endNode using Depth First Search (DFS).
- Parameters:
startNode (str) – The starting node.
endNode (str) – The target node.
path (list) – The current path (used for recursion).
- Returns:
A list of nodes representing the path from startNode to endNode.
- Return type:
list
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.find_path('a', 'c') ['a', 'b', 'c']
See also
- find_path_cycle_limit(startNode, endNode, max_internal_cycle, visited_nodes, node_visit_counts=None, path=None)
Find a path from startNode to endNode using DFS with backtracking, limiting the number of internal cycles.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The target node.
max_internal_cycle (int) – The maximum number of internal cycles allowed.
visited_nodes (set) – The set of nodes already visited in the overall path.
node_visit_counts (dict) – Dictionary of node visit counts in the current recursive path.
path (list) – The current path.
- Returns:
A list of nodes forming the path from startNode to endNode.
- Return type:
list
- static find_pivot_type(cycle1: str, cycle2: str) str
Determine the type of pivot (common node or path) between two cycles.
- Parameters:
cycle1 (str) – The first cycle.
cycle2 (str) – The second cycle.
- Returns:
The type of pivot (node, link or path).
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> cycle1 = "abc" >>> cycle2 = "bcd" >>> result = n.find_pivot_type(cycle1, cycle2) >>> print(result) # Output: 'link: bc'
- static find_pivots(signature: str) list
Find pivots in a network signature, which are common nodes between cycles.
- Parameters:
signature (str) – The network signature.
- Returns:
A list of pivots between cycles.
- Return type:
list of dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "abc + bcd + cde" >>> pivots = n.find_pivots(signature) >>> print(pivots)
- static flow_matrix_to_adj_list(F: list) dict
Convert a flow matrix to an adjacency list.
- Parameters:
F (list of list of int/float) – The flow matrix.
- Returns:
The adjacency list representation of the flow matrix.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = [[3, 1], [1, 0]] >>> adj_list = n.flow_matrix_to_adj_list(F) >>> print(adj_list) {0: {0: 3, 1: 1}, 1: {0: 1}} >>> F=[[0, 3, 0], [2, 0, 1], [1, 0, 0]] >>> n.flow_matrix_to_adj_list(F) {0: {1: 3}, 1: {0: 2, 2: 1}, 2: {0: 1}}
- static flows_in_cycle(F: list, cycle: tuple) list
Return list of flows in a cycle.
- Parameters:
F (list) – The flow matrix.
cycle (tuple or string) – tuple of indices in a cycle or string cycle term
- Returns:
The list of flows in the cycle.
- Return type:
list
See also
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = [[3, 1], [1, 0]] >>> adjL=n.flow_matrix_to_adj_list(F) >>> n.find_all_cycles_in_adj_list(adjL) [(0,), (0, 1)] >>> cycle = (0, 1) >>> n.flows_in_cycle(F,cycle) [1, 1] >>> cycle = (0,) >>> n.flows_in_cycle(F,cycle) [3] >>> F=[[0, 3, 0], [2, 0, 1], [1, 0, 0]] >>> adjL=n.flow_matrix_to_adj_list(F) >>> n.find_all_cycles_in_adj_list(adjL) [(0, 1), (0, 1, 2)] >>> cycle = (0, 1) >>> n.flows_in_cycle(F,cycle) [3, 2] >>> cycle = (0, 1, 2) >>> n.flows_in_cycle(F,cycle) [3, 1, 1] >>> cycles=n.find_all_cycles_in_matrix(F) >>> print(cycles) [('a', 'b', 'c'), ('a', 'b')] >>> n.flows_in_cycle(F,cycle[0]) [3, 1, 1] >>> n.flows_in_cycle(F,cycle[1]) [3, 2]
- static form_link_cycle_matrix(F: ndarray) tuple
Forms the link-cycle matrix H and the link flow vector y.
- Parameters:
F (np.ndarray) – Flow matrix representing the network.
- Returns:
- A tuple containing the link-cycle matrix H, the link flow vector y,
a list of cycles, and a list of links.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = np.array([[0, 1], [1, 0]]) >>> H, y, cycles, links = n.form_link_cycle_matrix(F)
- static from_base62(s: str) int
Convert a base62 string to a integer number.
- Parameters:
s (str) – The base62 string.
- Returns:
The corresponding number.
- Return type:
int
- Raises:
ValueError – If the string contains invalid base62 characters.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.from_base62('0') 0 >>> n.from_base62('A') 36 >>> n.from_base62('10') 62
- generate(startNode: str = None, is_cycle=True, allow_internal_cycles: bool = False, max_internal_cycles: int = inf) list
Generate a random walk or random cycle starting and ending at the specified cloud node.
- Internal Cycle Handling:
If allow_internal_cycles is False, the walk will terminate upon revisiting any node. If allow_internal_cycles is True, the walk can revisit nodes, but the number of internal cycles is limited by max_internal_cycles.
- Parameters:
startNode (str) – The starting node from which the random cycle is generated. Default is self.cloud_name.
is_cycle (bool) – technique to generate whether random walk or random cycle. Default is True (i.e. random cycle)
allow_internal_cycles (bool) – Whether to allow internal cycles (revisiting nodes) during the walk. Defaults to False.
max_internal_cycles (int) – The maximum number of internal cycles allowed. Defaults to infinity.
- Returns:
A list of nodes representing the random cycle.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> trajectory = ['a','b','c','d','e','a'] >>> n.assign(trajectory) >>> n.generate('b')
- static generate_combinations(elements: list) list
Generates all combinations of a given list of elements.
- Parameters:
elements (list) – The list of elements.
- Returns:
The list of combinations.
- Return type:
list of list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.generate_combinations(['a', 'b']) [['a'], ['a', 'b'], ['b']] >>> n.generate_combinations(['a', 'b', 'c']) [['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'c'], ['b'], ['b', 'c'], ['c']]
- static generate_random_terms(cycle_dict: dict, k: int, is_premier: bool = False) str
Generates a random cycle string with k terms selected from the given cycle dictionary. Optionally, assigns random coefficients to the terms.
- Parameters:
cycle_dict (dict) – A dictionary of cycle terms and their coefficients.
k (int) – The number of terms to generate.
is_premier (bool, optional) – If True, returns terms without random coefficients.
- Returns:
A new cycle string with k randomly selected terms.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> cycle_dict = {'a': 2, 'b': 1, 'c': 3} >>> n.generate_random_terms(cycle_dict, 2) '2a + 1b'
- get_data()
Property to return the internal data structure of adjacency list
Example: >>> import IdealFlow.Network as net >>> n = net.IFN() >>> adjList = {‘a’: {‘b’: 1, ‘c’: 3}, ‘b’: {‘c’:2}, ‘c’: {‘a’:5}} >>> n.set_data(adjList) >>> n.get_data() {‘a’: {‘b’: 1, ‘c’: 3}, ‘b’: {‘c’:2}, ‘c’: {‘a’:5}}
- get_link_flow(startNode: str, endNode: str) float
Returns the flow of a link between two nodes.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The ending node.
- Returns:
The flow of the link, or NaN if the link does not exist.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 2) >>> print(n.get_link_flow('a', 'b')) 2.0
- property get_links: list
Returns the list of links in the network.
- Returns:
A list of links, where each link is represented as [startNode, endNode].
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> print(n.get_links) [['a', 'b']]
- get_matrix() tuple
Return the adjacency matrix of the network and the list of nodes.
- Returns:
A tuple containing the adjacency matrix and list of nodes.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> adj_matrix, nodes = n.get_matrix()
- get_path(startNode: str, endNode: str) list
return a path from the startNode to the endNode if exists.
- get_path_entropy(trajectory: list, isUpdateFirst: bool = False) float
Calculate the entropy of a given trajectory (path).
If the network probability was not computed, it will update the probabilities before calculation. The link probability must be greater than zero to be included in entropy computation.
- Parameters:
trajectory (list) – A sequence of nodes forming a path.
isUpdateFirst (bool) – Whether to update the network probability before calculation. Defaults to False.
- Returns:
The entropy of the path.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.get_path_entropy(['a', 'b', 'c']) 0.9182958340544896
- get_path_probability(trajectory: list, isUpdateFirst: bool = False) tuple
Compute the average probability of traversing the given trajectory (path) and the number of links.
The traverse will end when it reaches the first zero flow link. If trajectory has no path, avg prob = 0. If the network probability was not computed, it will update the probabilities before calculation.
- Parameters:
trajectory (list) – A sequence of nodes forming a path.
isUpdateFirst (bool) – Whether to update the network probability before calculation. Defaults to False.
- Returns:
- A tuple containing:
avg_prob (float): The average probability of traversing the path.
num_links (int): The number of links traversed in the path.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.get_path_probability(['a', 'b', 'c']) (0.5, 2)
- static global_scaling(F: ndarray, scaling_type: str = 'min', val: float = 1) float
Compute a global scaling factor for a flow matrix. Return scaling factor to ideal flow matrix to get equivalent IFN
- Parameters:
F (np.ndarray) – The ideal flow matrix.
scaling_type (str) – The type of scaling (‘min’, ‘max’, ‘sum’, ‘int’, ‘avg’, ‘std’, ‘cov’). ‘int’ means basis IFN (minimum integer)
val (float) – The value for scaling. Default is 1.
- Returns:
The scaling factor.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = np.array([[0.2, 0.3], [0.4, 0.1]]) >>> scaling = n.global_scaling(F, 'min') >>> print(scaling) 5.0
- static hadamard_division(a: ndarray, b: ndarray) ndarray
Perform elementwise division of two matrices, ignoring division by zero.
- Parameters:
a (np.ndarray) – The numerator matrix.
b (np.ndarray) – The denominator matrix.
- Returns:
The result of the elementwise division. Zero is returned for divisions by zero.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> A = np.array([[1, 2], [3, 0]]) >>> B = np.array([[2, 2], [0, 2]]) >>> result = n.hadamard_division(A, B) >>> print(result) [[0.5 1. ] [0. 0. ]]
- static has_pivot(cycle1: str, cycle2: str) bool
Check if two cycles have a pivot (shared node or link, or path).
- Parameters:
cycle1 (str) – The first cycle.
cycle2 (str) – The second cycle.
- Returns:
True if there is a pivot, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> cycle1 = "abc" >>> cycle2 = "bcd" >>> result = n.has_pivot(cycle1, cycle2) >>> print(result) # Output: True
- static ideal_flow(S: ndarray, pi: ndarray) ndarray
Compute the ideal flow matrix from a stochastic matrix and Perron vector.
- Parameters:
S (np.ndarray) – The stochastic matrix.
pi (np.ndarray) – The Perron vector.
- Returns:
The ideal flow matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> S = np.array([[0.5, 0.5], [0.5, 0.5]]) >>> pi = np.array([[0.5], [0.5]]) >>> F = n.ideal_flow(S, pi) >>> print(F) [[0.25 0.25] [0.25 0.25]]
- static ideal_flow_to_stochastic(F: ndarray) ndarray
Convert an ideal flow matrix into a Markov stochastic matrix.
- Parameters:
F (np.ndarray) – The ideal flow matrix.
- Returns:
The stochastic matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = np.array([[0.2, 0.3], [0.4, 0.1]]) >>> S = n.ideal_flow_to_stochastic(F) >>> print(S) [[0.4 0.6] [0.8 0.2]]
- static identify_unique_nodes(signature: str) list
Identifies unique nodes in a cycle string.
- Parameters:
signature (str) – The cycle string with node names.
- Returns:
A sorted list of unique node names.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.identify_unique_nodes('a + b + c + a') ['a', 'b', 'c']
- property in_degree: tuple
Return the in-degree (number of incoming edges) for each node and a list of all nodes.
- Returns:
- A tuple containing two lists:
List of in-degrees for each node.
List of nodes corresponding to the in-degrees.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('a', 'c', 2) >>> n.in_degree ([0, 1, 1], ['a', 'b', 'c'])
- in_neighbors(toNode: str) dict
Return the incoming neighbors and their weights for the given node (predecessors).
- Parameters:
toNode (str) – The node for which incoming neighbors are required.
- Returns:
A dictionary where keys are incoming nodes and values are edge weights.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('c', 'b', 2) >>> n.in_neighbors('b') {'a': 3, 'c': 2}
- property in_weight: tuple
Return the total incoming weight of each node and a list of all nodes.
- Returns:
- A tuple containing two lists:
List of total incoming weights for each node.
List of nodes corresponding to the weights.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('c', 'b', 2) >>> n.in_weight ([0, 5, 0], ['a', 'b', 'c'])
- static intersect(net1: IFN, net2: IFN) IFN
Return the intersection of two networks.
- Parameters:
- Returns:
A new network representing the intersection of net1 and net2.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> net1, net2 = net.IFN(), net.IFN() >>> intersect_net = n.intersect(net1, net2)
- static inverse_dict(dic: dict) dict
Create an inverse dictionary where values become keys and keys become values.
- Parameters:
dic (dict) – The original dictionary.
- Returns:
Inverse dictionary with values as keys and lists of original keys as values.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> dic = {'a': 1, 'b': 2, 'c': 2} >>> n.inverse_dict(dic) {1: ['a'], 2: ['b', 'c']}
>>> dic = {'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2} >>> n.inverse_dict(dic) {1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}
- property is_acyclic: bool
Check if the internal network contains no cycle.
- Returns:
True if the network is acyclic, False if a cycle is present.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_acyclic True
- property is_bipartite: bool
Check if the internal network is bipartite.
- Returns:
True if the network is bipartite, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_bipartite True
- property is_connected: bool
Check if the internal network is connected.
- Returns:
True if the network is connected, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_connected True
- property is_contain_cycle: bool
Check if the internal IFN contains a cycle using in-degree tracking.
- Returns:
True if a cycle is present, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_contain_cycle False
- static is_cycle_canonical(cycle: str) bool
Check if a cycle is canonical by comparing lexicographically sorted and rotated versions.
- Parameters:
cycle (str) – The cycle string.
- Returns:
True if the cycle is canonical, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> cycle = "abc" >>> n.is_cycle_canonical(cycle) True >>> cycle = "cab" >>> n.is_cycle_canonical(cycle) False >>> cycle = "bca" >>> n.is_cycle_canonical(cycle) False
- static is_cycle_has_coef_1(cycle_str: str) bool
Checks if each term in a cycle string has a coefficient of 1. It does not combine the term.
- Parameters:
cycle_str (str) – The cycle string, where terms are separated by ‘+’.
- Returns:
True if all terms have a coefficient of 1, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_cycle_has_coef_1('2a+b+c') False >>> n.is_cycle_has_coef_1('a+b+c') True >>> n.is_cycle_has_coef_1('a+b+c+a') # not combine the terms True
- static is_edge_in_cycle(i: int, j: int, cycle: str) bool
Check if an edge is in a cycle.
- Parameters:
i (int) – The row index.
j (int) – The column index.
cycle (str) – The cycle string.
- Returns:
True if the edge is in the cycle, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> cycle = 'abc' >>> result = n.is_edge_in_cycle(0, 1, cycle) >>> print(result) True
- static is_equal_network(net1: IFN, net2: IFN) bool
Check if two networks are equal by comparing their adjacency lists.
- Parameters:
- Returns:
True if both networks are equal, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> net1, net2 = n, n >>> n.is_equal_network(net1, net2) True
- static is_equal_signature(signature1: str, signature2: str) bool
Check if two signatures are equal by comparing their canonical cycle dictionaries.
- Parameters:
signature1 (str) – The first network signature.
signature2 (str) – The second network signature.
- Returns:
True if the signatures are equal, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> sig1 = "abc + bcd" >>> sig2 = "bcd + abc" >>> result = n.is_equal_signature(sig1, sig2) >>> print(result) # Output: True
- is_equivalent_ifn(ifn: IFN) bool
Check if the current IFN is equivalent to another IFN based on the coefficient of variation of flow.
- Parameters:
ifn (IFN) – The IFN to compare.
- Returns:
True if both IFNs are equivalent, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n1 = net.IFN() >>> n2 = net.IFN() >>> n1.is_equivalent_ifn(n2) False
- property is_eulerian_cycle: bool
Check if the internal network contains an Eulerian cycle.
- Returns:
True if the network contains an Eulerian cycle, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_eulerian_cycle False
- property is_ideal_flow: bool
Check if the network is an ideal flow network (premagic and strongly connected).
- Returns:
True if the network is an ideal flow, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_ideal_flow True
- static is_ideal_flow_matrix(mA: ndarray) bool
Check if a matrix is an ideal flow matrix.
- Parameters:
mA (np.ndarray) – The input matrix.
- Returns:
True if the matrix is an ideal flow matrix, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> M = np.array([[0.5, 0.5], [0.5, 0.5]]) >>> result = n.is_ideal_flow_matrix(M) >>> print(result) True
- static is_irreducible_matrix(M: ndarray) bool
Check if a matrix is irreducible. This method is slow for large matrix.
- Parameters:
M (np.ndarray) – The input matrix.
- Returns:
True if the matrix is irreducible, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> M = np.array([[0, 1], [1, 0]]) >>> result = n.is_irreducible_matrix(M) >>> print(result) True
- static is_irreducible_signature(cycle_signature: str) bool
Check if a cycle signature is irreducible.
- Parameters:
cycle_signature (str) – The cycle signature.
- Returns:
True if the signature is irreducible, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_irreducible_signature("abc + abd") False
- static is_non_empty_adj_list(adjL: dict) bool
Check if the adjacency list is non-empty.
- Parameters:
adjL (dict) – The adjacency list.
- Returns:
True if the adjacency list contains at least one link, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> adjL = {'a': {'b': 1}, 'b': {}} >>> n.is_non_empty_adj_list(adjL) True
- static is_non_negative_matrix(M: ndarray) bool
Check if all elements in a matrix are non-negative.
- Parameters:
M (np.ndarray) – The input matrix.
- Returns:
True if all elements are non-negative, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> M = np.array([[0, 1], [2, 3]]) >>> result = n.is_non_negative_matrix(M) >>> print(result) True
- is_path(trajectory: list) bool
Check if the given trajectory is a valid path.
- Parameters:
trajectory (list) – A sequence of nodes.
- Returns:
True if the sequence forms a valid path, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.is_path(['a', 'b', 'c']) True
- static is_positive_matrix(M: ndarray) bool
Check if all elements in a matrix are positive.
- Parameters:
M (np.ndarray) – The input matrix.
- Returns:
True if all elements are positive, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> M = np.array([[1, 2], [3, 4]]) >>> result = n.is_positive_matrix(M) >>> print(result) True
- property is_premagic: bool
Check if the in-weight and out-weight of all nodes are approximately equal.
- Returns:
True if the in-weight is approximately equal to out-weight for all nodes, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_premagic True
- static is_premagic_matrix(M: ndarray) bool
Check if a matrix is premagic (row sums equal column sums).
- Parameters:
M (np.ndarray) – The input matrix.
- Returns:
True if the matrix is premagic, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> M = np.array([[1, 2], [2, 1]]) >>> result = n.is_premagic_matrix(M) >>> print(result) True
- static is_premier_matrix(F: list) bool
Check if an ideal flow matrix is premier.
- Parameters:
F (list) – The ideal flow matrix.
- Returns:
True if the matrix is premier, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> F = [[1, 1], [1, 1]] >>> n = net.IFN() >>> result = n.is_premier_matrix(F) >>> print(result)
- static is_premier_signature(net_signature: str) bool
Check if a network signature is premier (has all cycle and coefficients equal to 1).
- Parameters:
net_signature (str) – The network signature.
- Returns:
True if the signature is premier, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "abc + def" >>> n.is_premier_signature(signature) True >>> n.is_premier_signature("abc + 2ab") False >>> n.is_premier_signature("abc + bca + def") False
- is_reachable(startNode: str, endNode: str) bool
Check if a node is reachable from another node using BFS.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The node to check reachability for.
- Returns:
True if the endNode is reachable from startNode, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_reachable('A', 'B') True
- static is_row_stochastic_matrix(mA: ndarray) bool
Check if a matrix is row-stochastic (rows sum to 1).
- Parameters:
mA (np.ndarray) – The input matrix.
- Returns:
True if the matrix is row-stochastic, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> mA = np.array([[0.5, 0.5], [0.3, 0.7]]) >>> n.is_row_stochastic_matrix(mA) True
- static is_square_matrix(M: ndarray) bool
Check if a matrix is square.
- Parameters:
M (np.ndarray) – The input matrix.
- Returns:
True if the matrix is square, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> M = np.array([[1, 2], [3, 4]]) >>> result = n.is_square_matrix(M) >>> print(result) True
- property is_strongly_connected: bool
Check if the internal network is strongly connected.
- Returns:
True if the network is strongly connected, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_strongly_connected False
- is_trajectory_cycle(path: list) bool
Check if the given path forms a cycle (i.e., start and end nodes are the same).
- Parameters:
path (list) – A sequence of nodes.
- Returns:
True if the path forms a cycle, False otherwise.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.is_trajectory_cycle(['a', 'b', 'a']) False >>> n.add_link('b', 'a', 1) >>> n.is_trajectory_cycle(['a', 'b', 'a']) True
- static is_valid_signature(signature: str) bool
Check if a network signature is valid by ensuring that all cycles are canonical.
- Parameters:
signature (str) – The network signature.
- Returns:
True if the signature is valid, otherwise False.
- Return type:
bool
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.is_valid_signature("abc + bcd") True >>> n.is_valid_signature("5abc+2bcd") True >>> n.is_valid_signature("bac + dcb") False >>> n.is_valid_signature("cbcd") False
- static kappa(F: list) float
Compute the kappa value of a flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The kappa value.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[1, 2], [3, 4]] >>> n = net.IFN() >>> kappa_value = n.kappa(F) >>> print(kappa_value)
- static link_combination(trajectory: list) list
Given a list of nodes, generate all one-way link combinations. Note: the trajectory is not necessarily a path in the network
- Parameters:
trajectory (list) – A list of nodes.
- Returns:
A list of one-way link combinations.
- Return type:
list
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> n.link_combination(['a', 'b', 'c']) [['a', 'b'], ['a', 'c'], ['b', 'c']] >>> n.link_combination(['a','b','c','d']) [['a','b'],['a','c'],['a','d'],['b','c'],['b','d'],['c','d']]
- static link_cycle_matrix(F: list) dict
Generate the link-cycle matrix from a flow matrix.
- Parameters:
F (list of list of int/float) – The flow matrix.
- Returns:
A dictionary containing the link-cycle matrix, cycles, and links.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = [[3, 1], [1, 0]] >>> result = n.link_cycle_matrix(F) >>> print(result)
- static link_permutation(trajectory: list) list
Given a list of nodes, generate all two-way link permutations. Note: the trajectory is not necessarily a path in the network
- Parameters:
trajectory (list) – A list of nodes.
- Returns:
A list of two-way link permutations.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.link_permutation(['a', 'b', 'c']) [['a', 'b'], ['a', 'c'], ['b', 'a'], ['b', 'c'], ['c', 'a'], ['c', 'b']] >>> n.link_permutation(['a','b','c','d']) [['a','b'],['a','c'],['a','d'],['b','c'],['b','d'],['c','d'], ['b','a'],['c','a'],['d','a'],['c','b'],['d','b'],['d','c']]
- load(fileName: str) None
Load the adjacency list from a JSON file.
- Parameters:
fileName (str) – The name of the file to load the data from.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.load('network.json')
- static load_adj_list(filename: str) dict
Load an adjacency list from a JSON file.
- Parameters:
filename (str) – The name of the file to load from.
- Returns:
The loaded adjacency list.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> adjL = n.load_adj_list('adj_list.json') >>> print(adjL) {'a': {'b': 1}, 'b': {}}
- static markov(S: ndarray, kappa: float = 1) ndarray
Compute the steady-state Markov vector from a stochastic matrix. Exact computation approach.
- Parameters:
S (np.ndarray) – The stochastic matrix.
kappa (float) – Total of the Markov vector. Default is 1.
- Returns:
The Markov chain.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> S = np.array([[0.5, 0.5], [0.5, 0.5]]) >>> pi = n.markov(S) >>> print(pi) [[0.5] [0.5]]
Previous version: steadyStateMC()
- match(trajectory: list, dicIFNs: dict) tuple
Return the IFN from the dictionary with the maximum trajectory entropy and percentage of max entropy/sum of entropy.
- Parameters:
trajectory (list) – A list of nodes representing the trajectory.
dicIFNs (dict) – A dictionary where the keys are IFN names and values are IFN objects.
- Returns:
The name of the IFN with the maximum entropy and the percentage (float).
- Return type:
tuple
Example
>>> n1, n2 = IFN(), IFN() >>> n.match(['a', 'b'], {'IFN1': n1, 'IFN2': n2})
- static matrix_apply_cycle(flow_matrix: list, cycle: str, flow: float = 1) list
Return the updated flow matrix after applying flow unit along the given cycle.
- Parameters:
flow_matrix (list) – The flow matrix.
cycle (str) – The cycle string.
flow (float) – The flow to apply. Default is 1.
- Returns:
The updated flow matrix.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> flow_matrix = [[0, 2], [3, 0]] >>> cycle = 'ab' >>> n = net.IFN() >>> updated_matrix = n.matrix_apply_cycle(flow_matrix, cycle, flow=2) >>> print(updated_matrix) [[0, 4], [5, 0]]
- static matrix_replace_value(matrix: list, old_value: float, new_value: float) list
Replace all occurrences of old_value with new_value in a matrix.
- Parameters:
matrix (list) – The matrix to modify.
old_value (float) – The value to replace.
new_value (float) – The value to use as a replacement.
- Returns:
The modified matrix.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> matrix = [[1, 2], [2, 3]] >>> n.matrix_replace_value(matrix, 2, 0) [[1, 0], [0, 3]]
- static matrix_to_adj_list(matrix: ndarray) dict
Convert a weighted square matrix to an adjacency list.
- Parameters:
matrix (np.ndarray) – The weighted square matrix.
- Returns:
The adjacency list.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> matrix = np.array([[0, 1, 2], [0, 0, 3], [0, 0, 0]]) >>> adjL = n.matrix_to_adj_list(matrix) >>> print(adjL) {'0': {'1': 1, '2': 2}, '1': {'2': 3}, '2': {}}
- property max_flow: float
Find the internal maximum flow value in the network.
- Returns:
The maximum flow in the network.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> C = [[1, 2], [3, 4]] >>> n = net.IFN() >>> n.set_matrix(C,['a','b']) >>> print(n.max_flow)
- static max_flow_matrix(F: list) float
Compute the maximum flow value of a flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The maximum flow value.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[1, 2], [3, 4]] >>> n = net.IFN() >>> max_flow_value = n.max_flow_matrix(F) >>> print(max_flow_value)
- max_flow_path(startNode, endNode)
Find the path from startNode to endNode with the maximum total flow (sum of link weights).
- Parameters:
startNode (str) – The starting node.
endNode (str) – The ending node.
- Returns:
A tuple containing the maximum flow and the path as a list of nodes.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> adjList = { 'a': {'c': 1, 'd': 2}, 'b': {'c': 1, 'e': 3}, 'c': {'e': 5}, 'd': {'c': 5}, 'e': {'a': 3}, '#Z#': {'a': 0, 'b': 0} # Cloud node connections } >>> n.set_data(adjList) >>> max_flow, max_path = network.max_flow_path('a', 'e') >>> print(f"Maximum flow from 'a' to 'e': {max_flow}, Path: {max_path}")
- static max_network_entropy(P: list) tuple
Compute maximum network entropy for a given probability matrix.
- Parameters:
P (list) – The probability matrix.
- Returns:
The entropy, entropy ratio, and maximum entropy.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> P = [[0.25, 0.75], [0.6, 0.4]] >>> n = net.IFN() >>> max_entropy = n.max_network_entropy(P) >>> print(max_entropy)
- static merge_adjacency_list(adj_list1: dict, adj_list2: dict) dict
Merge two adjacency lists by combining their weights.
- Parameters:
adj_list1 (dict) – The first adjacency list.
adj_list2 (dict) – The second adjacency list.
- Returns:
The merged adjacency list.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> adj_list1 = {'a': {'b': 1}} >>> adj_list2 = {'b': {'c': 2}} >>> n.merge_adjacency_list(adj_list1, adj_list2) {'a': {'b': 1}, 'b': {'c': 2}}
- static merge_signatures(sig1: str, sig2: str) str
Merge two network signatures into one.
- Parameters:
sig1 (str) – The first network signature.
sig2 (str) – The second network signature.
- Returns:
The merged network signature.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.merge_signatures('abc', 'def') 'abc + def'
- property min_flow: float
Return the internal min flow in the network
Example
>>> import IdealFlow.Network as net >>> C = [[1, 2], [3, 4]] >>> n = net.IFN() >>> n.set_matrix(C,['a','b']) >>> print(n.min_flow)
- static min_flow_matrix(F: list) float
Compute the minimum flow value of a flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The minimum flow value.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[1, 2], [3, 0]] >>> n = net.IFN() >>> min_flow_value = n.min_flow_matrix(F) >>> print(min_flow_value)
- min_flow_path(startNode, endNode)
Find the path from startNode to endNode with the minimum total flow (sum of link weights).
- Parameters:
startNode (str) – The starting node.
endNode (str) – The ending node.
- Returns:
A tuple containing the minimum flow and the path as a list of nodes.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> adjList = { 'a': {'c': 1, 'd': 2}, 'b': {'c': 1, 'e': 3}, 'c': {'e': 5}, 'd': {'c': 5}, 'e': {'a': 3}, '#Z#': {'a': 0, 'b': 0} # Cloud node connections } >>> n.set_data(adjList) >>> min_flow, min_path = n.min_flow_path('a', 'e') >>> print(f"Minimum flow from 'a' to 'e': {min_flow}, Path: {min_path}")
- static min_irreducible(k: int) ndarray
Generate the minimum irreducible matrix of size k.
- Parameters:
k (int) – The size of the matrix.
- Returns:
The minimum irreducible matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> A = n.min_irreducible(3) >>> print(A) [[0 1 0] [0 0 1] [1 0 0]]
- network_delete_cloud() IFN
Return a duplicate of the current network, with the cloud node removed.
- Returns:
A new network without the cloud node.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> clean_net = n.network_delete_cloud()
- property network_entropy: float
Calculate the network entropy based on the stochastic flow matrix.
- Returns:
The network entropy.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[0, 2], [2, 1]] >>> n = net.IFN() >>> n.set_matrix(F,['a','b']) >>> n.network_entropy
- static network_entropy_matrix(F: list) float
Compute network entropy for a given flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The network entropy.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[2, 3], [1, 4]] >>> n = net.IFN() >>> entropy = n.network_entropy_matrix(F) >>> print(entropy)
- property network_entropy_ratio: float
Return the internal network entropy ratio of flows in the network
Example
>>> import IdealFlow.Network as net >>> C = [[1, 2], [3, 4]] >>> n = net.IFN() >>> n.set_matrix(C,['a','b']) >>> print(n.network_entropy_ratio)
- static network_entropy_ratio_matrix(F: list) float
Compute network entropy ratio for a given flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The network entropy ratio.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[2, 3], [1, 4]] >>> n = net.IFN() >>> ratio = n.network_entropy_ratio_matrix(F) >>> print(ratio)
- property network_probability: dict
Return the adjacency list with link probabilities calculated from the total flow (kappa).
- Returns:
The adjacency list with link probabilities.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('a', 'c', 2) >>> n.network_probability {'a': {'b': 0.6, 'c': 0.4}, 'b': {}, 'c': {}}
- static node_index(name: str) int
Convert a name to a unique index. - Single lowercase letter: returns an index between 0-25. - Single uppercase letter: returns an index between 26-51. - Single digit or Base62 character: returns its corresponding index starting from 52. - Multi-character name: returns a Base62-encoded index after 62.
- Parameters:
name (str) – The name to convert to an index.
- Returns:
The corresponding node index.
- Return type:
int
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.node_index('a') 0 >>> n.node_index('A') 26 >>> n.node_index('0') 52 >>> n.node_index('aa') 682
- static node_name(index: int) str
Convert an index back into a node name based on the original node_index logic. Generate a node name based on an index, using letters and base62 encoding.
- Parameters:
index (int) – The index to convert to a node name.
- Returns:
The node name.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.node_name(0) 'a' >>> n.node_name(26) 'A' >>> n.node_name(52) '0' # Example base62 string for index 52 >>> n.node_name(682) 'aa'
- property nodes
Property to returns a list of all nodes in the network.
- Returns:
A list of nodes in the network.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a','b') >>> print(n.nodes)
- property nodes_flow
Property to returns the flow associated with each node in the network.
- Returns:
A dictionary where keys are node identifiers and values are their respective flows.
Example: >>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link(‘a’,’b’,5) >>> print(n.nodes_flow)
- Return type:
dict
This property is useful for node flow analysis because node flow of an IFN must be the same as pi from markov.
- static num_to_excel_col(num: int) str
Convert a number to an Excel-style column label. such as a, b, …, z, aa, ab, …, az, ba, … Use it to rename the variable.
- Parameters:
num (int) – The number to convert.
- Returns:
The Excel column label.
- Return type:
str
- Raises:
ValueError – If the number is less than 1.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.num_to_excel_col(1) 'a' >>> n.num_to_excel_col(27) 'aa'
- static num_to_str_fraction(num: float) str
Converts a number to a string fraction representation.
- Parameters:
num (float) – The number to convert.
- Returns:
The string representation of the fraction.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> import numpy as np >>> n = net.IFN() >>> n.num_to_str_fraction(0.75) '3/4' >>> n.num_to_str_fraction(0.111111) '1/9' >>> n.num_to_str_fraction(np.pi) '355/113'
- order_markov_higher(trajectory: list, order: int) list
Convert a first-order Markov trajectory into a higher-order Markov trajectory.
- Agreement:
separator between node in supernode is ‘|’ cloud node is ‘#z#’ and always first order
- Parameters:
trajectory (list) – A list of nodes representing the first-order Markov trajectory in hash code.
order (int) – The desired (higher) Markov order.
- Returns:
A list of supernodes of K order representing the higher-order Markov trajectory.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.order_markov_higher(['a', 'b', 'c'], 2)
- order_markov_lower(trajSuper: list) list
Convert a high-order Markov trajectory into a first-order Markov trajectory.
Agreement: Separator between nodes in a supernode is ‘|’. Cloud node is ‘#z#’ and always first-order.
- Parameters:
trajSuper (list) – A list of supernodes of K order representing the trajectory.
- Returns:
A list representing the first-order Markov trajectory in hash code.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.order_markov_lower(['a|b', 'b|c', '#z#'])
- property out_degree: tuple
Return the out-degree (number of outgoing edges) for each node and a list of all nodes.
- Returns:
- A tuple containing two lists:
List of out-degrees for each node.
List of nodes corresponding to the out-degrees.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('a', 'c', 2) >>> n.out_degree ([2, 0, 0], ['a', 'b', 'c'])
- out_neighbors(startNode: str) dict
Return the outgoing neighbors and their weights from the given start node. (Successor)
- Parameters:
startNode (str) – The node for which outgoing neighbors are required.
- Returns:
- A dictionary where keys are neighboring nodes and values are edge weights.
Returns an empty dict if the node has no neighbors.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('a', 'c', 5) >>> n.out_neighbors('a') {'b': 3, 'c': 5}
- property out_weight: tuple
Return the total outgoing weight of each node and a list of all nodes.
- Returns:
- A tuple containing two lists:
List of total outgoing weights for each node.
List of nodes corresponding to the weights.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('a', 'c', 5) >>> n.out_weight ([8, 0, 0], ['a', 'b', 'c'])
- static overlay(net1: IFN, net2: IFN) IFN
Overlay net1 into net2, updating weights in net2 based on net1.
- Parameters:
- Returns:
The updated network with the overlay of net1.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> base_net, overlay_net = net.IFN(), net.IFN() >>> result_net = n.overlay(base_net, overlay_net)
- static parse_cycle(cycle: str) list
Parses a cycle string into a list of node indices.
- Parameters:
cycle (str) – The cycle string.
- Returns:
A list of node indices representing the cycle.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.parse_cycle('abc') [0, 1, 2]
- static parse_terms_to_dict(signature: str) dict
Parses a signature into a dictionary with terms as keys and their coefficients as values.
- Parameters:
signature (str) – The cycle string where each term is a variable or has a coefficient.
- Returns:
A dictionary where keys are terms (variables) and values are their coefficients.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.parse_terms_to_dict('2a + b + 3c') {'a': 2, 'b': 1, 'c': 3} >>> n.parse_terms_to_dict("abc + 2bca + 5def") {'abc': 1, 'bca': 2, 'def': 5}
- path_distance(startNode: str, endNode: str) float
Calculate the total weight of the shortest path between startNode and endNode.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The target node.
- Returns:
The sum of weights along the shortest path.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('b', 'c', 7) >>> n.path_distance('a', 'c') 10 >>> n.path_distance('c', 'a') 0
- path_length(startNode: str, endNode: str) int
Return the number of edges in the path if it forms a valid path, otherwise return 0.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The target node.
- Returns:
The number of edges in the shortest path, or 0 if not a path.
- Return type:
int
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('b', 'c', 7) >>> n.path_length('a', 'c') 2 >>> n.path_length('c', 'a') 0
- path_sum_weight(path: list) float
Return the sum of weights along the given path.
- Parameters:
path (list) – A sequence of nodes forming a path.
- Returns:
The sum of weights along the path.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 2) >>> n.path_sum_weight(['a', 'b', 'c']) 3
- static permutations(N: int) list
Generates all non-empty permutations of N letters.
- Parameters:
N (int) – The number of letters to permute.
- Returns:
The list of permutations.
- Return type:
list of str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.permutations(2) ['a', 'b', 'ab', 'ba'] >>> n.permutations(3) ['a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba']
- static premier_ifn(C: list) list
Return the minimum integer IFN regardless of stochastic matrix.
- Parameters:
C (list) – The capacity matrix.
- Returns:
The premier IFN.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> C = [[0, 2], [3, 0]] >>> n = net.IFN() >>> premier_flow = n.premier_ifn(C) >>> print(premier_flow) [[0, 1], [1, 0]]
- static premier_signature(C: list) str
Compute the premier signature for a given capacity matrix.
- Parameters:
C (list of list of int/float) – The capacity matrix.
- Returns:
The premier signature.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> C = [[3, 1], [1, 0]] >>> signature = n.premier_signature(C) >>> print(signature) ab + a
- query(sequence, method='min')
Find a cycle path from a cloud node to a cloud node that contains the node sequence.
- Parameters:
sequence (list or str) – The sequence of nodes to include in the path.
method (str) – ‘min’ for minimum flow paths, ‘max’ for maximum flow paths.
- Returns:
A tuple containing the path as a list of nodes and the probability.
- Return type:
tuple
Example
>>> path, probability = network.query('ace', method='min') >>> print(f"Query result: Probability: {probability}, Path: {path}")
- query_cycle_limit(sequence, method='min', max_internal_cycle=1)
Find a cycle path from the cloud node to the cloud node that contains the node sequence, limiting the number of internal cycles.
- Parameters:
sequence (list or str) – The sequence of nodes to include in the path.
method (str) – The method to use for pathfinding (‘min’, ‘max’, or ‘dfs’).
max_internal_cycle (int) – The maximum number of internal cycles allowed in the path.
- Returns:
A tuple containing the the path as a list of nodes and average probability
- Return type:
tuple
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> adjList = { 'a': {'c': 1, 'd': 2}, 'b': {'c': 1, 'e': 3, '#Z#': 10}, 'c': {'e': 5}, 'd': {'c': 5}, 'e': {'a': 3, 'b': 5}, '#Z#': {'a': 10, 'b': 10} # Cloud node connections } >>> n.set_data(adjList) >>> path, probability = n.query_cycle_limit('ace', method='min', max_internal_cycle=0) >>> print(f"Query result: Probability: {probability}, Path: {path}") >>> path, probability = nquery_cycle_limit('ace', method='max', max_internal_cycle=1) >>> print(f"Query result with max_internal_cycle=1: Probability: {probability}, Path: {path}")
- static rand_capacity(num_node=5, max_capacity=9)
Generate random capacity matrix for a given number of nodes.
- Parameters:
num_node (int) – Number of nodes.
max_capacity (int) – Maximum capacity value.
- Returns:
The random capacity matrix.
- Return type:
list of list of int
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.rand_capacity(5, 10) [[0, 7, 3, 0, 0], ...]
- rand_ifn_signature(numNodes=5, kappa=17)
Generate a random cycle signature for an Ideal Flow Network (IFN) that meets the specified number of nodes and total flow.
This method constructs a cycle signature by randomly generating cycles and assigning coefficients to them, ensuring that the total flow (sum of coefficients times cycle lengths) equals the specified kappa.
- Parameters:
numNodes (int, optional) – The number of nodes in the network. Default is 5.
kappa (int, optional) – The total flow in the network. Default is 100.
- Returns:
The cycle signature as a string.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = n.findIFNsignature(numNodes=5, kappa=50) >>> print(signature) abcde + 6abce + 4bcd + 2ade
The output is a cycle signature string where each term represents a cycle, and the coefficient indicates the number of times the cycle occurs in the network.
Notes
The method ensures that the total flow does not exceed the specified kappa.
It avoids adding self-loops (cycles of length 1) unless necessary.
- static rand_int(mR: int, mC: int, max_val: int = 10, prob: float = 0.8) ndarray
Generate a random integer matrix with biased zero entries.
- Parameters:
mR (int) – Number of rows.
mC (int) – Number of columns.
max_val (int) – Maximum value for non-zero entries. Defaults to 10.
prob (float) – Probability of zeros. Defaults to 0.8.
- Returns:
A random integer matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> m = n.rand_int(3, 3, max_val=5, prob=0.7) >>> print(m) [[0 3 0] [4 0 2] [0 0 5]]
- static rand_irreducible(num_nodes: int = 5, num_links: int = 8) ndarray
Generate a random irreducible matrix.
- Parameters:
num_nodes (int) – Number of nodes.
num_links (int) – Number of links.
- Returns:
The random irreducible matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> A = n.rand_irreducible(3, 4) >>> print(A) [[0 1 0] [1 0 1] [1 1 0]]
- static rand_permutation_eye(n: int = 5) ndarray
Generate a random permutation of the identity matrix.
- Parameters:
n (int) – The size of the matrix.
- Returns:
The permuted identity matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> permuted_eye = n.rand_permutation_eye(3) >>> print(permuted_eye) [[0. 1. 0.] [1. 0. 0.] [0. 0. 1.]]
- static rand_stochastic(n: int) ndarray
Generate a random row-stochastic matrix of size n.
- Parameters:
n (int) – Size of the square matrix.
- Returns:
The random row-stochastic matrix.
- Return type:
np.ndarray
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> S = n.rand_stochastic(3) >>> print(S) [[0.2 0.3 0.5] [0.4 0.2 0.4] [0.3 0.3 0.4]]
- random_cycle_from(startEndNode: str, allow_internal_cycles: bool = True, max_internal_cycles: int = inf) list
Perform a random walk that starts and ends at the specified startEndNode, forming a cycle.
- Parameters:
startEndNode (str) – The starting and ending node of the cycle.
allow_internal_cycles (bool, optional) – If True (default), the walk allows internal cycles (cycles from nodes other than startEndNode).
max_internal_cycles (int, optional) – Maximum number of allowed internal cycles. Defaults to infinity if not specified.
- Returns:
A list of nodes visited during the random walk that forms a cycle. If no cycle can be formed, it returns an empty list.
- Return type:
list
- Stochastic Behavior:
The next node in the walk is chosen probabilistically based on the weights of the outgoing edges. Nodes with higher edge weights have a greater chance of being chosen, making the walk biased toward those edges.
- Special Cases:
If the network contains no cycles, the method will return an empty list, as no cycle can be formed. If only one cycle exists in the network, the walk will discover that cycle. In strongly connected networks, the random walk is more likely to find cycles, as all nodes are reachable from any other node.
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 2) >>> n.add_link('b', 'd', 2) >>> n.add_link('d', 'a', 2) >>> n.add_link('d', 'c', 2) >>> print(n.random_cycle_from('a')) ['a', 'b', 'd', 'a'] [] >>> n.add_link('c', 'a', 2) >>> print(n.random_cycle_from('a', allow_internal_cycles=False)) # Disallowing Internal Cycles ['a', 'b', 'd', 'c', 'a'] >>> print(n.random_cycle_from('a', allow_internal_cycles=True, max_internal_cycles=2)) # Allowing Internal Cycles with a Limit ['a', 'b', 'c', 'a'] >>> print(n.random_cycle_from('a', allow_internal_cycles=True)) # Unrestricted Internal Cycles
- static random_ideal_flow_matrix(N: int, kappa: float = 1) array
Generate random irreducible ideal flow matrix.
- Parameters:
N (int) – Size of the matrix (number of nodes).
kappa (float) – Scaling factor for the ideal flow. Default is 1.
- Returns:
Random irreducible ideal flow matrix.
- Return type:
np.array
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> result = n.random_ideal_flow_matrix(3, kappa=27) >>> print(result) [[...], [...], [...]]
- static random_ifn(num_nodes: int = 5, total_flow: float = 1) list
Generate a random ideal flow matrix with a given number of nodes and total flow based on network signature.
- Parameters:
num_nodes (int) – Number of nodes. Default is 5.
total_flow (float) – Total flow. Default is 1.
- Returns:
The ideal flow network.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> random_network = n.random_ifn(3, 10) >>> print(random_network)
- static random_irreducible_stochastic(N)
Generate random irreducible stochastic matrix.
- Parameters:
N (int) – Size of the matrix.
- Returns:
The random stochastic matrix.
- Return type:
list of list of float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.random_irreducible_stochastic(3)
- random_walk_cycle(start_end_node: str) list
Perform a random walk through nodes in a cycle starting and ending at the same node.
- Parameters:
start_end_node (str) – The node from which the random cycle starts and ends.
- Returns:
List of nodes visited during the random walk cycle.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> result = n.random_walk_cycle('A') >>> print(result) ['A', 'B', 'C', 'A']
- random_walk_from(startNode: str, length: int = 1, allow_internal_cycles: bool = True, max_internal_cycles: int = inf) list
Perform a stochastic random walk from the given startNode, either until reaching a sink node (a node with no outgoing edges) or for a specified number of steps. The next node is chosen probabilistically based on the weights of the outgoing edges from the current node.
- Internal Cycle Handling:
If allow_internal_cycles is False, the walk will terminate upon revisiting any node. If allow_internal_cycles is True, the walk can revisit nodes, but the number of internal cycles is limited by max_internal_cycles.
- Parameters:
startNode (str) – The starting node.
length (int) – The maximum number of steps in the random walk.
allow_internal_cycles (bool) – Whether to allow internal cycles (revisiting nodes) during the walk. Defaults to True.
max_internal_cycles (int) – The maximum number of internal cycles allowed. Defaults to infinity.
- Returns:
A list of nodes visited during the random walk. The walk will stop if it reaches a sink node, if the specified length is reached, or if the number of allowed internal cycles is exceeded.
- Return type:
list
- Stochastic Behavior:
If the current node has multiple outgoing neighbors, the next node is chosen based on the probability distribution proportional to the weights of the edges. Nodes with higher edge weights are more likely to be chosen than those with lower weights.
Example
>>> import IdealFlow.Network as net # import package.module as alias >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 2) >>> n.add_link('b', 'd', 2) >>> n.add_link('d', 'a', 2) >>> n.add_link('d', 'c', 2) >>> print(n.random_walk_from('a', 7)) >>> # n.show() ['a', 'b', 'd', 'a', 'b', 'c'] >>> print(n.random_walk_from('a', 7)) ['a', 'b', 'd', 'a', 'b', 'd', 'a'] >>> print(n.random_walk_from('a', 7)) ['a', 'b', 'd', 'c'] >>> print(n.random_walk_from('a', 7, allow_internal_cycles=False)) ['a', 'b', 'c'] >>> print(n.random_walk_from('a', 7, max_internal_cycles=1)) ['a', 'b', 'd', 'a', 'b']
- static random_walk_matrix(m_capacity: array, arr_name: list, prev_index: int) tuple
Perform a random walk on a Markov transition matrix.
- Parameters:
m_capacity (np.array) – The Markov transition matrix.
arr_name (list of str) – List of node names corresponding to the rows/columns of the matrix.
prev_index (int) – The index of the previous node in the walk.
- Returns:
The next node name and its index.
- Return type:
tuple
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> markov_matrix = np.array([[0, 1], [1, 0]]) >>> arr_name = ['A', 'B'] >>> next_node, next_index = n.random_walk_matrix(markov_matrix, arr_name, 0) >>> print(next_node, next_index) B 1
- random_walk_nodes(start_node: str, length: int = 1) list
Perform a random walk through nodes starting from a specific node.
- Parameters:
start_node (str) – The starting node for the random walk.
length (int) – The number of steps to walk. Default is 1.
- Returns:
List of nodes visited during the random walk.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> result = n.random_walk_nodes('A', length=3) >>> print(result) ['A', 'B', 'C']
- static read_csv(fName: str) list
Read a CSV file and return a 2D array.
- Parameters:
fName (str) – The name of the CSV file to read.
- Returns:
A 2D array representing the content of the CSV file.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> data = n.read_csv('data.csv') >>> print(data) [['1', '2'], ['3', '4']]
- reduce_link_flow(startNode: str, endNode: str) None
Reduces the flow of a link by 1. If the flow reaches zero or below, the link is deleted.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The ending node.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.reduce_link_flow('a', 'b') >>> print(n.get_link_flow('a', 'b')) nan
- reindex() None
Sort the nodes and standardize the adjacency list.
This operation may take a long time for large datasets.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.reindex()
- static relabel_signature(net_signature: str, node_mapping: dict) str
Relabel a network signature using a node mapping.
- Parameters:
net_signature (str) – The network signature.
node_mapping (dict) – The node mapping.
- Returns:
The relabeled signature.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "abc + bcd" >>> node_mapping = {'a': 'x', 'b': 'y', 'c': 'z'} >>> relabeled = n.relabel_signature(signature, node_mapping) >>> print(relabeled) # Output: "xyz + yzd"
- reverse_network() IFN
Return a new network with the direction of all links reversed.
- Returns:
A new network with reversed links.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> reversed_net = n.reverse_network()
- static reverse_relabel_signature(relabeled_signature: str, node_mapping: dict) str
Reverse relabel a network signature using a node mapping.
- Parameters:
relabeled_signature (str) – The relabeled signature.
node_mapping (dict) – The node mapping.
- Returns:
The original signature.
- Return type:
str
See also
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> relabeled = "xyz + yzd" >>> node_mapping = {'x': 'a', 'y': 'b', 'z': 'c'} >>> original = n.reverse_relabel_signature(relabeled, node_mapping) >>> print(original) # Output: "abc + bcd"
- property row_stochastic: dict
Convert the adjacency list to a row-stochastic form, where values represent the link probability out of each node.
- Returns:
A row-stochastic adjacency list.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('a', 'c', 2) >>> n.row_stochastic {'a': {'b': 0.6, 'c': 0.4}, 'b': {}, 'c': {}}
- save(fileName: str) None
Save the adjacency list to a JSON file.
- Parameters:
fileName (str) – The name of the file to save the data.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.save('network.json')
- static save_adj_list(adjL: dict, filename: str) None
Save an adjacency list to a JSON file.
- Parameters:
adjL (dict) – The adjacency list.
filename (str) – The name of the file to save to.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> adjL = {'a': {'b': 1}, 'b': {}} >>> n.save_adj_list(adjL, 'adj_list.json')
- set_data(adjList)
Replaces the internal data structure of the network with the given adjacency list.
This method updates the internal adjacency list representation, the list of nodes, and the number of nodes in the network. The adjacency list represents the network structure where each key corresponds to a node, and the associated value is a list of nodes connected to that key node.
- Parameters:
adjList (dict) – A dictionary representing the adjacency list of the network, where keys are node identifiers and values are lists of neighboring nodes.
Example: >>> import IdealFlow.Network as net >>> n = net.IFN() >>> adjList = {‘a’: {‘b’: 1, ‘c’: 3}, ‘b’: {‘c’:2}, ‘c’: {‘a’:5}} >>> n.set_data(adjList) >>> print(n) {‘a’: {‘b’: 1, ‘c’: 3}, ‘b’: {‘c’: 2}, ‘c’: {‘a’: 5}}
- Side Effects:
- Updates the following internal attributes:
self.adjList: Stores the provided adjacency list.
self.listNodes: Stores the list of nodes derived from the adjacency list.
self.numNodes: Stores the number of nodes in the updated network.
- set_link_weight(startNode: str, endNode: str, weight: float) None
Sets the weight of a link directly. If the link does not exist, it is created.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The ending node.
weight (float) – The weight to set.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.set_link_weight('a', 'b', 3) >>> print(n.get_link_flow('a', 'b')) 3.0
- set_link_weight_plus_1(startNode: str, endNode: str) None
Increments the weight of a link by 1. If the link does not exist, it is created with weight 1.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The ending node.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.set_link_weight_plus_1('a', 'b') >>> print(n.get_link_flow('a', 'b')) 1.0
- set_matrix(M: list, listNode: list = []) None
Replace the adjacency list with the provided matrix. This is useful if we use matrices in computation and want to put the matrix into network
- Parameters:
M (list) – Adjacency matrix to set.
listNode (list) – List of node names. Defaults to generating Excel-like labels.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> matrix = [[0, 1], [1, 0]] >>> n.set_matrix(matrix)
- set_path(trajectory: list, delta_flow: float = 1) None
Set a path in the network, updating the link weight by flow if it exists or creating the link with weight = 1 if it does not exist.
- Parameters:
trajectory (list) – A sequence of nodes to set as a path.
delta_flow (float) – The additional weight of the links alongthe path. Defaults to 1.
- Returns:
None
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.set_path(['a', 'b', 'c'], 3) >>> n.adjList {'a': {'b': 4}, 'b': {'c': 3}, 'c': {}}
- shortest_path(startNode: str, endNode: str) list
Find the shortest path (minimum number of links) between startNode and endNode.
- Parameters:
startNode (str) – The starting node.
endNode (str) – The target node.
- Returns:
The shortest path from startNode to endNode.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.shortest_path('a', 'c') ['a', 'b', 'c']
- show(layout: str = 'Planar', mNode: list = None, arrThreshold: list = None, routes: list = None) DiGraph
Visualizes the network using matplotlib and NetworkX.
- Parameters:
layout (str, optional) – The layout of the graph visualization. Options include: ‘Bipartite’, ‘Circular’, ‘Fruchterman’, ‘Kawai’, ‘Planar’, ‘Random’, ‘Shell’, ‘Spectral’, ‘Spiral’, ‘Spring’. Defaults to ‘Planar’.
mNode (list, optional) – Custom positions for nodes, each row should be [node_id, x, y].
arrThreshold (list, optional) – Thresholds for edge weights to determine the edge color. Format: [low_threshold, high_threshold].
routes (list, optional) – A list of routes, where each route is a list of node IDs. Edges in these routes are highlighted in red.
- Returns:
The directed graph representing the IFN.
- Return type:
nx.DiGraph
Example
>>> import IdealFlow.Network as net >>> adjList = {'a': {'b': 1.5}, 'b': {'c': 0.7}, 'c': {}} >>> n = net.IFN(adjList) >>> n.show(layout='Planar')
- static signature_coef_to_1(net_signature: str) str
Convert all network signature coefficients to one. Internally, it also canonize the cycle terms.
- Parameters:
net_signature (str) – The network signature.
- Returns:
The converted signature with all coefficients set to one.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "2bca + 3fde" >>> result = n.signature_coef_to_1(signature) >>> print(result) # Output: "abc + def"
- static signature_to_adj_list(signature: str, is_cycle: bool = True) dict
Convert a network signature into an adjacency list.
- Parameters:
signature (str) – The network signature.
is_cycle (bool) – Whether the signature represents a cycle (default is True).
- Returns:
The adjacency list representation of the signature.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_adj_list("abc") {'a': {'b': 1.0}, 'b': {'c': 1.0}, 'c': {'a': 1.0}}
- static signature_to_coef_flow(cycle_signature: str) float
Compute the coefficient of flow of a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
- Returns:
The coefficient of flow.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_coef_flow("abc + def")
- static signature_to_column_stochastic(cycle_signature: str, is_cycle: bool = True) dict
Convert cycle signature to a column stochastic adjacency list.
- Parameters:
cycle_signature (str) – The cycle signature.
is_cycle (bool) – Whether the signature represents a cycle.
- Returns:
The column stochastic adjacency list.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_column_stochastic("abc") {'a': {'b': 1.0}, 'b': {'c': 1.0}, 'c': {'a': 1.0}}
- static signature_to_ideal_flow(cycle_signature: str, is_cycle: bool = True) dict
Convert cycle signature to an ideal flow adjacency list.
- Parameters:
cycle_signature (str) – The cycle signature.
is_cycle (bool) – Whether the signature represents a cycle.
- Returns:
The ideal flow adjacency list.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_ideal_flow("abc") {'a': {'b': 1.0}, 'b': {'c': 1.0}, 'c': {'a': 1.0}}
- static signature_to_kappa(cycle_signature: str) float
Compute the kappa value of a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
- Returns:
The kappa value.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_kappa("abc + def")
- static signature_to_link_flow(cycle_signature: str, is_cycle: bool = True) dict
Compute link flow values from a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
is_cycle (bool) – Whether the signature represents a cycle.
- Returns:
The link flow values.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "abc + def" >>> result = n.signature_to_link_flow(signature) >>> print(result) # Output: {'ab': 1, 'bc': 1, 'ca': 1, 'de': 1, 'ef': 1, 'fd': 1}
- static signature_to_links(cycle_signature: str, is_cycle: bool = True) set
Compute the links in a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
is_cycle (bool) – Whether the signature represents a cycle.
- Returns:
A set of links.
- Return type:
set
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "abc + def" >>> result = n.signature_to_links(signature) >>> print(result) # Output: {'ab', 'bc', 'ca', 'de', 'ef', 'fd'}
- static signature_to_max_flow(cycle_signature: str) float
Compute the maximum flow value in a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
- Returns:
The maximum flow value.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_max_flow("abc + def") 1.0
- static signature_to_min_flow(cycle_signature: str) float
Compute the minimum flow value in a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
- Returns:
The minimum flow value.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_min_flow("abc + def") 1.0
- static signature_to_num_links(cycle_signature: str, is_cycle: bool = True) int
Compute the number of links in a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
is_cycle (bool) – Whether the signature represents a cycle.
- Returns:
The number of links.
- Return type:
int
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_num_links("abc + def") 4
- static signature_to_num_nodes(cycle_signature: str) int
Compute the number of nodes in a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
- Returns:
The number of unique nodes.
- Return type:
int
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> signature = "abc + def" >>> result = n.signature_to_num_nodes(signature) >>> print(result) # Output: 6
- static signature_to_pivots(cycle_signature: str) dict
Find pivots in a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
- Returns:
A dictionary of pivots between cycles.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_pivots("abc + abd") {'abc-abd': ['a', 'b']}
- static signature_to_row_stochastic(cycle_signature: str, is_cycle: bool = True) dict
Convert cycle signature to a row stochastic adjacency list.
- Parameters:
cycle_signature (str) – The cycle signature.
is_cycle (bool) – Whether the signature represents a cycle.
- Returns:
The row stochastic adjacency list.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_row_stochastic("abc") {'a': {'b': 1.0}, 'b': {'c': 1.0}, 'c': {'a': 1.0}}
- static signature_to_sum_cols(cycle_signature: str) dict
Compute the sum of columns in a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
- Returns:
A dictionary of column sums.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_sum_cols("abc + def") {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1}
- static signature_to_sum_rows(cycle_signature: str) dict
Compute the sum of rows in a cycle signature.
- Parameters:
cycle_signature (str) – The cycle signature.
- Returns:
A dictionary of row sums.
- Return type:
dict
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.signature_to_sum_rows("abc + def") {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1}
- static solve_cycles(F: ndarray, method: str = 'lsq_linear') str
Solves the cycle decomposition for a given flow matrix using one of three methods: ‘pinv’, ‘lsq_linear’, or ‘nnls’.
- Parameters:
F (np.ndarray) – The flow matrix.
method (str, optional) – The method to solve the system. Options are: - ‘pinv’: Uses the generalized inverse solution (can produce negative results). - ‘lsq_linear’: Uses least-squares with non-negativity constraints (default). - ‘nnls’: Uses non-negative least squares.
- Returns:
A string representation of the decomposed cycles.
- Return type:
str
- Raises:
ValueError – If an unsupported method is provided.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = np.array([[0, 1], [1, 0]]) >>> n.solve_cycles(F, method='lsq_linear') 'ab + ba'
- static stationary_markov_chain(S: list) list
Compute the stationary distribution of a Markov chain.
- Parameters:
S (list) – The stochastic matrix.
- Returns:
The stationary distribution.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> S = [[0.5, 0.5], [0.5, 0.5]] >>> n = net.IFN() >>> stationary_dist = n.stationary_markov_chain(S) >>> print(stationary_dist)
- property stdev_flow: float
Calculate the internal standard deviation of the flow across all links in the network.
- Returns:
The standard deviation of flow.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> C = [[1, 2], [3, 4]] >>> n = net.IFN() >>> n.set_matrix(C,['a','b']) >>> print(n.stdev_flow)
- static stdev_flow_matrix(F: list) float
Compute the standard deviation of flow values in a flow matrix.
- Parameters:
F (list) – The flow matrix.
- Returns:
The standard deviation of flow values.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> F = [[1, 2], [3, 4]] >>> n = net.IFN() >>> std_flow_value = n.stdev_flow_matrix(F) >>> print(std_flow_value)
- static stochastic_to_entropy_ratio(S: list) float
Compute entropy ratio from stochastic matrix.
- Parameters:
S (list) – The stochastic matrix.
- Returns:
The entropy ratio.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> S = [[0.4, 0.6], [0.7, 0.3]] >>> n = net.IFN() >>> ratio = n.stochastic_to_entropy_ratio(S) >>> print(ratio)
- static stochastic_to_ideal_flow(S: list, kappa: float = 1) list
Convert stochastic matrix to ideal flow matrix. If matrix size is les than 25, use exact method else, use approximate method which is fast but inaccurate.
- Parameters:
S (list) – The stochastic matrix.
kappa (float) – The kappa parameter.
- Returns:
The ideal flow matrix.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> S = [[0.5, 0.5], [0.5, 0.5]] >>> n = net.IFN() >>> ideal_flow = n.stochastic_to_ideal_flow(S) >>> print(ideal_flow)
- static stochastic_to_network_entropy(S: list) float
Compute network entropy from stochastic matrix.
- Parameters:
S (list) – The stochastic matrix.
- Returns:
The network entropy.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> S = [[0.5, 0.5], [0.5, 0.5]] >>> n = net.IFN() >>> entropy = n.stochastic_to_network_entropy(S) >>> print(entropy)
- static stochastic_to_pi(S: list, kappa: float = 1) list
Compute Perron vector (phi) from stochastic matrix.
- Parameters:
S (list) – The stochastic matrix.
kappa (float) – The kappa parameter.
- Returns:
The Perron vector.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> S = [[0.5, 0.5], [0.5, 0.5]] >>> n = net.IFN() >>> pi = n.stochastic_to_pi(S) >>> print(pi)
- Alias:
See also
- static stochastic_to_probability(S: list) list
Compute probability matrix from stochastic matrix.
- Parameters:
S (list) – The stochastic matrix.
- Returns:
The probability matrix.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> S = [[0.3, 0.7], [0.6, 0.4]] >>> n = net.IFN() >>> prob_matrix = n.stochastic_to_probability(S) >>> print(prob_matrix)
- str_to_num()
- static string_to_matrix(signature: str) ndarray
Converts a cycle string into a flow matrix.
- Parameters:
signature (str) – The cycle string representation.
- Returns:
The flow matrix.
- Return type:
np.ndarray
See also
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> F = n.string_to_matrix('a+b+c') >>> F array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> F = n.string_to_matrix('ab+ba+cab') array([[0, 3, 0], [2, 0, 1], [1, 0, 0]])
- static sum_dict_values(dic: dict) float
Sum the values of a dictionary, treating None as zero.
- Parameters:
dic (dict) – The dictionary with values to sum.
- Returns:
The sum of the dictionary’s values.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> d = {'a': 1, 'b': None, 'c': 3} >>> n.sum_dict_values(d) 4.0
- static sum_of_col(M: list) list
Compute the sum of each column in a matrix.
- Parameters:
M (list) – The input matrix.
- Returns:
The column sums.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> M = [[1, 2], [3, 4]] >>> n = net.IFN() >>> col_sums = n.sum_of_col(M) >>> print(col_sums)
- static sum_of_row(M: list) list
Compute the sum of each row in a matrix.
- Parameters:
M (list) – The input matrix.
- Returns:
The row sums.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> M = [[1, 2], [3, 4]] >>> n = net.IFN() >>> row_sums = n.sum_of_row(M) >>> print(row_sums)
- static to_adjacency_matrix(matrix)
Convert a non-negative matrix to a binary (0, 1) adjacency matrix.
- Parameters:
matrix (list of list of int/float) – The input matrix.
- Returns:
The adjacency matrix.
- Return type:
np.array
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> matrix = [[0, 1], [1, 0]] >>> n.to_adjacency_matrix(matrix) array([[0, 1], [1, 0]])
- static to_base62(num: int) str
Convert a integer number to a base62 string.
- Parameters:
num (int) – The number to convert.
- Returns:
The base62 string.
- Return type:
str
- Raises:
ValueError – If the number is negative.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.to_base62(0) '0' >>> n.to_base62(36) 'A' >>> n.to_base62(123) '1Z'
- static to_equal_inflow(C)
Return ideal flow matrix with equal inflow from capacity matrix.
- Parameters:
C (list of list of int/float) – The capacity matrix.
- Returns:
The ideal flow matrix.
- Return type:
list of list of int/float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> C = [[1, 2], [0, 1]] >>> n.to_equal_inflow(C)
- static to_equal_outflow(C)
Return ideal flow matrix with equal outflow from capacity matrix.
- Parameters:
C (list of list of int/float) – The capacity matrix.
- Returns:
The ideal flow matrix.
- Return type:
list of list of int/float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> C = [[1, 2], [0, 1]] >>> n.to_equal_outflow(C)
- to_graph() IFN
Convert the digraph to a graph, making the adjacency matrix symmetric. The link weights are adjusted to all 1.
- Returns:
A new network representing the graph counterpart of the digraph.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> graph_net = n.to_graph()
- to_markov_order(trajectory: list, toOrder: int) list
Convert a trajectory from any Markov order to a specified Markov order.
- Parameters:
trajectory (list) – A list of nodes representing the trajectory.
toOrder (int) – The desired Markov order.
- Returns:
A list representing the trajectory in the specified Markov order.
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.to_markov_order(['a', 'b', 'c'], 2)
- property total_flow: float
Calculate the total flow in the network, which is the sum of all edge weights.
- Returns:
The total flow in the network.
- Return type:
float
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 3) >>> n.add_link('a', 'c', 2) >>> n.total_flow 5
- property total_links: int
Returns the total number of links in the network.
- Returns:
The total number of links.
- Return type:
int
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 2) >>> print(n.total_links) 2
- property total_nodes
roperty to returns the total number of nodes in the network.
- Returns:
The total number of nodes.
- Return type:
int
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a','b') >>> print(n.total_nodes)
- static trajectory_to_links(trajectory: list) list
Given a list of nodes, generate a list of links (node pairs). Note: The trajectory is not necessarily a path in the network.
- Parameters:
trajectory (list) – A list of nodes.
- Returns:
A list of links (node pairs).
- Return type:
list
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.trajectory_to_links(['a', 'b', 'c']) [['a', 'b'], ['b', 'c']] >>> n.trajectory_to_links(['a','b','c','d']) [['a','b'],['b','c'],['c','d']]
- static union(net1: IFN, net2: IFN) IFN
Return the union of two networks, combining links and nodes from both.
- Parameters:
- Returns:
A new network containing the union of net1 and net2.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> net1, net2 = net.IFN(), net.IFN() >>> union_net = n.union(net1, net2)
- static universe(net: IFN) IFN
Return the universe (complete digraph) of the given network.
- Parameters:
net (IFN) – The network to create a universe from.
- Returns:
A complete graph representing the universe of the network.
- Return type:
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> universe_net = n.universe(n)
- unlearn(trajectory: list) None
Unassign (subtract weight) a trajectory from the network by setting weight = -1 for each link along the trajectory.
- Parameters:
trajectory (list) – A list of nodes representing the trajectory (node sequence) to be unlearned.
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> n.add_link('a', 'b', 1) >>> n.add_link('b', 'c', 1) >>> n.unlearn(['a', 'b', 'c'])
- static weighted_random_choice(list_nodes: list, probs: list) str
Select a random node from a list based on given probabilities.
- Parameters:
list_nodes (list of str) – List of node names.
probs (list of float) – List of probabilities corresponding to each node.
- Returns:
Selected node.
- Return type:
str
Example
>>> import IdealFlow.Network as net >>> n = net.IFN() >>> nodes = ['A', 'B', 'C'] >>> probabilities = [0.2, 0.5, 0.3] >>> result = n.weighted_random_choice(nodes, probabilities) >>> print(result) 'B'