dynsimf.models package

Subpackages

Submodules

dynsimf.models.Example module

class dynsimf.models.Example.Example

Bases: object

Base meta class for creating examples

Every example should at least contain a simulate and visualize function

abstract classmethod simulate()

Meta function

The simulate function should simulate the example

abstract classmethod visualize(output)

Meta function

The visualization function should take in the output of the simulation and visualize it

Parameters:

output (dict) – The output from the simulation

dynsimf.models.ExampleRunner module

class dynsimf.models.ExampleRunner.ExampleRunner(example)

Bases: object

This class contains the references to all the created examples that can be simulated.

They can then be ran and visualized using this class

Variables:
  • example (str) – The name of the example to simulate

  • model (object) – An object of the example class that should be simulated

initialize_model()

Initialize the correct model to simulate by creating an object of the right example class

simulate(n)

Simulate the model for n iterations and return the results

Parameters:

n (int) – The amount of iterations to simulate the model

Returns:

The output of the simulation

Return type:

dict

visualize(output)

Visualize the output of the model simulation

Parameters:

output (dict) – The output of the simulation to visualize

dynsimf.models.Model module

class dynsimf.models.Model.Model(graph, config=None, seed=None)

Bases: object

The base class used to define a model

add_edge_values_update(fun, args=None, condition=None, get_nodes=False)

Helper function that is a shorthand to set an update to update the edge values. It shows more clearly what is updated in the name and does not require an UpdateType object.

Parameters:
  • fun (function) – The function that updates the edge values. It should return a 2d array with values for each desired edge value

  • args (dict, optional) – Arguments for the given function. The keys should match the parameters of the function, defaults to None

  • condition (Condition, optional) – A single chained condition that filters the nodes. The update will only be applied on the nodes that the condition returns, defaults to None

  • get_nodes (bool, optional) – A boolean indicating whether the given function should receive a list argument that gives the indices of the nodes that the update will be applied on, defaults to False

add_network_update(fun, args=None, condition=None, get_nodes=False)

Helper function that is a shorthand to set an update to update the network. It shows more clearly what is updated in the name and does not require an UpdateType object.

Parameters:
  • fun (function) – The function that updates the network. To update the network using a function, a dictionary should be returned with specific keys indicating what kind of change the values of the dictionary are. There are three options: add, edge_change, and remove. The remove option is the most straightforward, if this key is included in the dictionary that is returned by the function, then the corresponding value should be a list of the names of all the nodes that should be removed from the network. When using the add key, the corresponding value should be a list of dictionaries, where each dictionary inside the list will serve as the initialization for a new node. This dictionary should contain 2 keys: neighbors and states. The neighbors key should have a list as value, where each entry in the list should be a name of a neighbor. This way new nodes can immediately be connected to other nodes when they are added to the network. The states key should have another dictionary as a value, in which every key can refer to a state with corresponding initial values for that node. This way, nodes can now be added to the network and their connections and states can immediately be initialized.

  • args (dict, optional) – Arguments for the given function. The keys should match the parameters of the function, defaults to None

  • condition (Condition, optional) – A single chained condition that filters the nodes. The update will only be applied on the nodes that the condition returns, defaults to None

  • get_nodes (bool, optional) – A boolean indicating whether the given function should receive a list argument that gives the indices of the nodes that the update will be applied on, defaults to False

add_property_function(fun)

Add a PropertyFunction object to the model

Parameters:

fun (PropertyFunction) – The property function to add to the model

add_scheme(scheme)

Adds a scheme to the model

Parameters:

scheme (Scheme) – The Scheme object to add to the model

add_state_update(fun, args=None, condition=None, get_nodes=False)

Helper function that is a shorthand to set an update to update states. It shows more clearly what is updated in the name and does not require an UpdateType object.

Parameters:

fun – The function to be executed and get the new state values from.

The function should return a dictionary where each key matches a state added using the set_states function.

