dynsimf.models.tools package
Submodules
dynsimf.models.tools.SA module
- class dynsimf.models.tools.SA.SAConfiguration(config)
Bases:
objectConfiguration for Sensitivity Analysis
- Variables:
bounds (dict) – a dictionary with (str) constant (key): tuple(lower_bound, upper_bound) for indicating the bounds to sample the constants from
iterations (int) – The amount of iterations to run the model for one simulation
initial_state (dict) – The initial state of the model per simulation
initial_args (dict) – Initial arguments to pass to initial state function if provided
n (int) – The amount of samples to generate
second_order (bool) – Whether to set calc_second_order to true when Using Saltelli sample from SALib
algorithm_input (str) – When set to ‘network’, the networkx graph will be given as output,
if set to anything else the states will be outputted per simulation :var function algorithm: The algorithm or function to use on the state values, can be any function that results in one value for each node per state (e.g: mean, variance, max, or any other) :var dict algorithm_args: A dictionary with custom input params for the provided algorithm function :var str output_type: If the output_type is set to ‘reduce’, the algorithm that is provided will be applied be applied on every simulation run and the output is appended to an array This allows custom algorithms to transform the output in whatever shape is required, Otherwise the algorithm takes as default input a column that contains the values for all the nodes for one state
- set_config(config)
- validate()
- class dynsimf.models.tools.SA.SensitivityAnalysis(config, model)
Bases:
object- analyze_output(problem, output)
Analyze the output after reducing the values using the sobol.analyze function from SALib The returned value is either a dictionary with an analysis per state, or a single analysis object if there is only one input list
- analyze_sensitivity()
The main entry point to analyze the sensitivity of a model to its constants
First the constants are sampled using the saltelli sample function, then the model is simulation for all the samples generated. Each model simulation takes ‘iterations’ iterations from the config. After the simulation, the output is reduced so that each model run, results in one value per state. By default only the last iteration of a simulation is considered. This is done using the provided algorithm in the config.
Finally, the outputs are analyzed using sobol.analyze from SALib. This results in an output dictionary containing the output of sobol.analyze as value for each state (key)
- apply_algorithm(outputs)
Apply a known algorithm, or a custom algorithm on the output of the simulation runs, this will reduce the values to one value per state per simulation.
- custom_reduce(outputs)
If the output type in the config is set to ‘reduce’, the algorithm that is provided will be applied be applied on every simulation run and the output is appended to an array This allows custom algorithms to transform the output in whatever shape is required
- flatten_output(outputs)
Transform the output of the model run to a list that contains the values of the last iteration and the states in order The output is a list of 2d arrays that contain columns for states and rows for nodes where each 2d array is one model run
- get_saltelli_params()
Use saltelli sample from SALib to generate samples to use for the simulation runs And create the exact problem dictionary that SALib requires.
- get_state_dict()
Return a dictionary with the states as keys, and an empty numpy array as value
- parse(outputs)
Flatten the output of all the iterations per simulation runs, for each node and their states Then apply an algorithm on the runs/nodes/states to get one value for each simulation run that can be analyzed
- run_model(params, names)
Simulate the model for ‘iterations’ iterations and either return the networkx graph as output, or the complete simulation output (states, etc)
- set_model(params, names)
Reset the model and set the new sampled params
- state_reduce(outputs, fun, args=None)
Create a dictionary that holds states as keys and reduces the values across all nodes to a single value using a provided algorithm (e.g: average value for all nodes per state)
dynsimf.models.tools.Visualizer module
- class dynsimf.models.tools.Visualizer.VisualizationConfiguration(config)
Bases:
objectConfiguration for the visualizer
- Variables:
plot_interval (int) – An integer indicating the interval between iterations to store a new plot, defaults to 1
initial_positions (dict) – A dictionary with (int) node (key): tuple((x_pos (float), y_pos (float))) (value) pairs that indicate the initial positions, defaults to None
fixed_positions (dict) – A dictionary with (int) node (key): tuple((x_pos (float), y_pos (float))) (value) pairs that indicate stationary positions of the nodes, defaults to None
plot_variable (str) – A string indicating the main variable to plot as the node color, defaults to None
color_scale (str) – A string indicating the matplotlib color scale to use, defaults to Reds
show_plot (bool) – Inidicates whether the animated plot should be shown after the simulation, defaults to True
repeat (bool) – Indicates whether the animated plot should repeat itself after fully playing, defaults to True
plot_output (str) – The path + name + extension of where the output of the animation should be saved, if it is not set, the plot will not be saved, defaults to None
save_fps (int) – The frames per second the saved animation should have, defaults to 5
plot_title (str) – The title of the plot, defaults to Network visualization
layout (str or function) – The layout of the network used for the visualization, this can be a networkx layout function, a custom function, or a string indicating a built-in function, like fr. This will then use the layout_fruchterman_reingold from the igraph package. If a custom function is used, it should return a dictionary where they keys are nodes and the values are tuples with their x and y positions as floats. Defaults to None
layout_params (dict) – A dictionary that is unpacked when calling the layout function if a custom layout function is set. The keys should correspond with the parameters of the function. Defaults to None
edge_alpha (float) – The alpha of the edges between nodes in the plot, defaults to 0.2
edge_values (str) – A string indicating which edge_values variable from the model should be used to visualize the edge colors, defaults to None
directed (bool) – Indicates whether the network plot should have directed edges, defaults to True
: dict save_arguments: unpacks to the mpl.animation.Animation.save(filename, **save_arguments). This can consist of writer, fps, dpi, codec, etc. If given, it overwrites other given inputs such as save_fps.
- set_config(config)
Set the config, its default values and validate it after
- Parameters:
config (dict) – Dictionary containing the values for the members of the configuration class, When certain keys/value pairs are not provided, default values are used
- validate()
Validate the config using the ConfigValidator class.
- Raises:
ValueError – if a class member does not match its expected type or range, or if is not optional and has not been set
- class dynsimf.models.tools.Visualizer.Visualizer(config, model_input)
Bases:
objectVisualizer class handling animations and plotting
- Variables:
config (VisualizationConfiguration) – The config class containing all configuration values
graph (networkx.classes.graph.Graph) – The networkx graph to plot
state_map (dict) – A dictionary mapping the state names (str) to the index of the state column in the 2d states array
edge_values_map (dict) – A dictionary mapping the edge value names (str) to the index of the edge values arrays
states (dict) – A dictionary where the key is an iteration (int) and the values are a 2d array with columns as state values and rows as nodes
adjacencies (dict) – A dictionary where the key is an iteration (int) and the values are network adjacency matrices
edge_values (dict) – A dictionary where the key is an iteration (int) and the values are network edge values
utilities (dict) – A dictionary where the key is an iteration (int) and the values are utility values per edge
max_iteration (int) – The max amount of iterations that are available
- animation()
This function displays and animates the visualization.
The plot is being cleared and redrawn every plot. If configured, the plot will be shown and saved.
- assign_dynamic_graph_values()
For each iteration and adjacency matrix, generate new locations or use the previous ones if the graph hasn’t changed
- assign_static_graph_values()
- create_adjacency_node_locations(adjacency_matrix, initial_positions)
Create a networkx graph from an adjacency matrix and return the generated locations of the nodes
- Parameters:
adjacency_matrix (numpy.ndarray) – The adjacency matrix to turn into a networkx graph
initial_positions (Dict or None) – The initial positions to use when generating new positions
- Returns:
A tuple containing the new networkx graph and the corresponding node positions
- Return type:
tuple
- create_graph_node_locations()
Create locations of the graph for graph is static positions is set, use intitial positions if set
- create_layout(graph, initial_positions=None)
Generate new positions for the nodes in a given graph, using initial positions if given
- Parameters:
graph (networkx.classes.graph.Graph) – The graph with the nodes to generate the locations for
initial_positions (Dict, optional) – Optional initial positions to use when creating the node locations
- Returns:
A dictionary with nodes as keys and tuples of form (x_pos, y_pos) as values
- Return type:
dict
- create_locations()
Generate locations for all the adjacency graphs for each iteration
- create_new_positions_graph(iteration, adjacency_matrix, last_index)
Create new graphs: if it is the first iteration and initial positions have been given, use them, otherwise use the previous graph’s calculated positions as initial positions if there are any
- Parameters:
iteration (int) – The iteration to store and create the positions for
adjacency_matrix (numpy.ndarray) – The adjacency matrix that the positions should be generated for
last_index (int) – The last iteration that the locations were generated for
- get_initial_positions(last_index)
Check if last_index has already any locations generated, if so use it as initial position for the next location generation
- Returns:
Initial positions to use for the next location generation
- Return type:
dict or None
- get_last_index(variable, index)
Find the key index in the dictionary variable. If index does not exist, subtract 1 from index and try again. Keep repeating this, until a value is found.
- Parameters:
variable (dict) – The dictionary to find the key for
index (int) – The index to find the key in the dict for
- Returns:
The found key in the dictionary that matches the index parameter.
- Return type:
int
- get_node_colors()
Helper function to create a list of floats that indicate the colors of each node.
If utility is selected, the values are taken from the utility arrays, otherwise the correct state is chosen
- Returns:
list of lists where each list corresponds to a list of floats that indicate the color for each node
- Return type:
list
- get_total_iterations()
Get the total amount of iterations that can be used for the visualization
- Returns:
The total amount of iterations
- Return type:
int
- static read_states_from_file(path)
Reads in saved states to disk and returns a numpy array
Note: Has to be reworked
- Parameters:
path (str) – The path to read the states from
- save_plot(simulation)
Save the plot to a file, specified in plot_output in the visualization configuration The file is generated using the writer from the pillow library
- Parameters:
simulation – Output of matplotlib animation.FuncAnimation
- setup_animation()
Setup the animation by creating all the necessary elements for the plot
- Returns:
tuple containing all necessary plot elements: state_names: names of all the states to display, n_states: integer with all the states, node_colors: list will all the colors of the nodes for each iteration, fig: matplotlib figure, gs: figure gridspec, network: subplot to plot the network in, axis: list of axes to display the barplots, n: amount of plots, cm: colormap to use, vmin: minimum value of the node colors, vmax: maximum value of the node colors, colors: 25 values between 0 and 1 on the colormap
- visualize(vis_type)
Navigate to the appropriate visualisation function