src package
Subpackages
- src.gss package
- Submodules
- src.gss.Data_simulation_util module
- src.gss.GSS_analysis module
GSS
GSS.bins
GSS.compute_kl_divergence()
GSS.data_analysis()
GSS.data_preparation()
GSS.distributed_gss_data
GSS.goodness_of_fit()
GSS.gss_data
GSS.gss_data_groups
GSS.gss_histograms
GSS.initial_data
GSS.kl_divergence
GSS.model
GSS.number_of_agents
GSS.plot_distributed_data()
GSS.plot_gss_participants()
GSS.plot_kl_divergence()
GSS.rescale_data()
GSS.data_key
GSS.simulation_histograms
GSS.time_period
GSS.xlim
GSS.years
GSS.ylim
parameter_search()
- src.gss.image_util module
- Module contents
Submodules
src.agent module
- class src.agent.Agent
Bases:
object
An agent in the ABM
- get_coordinates()
returns x and y as a list
- get_opinion()
returns the value of the opinion
- get_x()
returns the value of the coordinates
- get_y()
returns the value of the coordinates
- set_opinion(new_opinion)
sets the value of the opinion
- set_x(new_x)
sets the value of the coordinates
- set_y(new_y)
sets the value of the coordinates
src.bifurcations module
- class src.bifurcations.BifurcationAnalysis(num_iterations: int, parameters: list, delta_t: float, init_xlim: tuple[float, float] = (-0.25, 0.25), init_ylim: tuple[float, float] = (-0.25, 0.25), init_oplim: tuple[float, float] = (-1, 1), useDoublewell: bool = False, spatial_clustering=True, opinion_clustering: bool = True, dynamic_eps: bool = False, useHDBSCAN: bool = True, datasim: bool = False, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None, boundary: bool = True, normalize_with_neighbour_num: bool = False, input_df: DataFrame | None = None, initialize: bool = True, data_bank: str | None = None)
Bases:
object
This class will handle all the bifurcation analysis and parameter variation. It is structured the same way as the ModelStatistics class.
- diversity_metrics(methods: list, timestep: int | None = None)
This function serves as a general function that calls the implemented diversity metrics. Allowed values for methods are “average_local_agreement”, “polarization”, “opinion_diversity”, “network_disagreement_index”, “polarization_level” and “radicalisation_level”.
- Parameters:
methods (list of str) –
diversity metrics to be calculated. methods must belong to the set {“average_local_agreement”, “polarization”,
”opinion_diversity”, “network_disagreement_index”, “polarization_level”, “radicalisation_level”}
- Returns:
res – list of calculated averaged diversity metrics in input order.
- Return type:
list
- plot_assortativity_time_series(axs: ndarray[Axes] | Axes, max_timestep: int | None = None, title=None, plot_all_realizations=False, plot_stdw=False, parameter_subset: list[int] | None = None) Axes | ndarray[Axes]
Plot the mean assortativity time series for a Parameter Sweep either in one or several axes objects. Possibly plot all the all realizations or the standard deviations envelope. @param axs: optinal axes object @param title: optinal, bool
plot
@param plot_all_realizations: @param plot_stdw: @return:
- plot_diversity_metrics(bifurcation_parmeter: str, methods, timestep: int | None = None, ax: Axes | None = None, print_title=True, print_legend: bool = True, xlabel: str | None = None, ylabel: str | None = None, marker: list | list[str] | None = None, marker_colors: list[str] | None = None, confidence_level=None, std_error=False)
- simulate(steps, n_processes=-1, clear=False)
src.model module
- class src.model.Model(N: int, R: float | tuple[float, float], alpha: float, beta: float, sigma_op: float, sigma_sp: float, delta_t: float, init_xlim: tuple[float, float] = (-0.25, 0.25), init_ylim: tuple[float, float] = (-0.25, 0.25), init_oplim: tuple[float, float] = (-1, 1), useDoublewell: bool = False, seed: int | None = None, spatial_clustering: bool = True, opinion_clustering: bool = True, dynamic_eps: bool = False, useHDBSCAN: bool = True, datasim: bool = False, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None, boundary: bool = True, normalize_with_neighbour_num: bool = False)
Bases:
object
Agent-based model using the class Agent. This class handles all calculations analysis and visualization for a single realization.
- Brownian_motion()
generate brownian motion
- Return type:
A value emulating brownian motion
- boundary()
Enforces the boundary conditions (only for the outer boundaries of the domain)
- Return type:
None.
- calculate_distances()
calculates all pairwise distances between current agents and updates the distance matrix
- Return type:
None.
- calculate_eps(minpoints=None)
calculates the knee point of the k-neighbours graph, where k is the minimum number of points/agents in a cluster. This value is considered to be the optimal value for eps. The calculated eps shall not be larger than the opinion radius or the spatial radius.
- Parameters:
minpoints (int, optional) – min_samples parameter for DBSCAN clustering. The default is None, resulting in the usage of the class variable minpoints.. The default is None.
- Returns:
min_eps (float) – The minimum of the calculated eps, opinion radius and spatial radius.
bounded (bool) – specifies if either the opinion radius or the spatial radius was smaller than the calculated eps.
- cluster(eps=None, minpoints=None)
clusters the agents using DBSCAN or HDBSCAN, if clustering is enabled
- Parameters:
eps (float, optional) – eps parameter used for DBSCAN/HDBSCAN clustering. The default is None, resulting in the usage of the class variable eps.
minpoints (int, optional) – min_samples parameter for DBSCAN clustering. The default is None, resulting in the usage of the class variable minpoints.
- Return type:
None.
- compute_borders()
computes the borders of the gridcells class variable borders is a dictionary containing a 4-tuple for each gridcell. the 4-tuple describes the cell boundaries (left, right, lower, upper)
- Return type:
None.
- double_well_potential(x: float, y: float) float
Definition of the double well potential for plotting.
- Parameters:
x (int) – x-coordinate.
y (int) – y-coordinate.
- Returns:
double-well potential at the coordinate.
- Return type:
int
- get_adjacency_matrix(useR_sp: bool = True, time_step: int | None = None)
Returns the adjacency matrix of the latest snapshot. Two agents are adjacent to each other if the distance between them is smaller than the spatial radius.
- Parameters:
useR_sp (@param) – specifies if the spatial radius should be used to determine adjacency. The default is True.
useR_sp – If false, the opinion Radius will be used for the network. The default is True
time_step (@param) – for which timestep the adjacency matrix is computed. The default is the end of the simulation.
- Returns:
res – adjacency matrix, describing the edges of the network. The rows and columns of the matrix represent the agents. Entries of the matrix are 0 and 1 indicating no edge and edge, respectively.
- Return type:
numpy matrix
- get_clusters()
returns the list of labels which show the cluster-membership of all agents
- Returns:
list of cluster labels.
- Return type:
list
- get_coordinates()
returns the coordinates of all agents as a list of lists
- Returns:
coordinates of all agents [[x1,y1],[x2,y2]…].
- Return type:
list of lists
- get_data()
returns a dataframe containing coordinates, opinions and gridcell
- Return type:
list
- get_degree_distributions(time_step: int | None = None, bins: int | ndarray | None = None) dict[str, tuple[int, int]]
Returns the degree distribution of the network defined by the spatial and opinion interaction function respectively. The network corresponds to the final timestep of the model.
- Returns:
dict
containing the spatial degree distribution with key ‘spatial’ as numpy ndarray
and the opinion degree distribution with key ‘opinion’ as numpy ndarray. The first entry of each array contains
the counts and the second entry the bin edges.
- get_grid_cell(coordinate)
calculates the gridcell, given a coordinate. The cells of the 3x3 grid are enumerated as follows:
6 7 8 3 4 5 0 1 2
- Parameters:
coordinate (tuple of floats) – x and y coordinate (x,y).
- Returns:
int – gridcell in which the coordinate is located at.
None – if the coordinate is outside of the grid
- get_opinions()
returns the opinion of all agents as a list
- Returns:
opinions of all agents.
- Return type:
list
- get_results()
returns the dictionary containing the simulation
- Returns:
Dictionary containing “Coordinates”, “Opinions”, “Networks”, “Cluster Labels” and “gridcell”.
- ”Coordinates”: list of pandas DataFrames
Each DataFrame contains the x coordinates of agents in the first column and y coordinates of agents in the second column. The list index corresponds to the simulation snapshot.
- ”Opinions”: pandas DataFrame
Rows represent agents and columns represent simulation snapshots. The entries are the opinion values.
- Return type:
dictionary
- ”Networks”: list of numpy matrices
The list index corresponds to the simulation snapshot. Each entry is the adjacency matrix, describing the network, for the snapshot.
- ”Cluster Labels”: pandas DataFrame
Rows represent agents and columns represent simulation snapshots. The entries are the cluster label, with -1 denoting noise.
- ”gridcell”: pandas DataFrame
Rows represent agents and columns represent simulation snapshots. The entries are the gridcell the agent is located in. The cells of the 3x3 grid are enumerated as follows:
6 7 8 3 4 5 0 1 2
- get_results_as_numpy_array()
Converts the results to a numpy array So that it can be saved more efficently. We are ommiting some data, like adjacency matrix, clustering, grid cells etc.
- global_assortativity(time_step: int | None = None, use_spatial_radius: bool = True) float
- initialize_model(input_df: DataFrame | None = None)
- initialize the location and opinion of all agents randomly and calculate the distances and clustering.
A input matrix can be provided to define the intitialization of the agents
- Parameters:
input_df (Nx3 pd.DataFrame, optional) – Matrix containing x coordinates for all agents in the first column, y coordinates in the second column and opinions in the third column. The default is None.
- Return type:
None.
- opinion_interaction(k)
defines interaction map influencing opinion states (V tilde)
- Parameters:
k (int) – index of agent.
- Returns:
change to opinion of agent k from spatial interactions.
- Return type:
float
- opinion_pairwise_interaction(k, j)
defines pairwise interaction map (V)
- Parameters:
k (int) – index of first agent.
j (int) – index of second.
- Returns:
change to opinion of agent k from pairwise spatial interaction to agent j.
- Return type:
float
- partialX(x: float) float
- partialY(y: float) float
- plot(*args, **kwargs) Axes
- plot_opinions(*args, **kwargs) Axes
- plot_with_marginals(*args, **kwargs) Figure | None
- set_results_from_numpy_array(array, cluster=False)
Brings loaded data into the appropriate data formats.
- set_useDoubleWell(useDoublewell)
sets the value of the class variable useDoublewell
- Parameters:
useDoublewell (bool) – Value the class variable useDoublewell is set to.
- Return type:
None.
- simulate(number_of_steps=1)
Simulate the model for a single step or multiple steps using the euler-maruyama method
- Parameters:
number_of_steps (int, optional) – number of consecutive steps to be simulated . The default is 1.
- Return type:
None.
- spatial_interaction(k)
defines interaction map influencing spatial movement(U tilde)
- Parameters:
k (int) – index of agent.
- Returns:
float – change to x coordinate of agent k from spatial interactions.
float – change to y coordinate of agent k from spatial interactions.
- spatial_pairwise_interaction(k, j)
defines pairwise interaction map (U)
- Parameters:
k (int) – index of first agent.
j (int) – index of second.
- Returns:
float – change to x coordinate of agent k from pairwise spatial interaction to agent j.
float – change to y coordinate of agent k from pairwise spatial interaction to agent j..
src.model_plot_lib module
- class src.model_plot_lib.ModelPlotter(model)
Bases:
object
- plot(timestep: int | None = None, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None, print_title: bool | None = True, show_network: bool = False, use_spatial_network: bool = True, show_clusters: bool = False, ax: ~matplotlib.pyplot.axes | None = None, show_landscape: bool = False, landscape_colorbar=True, cmap: str | ~matplotlib.colors.Colormap = 'turbo', op_cmap: str | ~matplotlib.colors.Colormap = <matplotlib.colors.LinearSegmentedColormap object>, node_color: ~typing.Iterable | None = None, colorbar_left: bool = False, colorbar: bool = True, colorbar_ticks: ~typing.Iterable | None = None, colorbar_fontsize: float | None = None, cluster_legend_outside: bool = True, opinion_label: str = 'Opinion', s: float | None = None, network_alpha: float | None = None, network_lw: float | None = None, node_linewidth: float = None) Axes
Plots the agents in the social space.
- Parameters:
timestep (@param) – timestep/snapshot of the simulation which is to be plotted. The default is None, resulting in plotting of the latest snapshot of the simulation.
xlim (@param) – interval of the x-axis (lower bound, upper bound) of the figure. The default is None.
ylim (@param) – interval of the y-axis (lower bound, upper bound) of the figure. The default is None.
print_title (@param) – specifies if the title should be printed. The default is True.
show_network (@param) – specifies if the network edges should be shown. The default is False.
use_spatial_network (@param) – The default is True. If False, the network induced by R_op is plotted
network_alpha (@param) – Sets the opacity for the network. The Default is None.
network_lw (@param) – Sets the line width for the edges in the network. The default is None and will use the default from networkx.
show_clusters (@param) – specifies if cluster membership should be shown. The default is False.
ax (@param) – object on which the graph is plotted. The default is None, resulting in the creation of a new Axes object.
show_landscape (@param) – specifies if the double well potential should be shown. The default is False.
cmap (@param) –
- specifies which color map should be used for the potential landscape (parula, turbo).
The default is “turbo”.
op_cmap (@param) –
- specifies which color map should be used for the opinions. The default is the red-blue colormap with
a discontinuity at zero. The custom colormap can be found in the plotting_functions.py file.
s (@param) – The size of the markers used for the agent in the social space. The dfault is None and will use the default size in matplotlib.pyplot.rcParams
colorbar_left (@param) – Will move the colorbar to the left of the figure. The default is False. This is important, when plotting the marginal distribution of agents in the social space.
opinion_label (@param) – Sets the label for the colorbar. The default is “Opinion”
cluster_legend_outside (@param) – If True the legend for the cluster marker will be located outside the figure. Otherwise, the legend will be located in the figure and may overlap with the plot.
colorbar_fontsize (@param) – Sets the font size for the colorbar labels.
colorbar_ticks (@param) – Set the ticks for the colorbar. Must contain floats.
colorbar (@param) – Determines if the colorbar will be plotted.
- Raises:
ValueError – Raised if cmap is not “parula” or “turbo”.
- Return type:
An Axes object from matplotlib containing the plot.
- plot_degree_distributions(ax: axes | None = None, plot_title: bool = True, time_step: int | None = None, bins: int | ndarray | None = None) Axes
Plots the degree distribution. If R_sp = R_op the bars are colored according to the average opinion of the agents with that degree.
- Parameters:
ax (@param)
plot_title (@param) – Default is True.
time_step (@param) – Timestep to plot the degree distribution
bins (@param) – If the input is an int, it determines the number of bins, if a nnumpy array is given, the entries detrmine the edges of the bins.
- Returns:
matplotlib axis object with a bar plots for the degree distribution
- Return type:
result
- plot_global_assortativity(ax: Axes | None = None, use_Rsp=True) Axes
- plot_opinions(timestep: int | None = None, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None, bins: int | ndarray | None = 50, print_title: bool = True, ax: Axes | None = None, density: bool = True) Axes
Creates a histogram of the opinion in the population. :param @param timestep: timestep/snapshot of the simulation which is to be plotted. The default is None, resulting in plotting of
the latest snapshot of the simulation.
- Parameters:
xlim (@param) – interval of the x-axis (lower bound, upper bound). The default is None.
ylim (@param) – interval of the y-axis (lower bound, upper bound). The default is None.
bins (@param) – number of bins used for the histogram. The default is 50. If an array is supplied, it will define edges of the bins.
print_title (@param) – specifying if the title should be shown. The default is True.
ax (@param) – object on which the graph is plotted. The default is None, resulting in the creation of a new Axes object.
measures (@param) – Specifies which diversity measures should be added to the legend. It has to be one of the following: “average_local_agreement”, “polarization”, “opinion_diversity”, “network_disagreement_index”, “polarization_level”,”radicalisation_level”
density (@param) – If True, the histogram will be scaled as a density and not a probability mass function.
- Return type:
An Axes object from matplotlib containing the plot.
- plot_with_marginals(timestep: int | None = None, bins: int | ndarray = 31, show_landscape: bool = False, show_clusters: bool = False, show_network: bool = True, use_spatial_network: bool = True, print_title: bool = True, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None, filename: str | None = None, xlabel: str | None = None, ylabel: str | None = None, opinion_label: str | None = None, fig=typing.Optional[matplotlib.figure.Figure], no_ticks: bool = False, colorbar: bool = True, s: float | None = None, network_alpha: float | None = None, network_lw: float | None = None, hist_ylim: int = None, node_linewidth=None) Figure
Create a plot of the agents in the social space with the marginal distributions plotted next to the social space. The colors of the histogram bins correspond to the average opinion of the agents that contribute to that bin. @param timestep : int, optional
timestep/snapshot of the simulation which is to be plotted. The default is None, resulting in plotting of the latest snapshot of the simulation.
- @param bins: int, numpy.ndarray, optional
Set the bin_edegs directly or the number of bin edges. So for 5 bins set 6.
- @param hist_ylim: int, optional
set the upper limit for the histograms. The lower Limit is 0. The default is the maximum count of both hitograms
- @param filename: str, optional
If specified, the plot will be saved here. Include the file ending and path to directoty if needed.
- @param xlabel:str, optional
Label for x-axis
- @param ylabel:str, optional
Label for y-axis
- @param fig: Figure object from Matplotlib, optional,
object on which the graph is plotted. The default is None, resulting in the creation of a new Figure object.
- @param no_ticks: bool
remove the numbering on the x-axis and y-axis of the social space
- @param xlimtuple of floats, optional
interval of the x-axis (lower bound, upper bound) of the figure. The default is None.
- @param ylimtuple of floats, optional
interval of the y-axis (lower bound, upper bound) of the figure. The default is None.
- @param print_titlebool, optional
specifies if the title should be printed. The default is True.
- @param show_networkbool, optional
specifies if the network edges should be shown. The default is False.
- @param use_spatial_networkbool, optional
The default is True. If False, the network induced by R_op is plotted
- @param network_alpha: float, optional
Sets the opacity for the network. The Default is None.
- @param network_lw: str, optional
Sets the line width for the edges in the network. The default is None and will use the default from networkx.
- @param show_clustersbool, optional
specifies if cluster membership should be shown. The default is False.
- @param show_landscapebool, optional
specifies if the double well potential should be shown. The default is False.
- @param cmapstr, optional
- specifies which color map should be used for the potential landscape (parula, turbo).
The default is “turbo”.
- @param op_cmapstr, optional
- specifies which color map should be used for the opinions. The default is the red-blue colormap with
a discontinuity at zero. The custom colormap can be found in the plotting_functions.py file.
- @param s: float, optional
The size of the markers used for the agent in the social space. The dfault is None and will use the default size in matplotlib.pyplot.rcParams
- @param colorbar_left: bool, optional
Will move the colorbar to the left of the figure. The default is False. This is important, when plotting the marginal distribution of agents in the social space.
- @param opinion_label: str, optional
Sets the label for the colorbar. The default is “Opinion”
- @param cluster_legend_outside: bool, optional
If True the legend for the cluster marker will be located outside the figure. Otherwise, the legend will be located in the figure and may overlap with the plot.
- @param colorbar_fontsize: float, optional
Sets the font size for the colorbar labels.
- @param colorbar_ticks: Iterable
Set the ticks for the colorbar. Must contain floats.
- @param colorbar: bool
Determines if the colorbar will be plotted.
@return: plt.Figure object
src.plotting_aux_file module
src.statistics module
Created by Soeren Nagel
This file contains the ModelStatistics Class that handles any statistics related to the Model class.
For a main overview of how and what data is stored, see the documentation of the get_results() method.
- class src.statistics.ModelStatistics(num_iterations: int, N: int, R: float | tuple[float, float], alpha: float, beta: float, sigma_op: float, sigma_sp: float, delta_t: float, init_xlim: tuple[float, float] = (-0.25, 0.25), init_ylim: tuple[float, float] = (-0.25, 0.25), init_oplim: tuple[float, float] = (-1, 1), useDoublewell: bool = False, spatial_clustering: bool = True, opinion_clustering: bool = True, dynamic_eps: bool = False, useHDBSCAN: bool = True, datasim: bool = False, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None, boundary: bool = True, normalize_with_neighbour_num: bool = False, input_df: DataFrame | None | list[DataFrame] = None, initialize: bool = True, seed: int | None = None)
Bases:
object
This class is ment to handle all statistics and bifurcation analysis of the underlying Model.
- clear() None
Clears any data in the instance and creates new empty model instances. This method can be used if the amounts of data exceed the memory.
- data_exists(steps, final=False) bool
Checks if this instance exists in the DataBank folder. The steps need to be specified, since data can only be loaded into an empty instance.
- get_results() dict
Returns the dictionary containing the simulation data from all the individual Model instances.
- Returns:
Dictionary containing “Coordinates”, “Opinions”
- ”Coordinates”: lists of pandas DataFrames
Each DataFrame (i.e., get_results()[time_step]) contains the x coordinates of agents in the first column and y coordinates of agents in the second column. The list index corresponds to the simulation snapshot. The coordinaters are stacked on top of each other fo the columns of each dataframe have length slef.num_iterations*self.N. To access the data of indivual models, use the get_results on individual models in self.models.
- Return type:
dictionary
- ”Opinions”: pandas DataFrame
Rows represent agents and columns represent simulation snapshots. The entries are the opinion values. The shape of the dataframe is (num_agents x num_iterations) x num_timesteps
- global_assortativity(time_step=None) ndarray
- load_results_from_numpy(folder, final=False) None
Loads saved data from the given folder. The filename is automatically defined via the __repr__ method. So any data can be read by creating a new instance of the class by using the filename without the .npy extension.
- plot_opinions(timestep: int | None = None, ylim: tuple[float, float] | None = None, bins: int | ndarray = 30, print_title: bool = True, ax: Axes | None = None) Axes
Plots the average opinionn distribution for the given timestep.
- Parameters:
timestep (@param) – timestep/snapshot of the simulation which is to be plotted. The default is None, resulting in plotting of the latest snapshot of the simulation.
ylim (@param) – interval of the y-axis (lower bound, upper bound). The default is None.
bins (@param) – number of bins used for the histogram. The default is 50. If an array is supplied, it will define edges of the bins
print_title (@param) – specifying if the title should be shown. The default is True.
ax (@param) – object on which the graph is plotted. The default is None, resulting in the creation of a new Axes object.
- Return type:
An Axes object from matplotlib containing the plot.
- save_results_as_numpy(folder: str, final=False) None
Save the results to a .npy file in the specified folder. The name is python-readable (without the .npy) file extension. So any stored data can be read by creating a new instance of the class by using the filename and then loading the data. @param folder: @return: None
- simulate(steps: int, n_processes=-1) None
Runs the simulations in parallel to speed up thinks a little bit.
- Parameters:
steps (int Number of steps for each simulation)
n_processes (int Number of processes to be started simultaneously Default: Use all available)