The value for each key should either be a constant value, or an array, where each value should be the value of a node in the network.

The indices in the array match the indices of the nodes in the networkx graph. :type fun: function :param args: Arguments for the given function. The keys should match the parameters of the function, defaults to None :type args: dict, optional :param condition: A single chained condition that filters the nodes. The update will only be applied on the nodes that the condition returns, defaults to None :type condition: Condition, optional :param get_nodes: A boolean indicating whether the given function should receive a list argument that gives the indices of the nodes that the update will be applied on, defaults to False :type get_nodes: bool, optional

add_update(fun, args=None, condition=None, get_nodes=False, update_type=None)

Add an update function to the model to update the states, utility, edge values, or network of the model.

Parameters:

fun – The function to be executed and get the new state values from.

The function should return a dictionary where each key matches a state added using the set_states function.

The value for each key should either be a constant value, or an array, where each value should be the value of a node in the network.

The indices in the array match the indices of the nodes in the networkx graph. :type fun: function :param args: Arguments for the given function. The keys should match the parameters of the function, defaults to None :type args: dict, optional :param condition: A single chained condition that filters the nodes. The update will only be applied on the nodes that the condition returns, defaults to None :type condition: Condition, optional :param get_nodes: A boolean indicating whether the given function should receive a list argument that gives the indices of the nodes that the update will be applied on, defaults to False :type get_nodes: bool, optional :param update_type: The type of update, could be a state, network, edge values, or utility update. defaults to None :type update_type: UpdateType, optional

assign_network_operation(network_update_type, change, update_nodes)

Assign a network operation depending on whether the network update removes or adds nodes, or changes the adjacencies of the nodes.

Parameters:
  • network_update_type (str) – The type of the network update

  • change (any) – The first parameter of the specified network update

  • update_nodes (any) – The update to perform on the nodes

assign_update(update, update_nodes, updatables)

Function that runs the correct update execution function based on the type of the update

Parameters:
  • update (Update) – The update function

  • update_nodes (list or numpy.ndarray) – The nodes that the update function is applied on

  • updatables (dict) – Dictionary with keys as states or network keywords and values which should be assigned to the nodes

calculate_properties()

Calculate the output from the added property functions and append their results

clear()

Initialize all internal variables as empty

configure_visualization(options, output)

Configure the visualization using a dictionary and the output of a simulation

Parameters:
  • options (dict) – Dictionary with the visualization options

  • output (dict) – Output of a simulation

property constants

Constants of the model

Returns:

Model constants

Return type:

dict

create_update(update_content)

Internal function used to create an Update object

Parameters:

update_content (tuple or list) – The parameters required for an update object

Returns:

The update object created from the update content

Return type:

Update

delete_rows_columns(var, removables)

Helper function to delete a row and column from a 2d numpy array, used for removing nodes

Parameters:
  • var (numpy.ndarray) – The variable to delete the column and row of, should be 2d numpy array

  • removables (numpy.ndarray or list) – Indices of the rows and columns to delete

get_adjacency()

Get the adjacency matrix of the networkx graph

Returns:

The adjacency matrix, which is a 2d numpy array

Return type:

numpy.ndarray

get_all_edge_values()

Get all edge values for each node.

Each index in the returned array contains a 2d matrix with edge values that resembles an adjacency matrix.

Returns:

The 3d array with matrices for each edge value name

Return type:

numpy.ndarray

get_edge_values(edge_values_name)

Get the given edge values for each node

Parameters:

edge_values_name (str) – The name of the edge values to get

Returns:

a 2d array with the edge values between nodes. It resembles an adjacency matrix.

Return type:

numpy.ndarray

get_neighbors(node)

Get a list of neighbors of one node

Parameters:

node (int) – The node to get the neighbors of

Returns:

A list of node names (indices) that are adjacent to the given node

Return type:

list

get_neighbors_neighbors(node)

Get an array that shows the which neighbors the neighbors of a given node have.

Parameters:

node (int) – The node to get the neighbors’ neighbors of

Returns:

An array where each one represents that the node in that column is a neighbor of a neighbor of the given node

Return type:

numpy.ndarray

get_neighbors_neighbors_adjacency_matrix()

Returns a matrix that indicates which nodes are only connected through another node.

Returns:

A 2d numpy array where each 1 represents that the node in that row is a neighbor of a neighbor of the node in that column.

Return type:

numpy.ndarray

get_new_state(state)

Get all values for a given state for the current iteration

Parameters:

state (str) – The state to get the values for each node

Returns:

An array containing a value per node for the given state

Return type:

numpy.ndarray

get_node_new_state(node, state)

Get the value for a single state for a single node for the current iteration

Parameters:
  • node (int) – The node to get the state for

  • state (str) – The state name to get the value of

Returns:

The value for the given node’s state

Return type:

number

get_node_state(node, state)

Get the value for a single state for a single node

Parameters:
  • node (int) – The node to get the state for

  • state (str) – The state name to get the value of

Returns:

The value for the given node’s state

Return type:

number

get_node_states(node)

Get all states of a single node

Parameters:

node (int) – The node to get all states for

Returns:

An array containing values of all states for one node.

Return type:

numpy.ndarray

get_nodes_adjacency(nodes)

Get the adjacency values for a specific subset of nodes

Parameters:

nodes (list or numpy.ndarray) – A list of nodes to get the adjacency for

Returns:

A numpy.ndarray where each row matches a node from the argument and each column represents whether the node is linked to it. A 1 indicates a connection and a 0 the opposite.

Return type:

numpy.ndarray

get_nodes_state(nodes, state)

Get the value for a single state for a list of nodes

Parameters:
  • node (list[int]) – A list of nodes to get the state for

  • state (str) – The state name to get the value of

Returns:

The values for the given node’s state

Return type:

list[number]

get_nodes_states()

Get all the states of all the nodes in a 2d array.

Each row represents a node and each column represents a state.

Returns:

The 2d array with all the nodes’ states

Return type:

numpy.ndarray

get_previous_nodes_adjacency(n)

Get all the adjacency matrix from the n’th previous saved iteration

get_previous_nodes_states(n)

Get all the nodes’ states from the n’th previous saved iteration

Parameters:

n (int) – The n’th previous iteration to get the states from

Returns:

2d array with nodes’ states from the current iteration minus n

Return type:

numpy.ndarray

get_properties()

Get all properties from the PropertyFunctions of the model

Returns:

Dictionary with values for the different property functions, keys are the names and values a list of outputs of the functions as values

Return type:

dict

get_state(state)

Get all values for a given state

Parameters:

state (str) – The state to get the values for each node

Returns:

An array containing a value per node for the given state

Return type:

numpy.ndarray

get_state_index(state)

Get the internal index for a given state name

Parameters:

state (str) – Name of the state to retrieve index from

Returns:

The internal index of the state

Return type:

int

handle_adjacency_node_add(origin, neighbors)

Set new node adjacency and if applicable assign given edge values

Parameters:
  • origin (int) – Index of the origin node

  • neighbors (list[tuple]) – Format: list[(neighbor_index, edge_variable_name, origin_to_neighbor_val, neighbor_to_origin_val)]

handle_adjacency_node_overwrite(origin, neighbors)

Overwrite the adjacency of nodes

Parameters:
  • origin (int) – Origin node index to change adjacency for

  • neighbors – Neighbor indices and optional edge values for their link

Format: (neighbor_index, edge_variable_name, origin_to_neighbor_val, neighbor_to_origin_val) :type neighbors: list[tuple]

handle_adjacency_node_remove(origin, neighbors)

Remove neighbor links of an origin node

Parameters:
  • origin (int) – Origin node index to remove the connections from

  • neighbors (list or numpy.ndarray) – Array of neighbors to remove

handle_node_initialization(index, node)

Initialize a node by setting the edge values of the neighbors and setting the node states

Parameters:
  • int (index) – The index of the node in the graph

  • dict (node) – a node dictionary of the form: key (str): ‘neighbors’, value (list[tuple]): (neighbor_index, edge_values_name values_in, values_out) key (str): ‘states’, value (dict): { ‘state_name’ (str) : state_value (number) }

inactive_scheme(scheme)

Returns True when a scheme is not active this iteration

Parameters:

scheme (Scheme) – Scheme to check whether it’s active

Returns:

Bool that indicates whether the scheme is active or not

Return type:

bool

init()

Initialize the internal variables used for the simulation.

initialize_new_node()

Add a new row of 0s to the new adjacency, new edge utilities and new node states matrices Also add a new column of 0s to the new adjacency and new edge utilities

iteration()

A single iteration step. All values are calculated and assigned to their variables. The property functions of the model are executed and the next iteration is prepared.

iteration_assignment()

Assign all values from the iteration output

iteration_calculation()

The calculation part of an iteration. Every active scheme is evaluated; every update in the scheme is executed and the results are assigned.

neighbor_update_to_var(var_type, neighbors)

Get a list of neighbor indices, edge value names ingoing edge values, or outgoing edge values The input format is: [(neighbor index, edge_value_var, value_in, value_out)] If a value is not set, a 0 is returned for that neighbor

network_edges_change(change, _)

Change the edges of a network by adding and removing links.

Parameters:

change (dict) –

Dictionary with the changes to apply on the network

key (str): ‘overwrite’, value (list[tuple]): [(neighbor, edge value name, util_in, util_out)] key (str): ‘add’, value (list[tuple]): [(neighbor, edge value name, util_in, util_out)] or [neighbor, neighbor 2, neighborN] key (str): ‘remove’, value (list): [neighbor index, neighbor 2 index, neighbor 3 index]

network_nodes_add(new_nodes, _)

Add a list of new node dictionaries to the model

Parameters:

new_nodes (list[dict]) – A list of dictionaries for new nodes

network_nodes_remove(removable_nodes, _)

Remove a list of nodes from the network

Parameters:

removable_nodes (numpy.ndarray or list) – The nodes to remove from the network

property nodes
prepare_next_iteration()

Increase the iteration counter and prepare the next iteration by setting graph change flag to false

prepare_output(n)

Internal function used to create files that are used to store intermediate results of the simulation.

Parameters:

n (int) – Total amount of simulation iterations

reset()

Initialize internal variables; state and edge values to 0

set_conditions_state_indices(condition)

An internal function that is used to set the indices for each state in every condition when the simulation has started. This is used because initially only the state names are provided when the conditions are created. The function cycles through each condition and checks whether a state index should be set.

Parameters:

condition (Condition) – The first condition in the condition chain to set the state indices of

set_edge_values(edge_values_names)

Initialize the edge values of the model, an internal representation is made to keep track of the edge values and the corresponding names.

Parameters:

edge_values_names (list[str]) – A list of strings that contain the names of each edge value

set_initial_edge_values(initial_edge_values, args=None)

Set the initial values for each edge value for each node connection.

Parameters:
  • initial_state (list or number or function) – A dictionary containing either an array, function or constant value. The keys should represent edge value names and their value will be used as the initial value. In case of an array, it should be 2d and each index should match the value for the edge value between node i to j. A constant value will be duplicated for each node value for that edge value name. If a function is used, it should return either a constant value or a 2d array.

  • args (dict, optional) – Arguments to provide to every function provided in the initial_state dictionary, defaults to {}

set_initial_state(initial_state, args=None)

Set the initial values for each state for each node.

Parameters:
  • initial_state (list or number or function) – A dictionary containing either an array, function or constant value. The keys should represent state names and their value will be used as the initial value. In case of an array, the indices will be used for the correpsonding nodes. A constant value will be duplicated for each node for that state. If a function is used, it should return either a constant value or array.

  • args (dict, optional) – Arguments to provide to every function provided in the initial_state dictionary, defaults to {}

set_new_node_states(index, states)

Set the values for each state of the new node

Parameters:
  • index (int) – Index of the new node

  • states (np.ndarray or list) – An array containing values for each state for a node

set_node_neighbor_values(origin, neighbors)

Set the neighbors for an origin node and their edge values if given

Parameters:
  • origin (int) – Origin node index

  • neighbors – Array of neighbor indices and their edge values in a tuple if given

Format: [(neighbor index, edge_value_var, value_in, value_out)] :type neighbors: list[tuple] or list or numpy.ndarray

set_scheme_update_condition_state_indices(scheme)

Internal function that sets the state indices for each condition that has them in any scheme

Parameters:

scheme (Scheme) – Scheme to set the conditions’ state indices for

set_states(state_names)

Initialize the states of the model, an internal representation is made to keep track of the state values and the corresponding names.

Parameters:

state_names (list[str]) – A list of strings that contain the names of each state

simulate(n, show_tqdm=True)

Simulate the model n iterations.

Parameters:
  • n (int) – The amount of iterations to run the simulation

  • show_tqdm (bool, optional) – Shows a progress bar and estimates time until completion for the simulation, defaults to True

Returns:

Simulation output. A dictionary is returned with 3 keys: states, adjacency, and edge_values. Each value linked to a key is another dictionary with keys for each iteration of the simulation. The value for each iteration key contains the relevant values for that key for that iteration.

Return type:

dict

simulation_step()

A single iteration step. The iteration is completed and then stored or written if so configured.

simulation_steps(n, show_tqdm)

Store the initial state of the simulation and then execute the iteration_step function each iteration.

Parameters:
  • n (int) – Total amount of iterations

  • show_tqdm (bool) – Shows a progress bar and estimates time until completion for the simulation

store_adjacency_iteration()

Store the adjacency matrix of the current iteration in memory. If the configured memory size is exceeded, clear the memory.

store_edge_values_iteration()

Store the edge values for the current iteration in memory. If the configured memory size is exceeded, clear the memory.

store_simulation_step()

Store the states, adjacency, and edge values for the current iteration

store_states_iteration()

Store the states for the current iteration in memory. If the configured memory size is exceeded, clear the memory.

update_edge_values(update_nodes, updatables)

Update the edge values for each edge value returned by an update

Parameters:
  • update_nodes (numpy.ndarray or list) – the nodes to update

  • updatables (dict) – Dictionary with keys as edge value names and 2d array values which should be assigned to the nodes

update_network(update_nodes, updatables)

Assign the correct network update

Parameters:
  • update_nodes (numpy.ndarray or list) – the nodes to update

  • updatables (dict) – Dictionary with keys as network update keywords and relevant values for that network update

update_state(nodes, updatables)

Update all states from an update for the given nodes

Parameters:
  • nodes (list or numpy.ndarray) – nodes that the update should be assigned to

  • updatables (dict) – Dictionary with keys as states and values which should be assigned to the nodes for that state

valid_update_condition_nodes(update, scheme_nodes)

[summary]

Parameters:
  • update (Update) – The update to get the eligible nodes for

  • scheme_nodes (list or numpy.ndarray) – All eligible nodes from the scheme

Returns:

List of nodes that pass the condition

Return type:

list or numpy.ndarray

visualize(vis_type)

Visualize the model results using the Visualization class

Parameters:

vis_type (str) – The visualization to use

write_adjacency_iteration(n_nodes)

Write the adjacency matrix of the current iteration to a configured file

Parameters:

n_nodes (int) – The amount of nodes in the simulation

write_edge_values_iteration(n_nodes)
write_simulation_step()

Write the output of the simulation to the configured files if the iteration matches the configured save interval.

write_states_iteration(n_nodes)

Write the states of the current iteration to a configured file

Parameters:

n_nodes (int) – The amount of nodes in the simulation

class dynsimf.models.Model.ModelConfiguration(cfg=None)

Bases: object

Configuration for the model

Can be used to configure the amount of memory to be kept in memory for the states, adjacency, utility, and edge values. The configurations are done using the MemoryConfiguration class.

dynsimf.models.UtilityCostModel module

class dynsimf.models.UtilityCostModel.FunctionType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

MATRIX = 0
PAIRWISE = 1
class dynsimf.models.UtilityCostModel.SampleMethod(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

ALL = 0
CUSTOM = 2
NEIGHBORS_OF_NEIGHBORS = 1
class dynsimf.models.UtilityCostModel.UtilityCostModel(graph, cost_threshold, config=None, seed=None)

Bases: Model

add_cost_function(function, function_type)
add_node_adjacency(nodes, neighbors)
add_node_connections(nodes)
add_utility_function(function, function_type)
calculate_all_pairwise(nodes, variable, function)

Calculate the function parameter for the variable parameter pairwise for every node

calculate_cost()
calculate_fof_pairwise(nodes, variable, function)

Calculate the function parameter for the variable paramater, pairwise for every node and their neighbors of neighbors

calculate_neighbors_pairwise(nodes, variable, function)
calculate_pairwise(variable, function)
calculate_utility()
check_user_input_set()
get_eligible_neighbors_of_neighbors()

Returns a matrix where a row is a node, and a 1 means that the column node is a neighbor of a neighbor of the row node

get_inverted_adjacency_matrix()

Returns an inverted adjacency matrix, where every 1 means that there is no connection between nodes

get_nodes_utility(nodes)
get_previous_nodes_utility(n)

Get all the nodes’ utility from the n’th previous saved iteration

get_sampled_nodes()

Create a matrix of eligble nodes per node to which a connection can be formed, Every row indicates a node source node and every column a node that a connection can be formed with This function does not take any cost or utility into account

The definition of eligible nodes depends on the set SampleMethod enum

get_utility()
initialize_cost()
initialize_user_input()
initialize_utility()
iteration()

A single iteration step. All values are calculated and assigned to their variables. The property functions of the model are executed and the next iteration is prepared.

iteration_assignment()

Assign all values from the iteration output

optimize_nodes_utility()

Optimize the utility for each node Nodes that exceed the cost_threshold remove a link with lowest utility to achieve < threshold Nodes that don’t exceed the threshold add a new connection with highest utility while staying < threshold TODO: Optimize by reconfiguring existing links by checking neighborhood TODO: Do the above to do for nodes for which cost_sum == cost_threshold

prepare_output(n)

Internal function used to create files that are used to store intermediate results of the simulation.

Parameters:

n (int) – Total amount of simulation iterations

prepare_simulation()
remove_node_adjacency_and_utility(nodes, neighbors)
remove_node_connections(nodes)

Remove a neighbor for each node to get the total cost under the cost threshold, while removing the neighbor with the lowest utility for that node

TODO: Check if utility == 0 is ever possible and doesn’t get removed

set_sampling_function(sample_method, function=None)
simulate(n, show_tqdm=True)

Simulate the model n iterations.

Parameters:
  • n (int) – The amount of iterations to run the simulation

  • show_tqdm (bool, optional) – Shows a progress bar and estimates time until completion for the simulation, defaults to True

Returns:

Simulation output. A dictionary is returned with 3 keys: states, adjacency, and edge_values. Each value linked to a key is another dictionary with keys for each iteration of the simulation. The value for each iteration key contains the relevant values for that key for that iteration.

Return type:

dict

store_simulation_step()

Store the states, adjacency, and edge values for the current iteration

store_utility_iteration()
write_simulation_step()

Write the output of the simulation to the configured files if the iteration matches the configured save interval.

write_utility_iteration(n_nodes)

Module contents