Full API
Figure objects figure.py
Figure objects.
- Figures can be plotted by calling an instance of the relevant class,
e.g. f = Skyrms2010_3_3() will create a figure object and simultaneously plot it.
- class figure.Figure(evo=None, game=None, **kwargs)
Abstract superclass for all figures.
- abstract show()
Show the plot of the figure with the current parameters, typically with plt.show().
This is an abstract method that must be redefined for each subclass.
- Return type:
None.
- abstract reset()
Reset parameters for the figure.
This is an abstract method that must be redefined for each subclass.
- Return type:
None.
- classmethod demo_warning()
Warn the user that they are running in demo mode.
- Return type:
None.
- class figure.Scatter(**kwargs)
Superclass for scatter plots
- reset(x, y, xlabel, ylabel, marker_size=10, marker_color='k', xlim=None, ylim=None, xscale=None, yscale=None)
Update figure parameters, which can then be plotted with self.show().
- Parameters:
x (array-like) – x-axis coordinates.
y (array-like) – y-axis coordinates.
xlabel (str) – x-axis label.
ylabel (str) – y-axis label.
marker_size (int, optional) – Size of the markers for each data point. The default is 10.
marker_color (str, optional) – Color of the datapoint markers. The default is “k”.
xlim (array-like, optional) – Minimum and maximum values of x-axis. The default is None.
ylim (array-like, optional) – Minimum and maximum values of y-axis. The default is None.
xscale (str, optional) – x-axis scaling i.e. linear or logarithmic. The default is None.
yscale (str, optional) – y-axis scaling i.e. linear or logarithmic. The default is None.
- Return type:
None.
- show()
Show figure with the current parameters.
- Return type:
None.
- property marker_size
Marker color
- property marker_color
Line connecting the markers
- class figure.Quiver(**kwargs)
Superclass for Quiver plots
- class figure.Quiver2D(scale=20, **kwargs)
Plot a 2D quiver plot.
- reset(color=None, xlabel=None, ylabel=None)
Set global attributes for the 2D quiver plot.
- show()
Display the 2D quiver plot with the loaded data.
- Raises:
NoDataException – The requisite data has not been supplied by the user.
- Return type:
None.
- uv_from_xy(p_sender_1, p_receiver_1)
Take proportions of first sender strategy (p_sender_1) and first receiver strategy (p_receiver_1), and using the self.evo object, return velocities of both strategies.
- Parameters:
- Returns:
change_in_senders_1 (float) – Change in the proportion of the first sender strategy.
change_in_receivers_1 (float) – Change in the proportion of the first receiver strategy.
change_in_senders_2 (float) – Change in the proportion of the second sender strategy.
change_in_receivers_2 (float) – Change in the proportion of the second receiver strategy.
- class figure.Quiver3D(color='k', normalize=True, length=0.5, arrow_length_ratio=0.5, pivot='middle', camera_dist=13, camera_dist_noaxis=10, **kwargs)
Plot a 3D quiver plot.
- reset(color='k', normalize=True, length=0.5, arrow_length_ratio=0.5, pivot='middle', camera_dist=13, camera_dist_noaxis=10)
Update figure parameters.
- Parameters:
color (str, optional) – Color of the arrows. The default is “k” (black).
normalize (bool, optional) – Normalize the arrows. The default is True.
length (float, optional) – Length of the arrows. The default is 0.5.
arrow_length_ratio (float, optional) – Ratio of the arrow length to the length of the arrowhead(?). The default is 0.5.
pivot (str, optional) – Pivot point of the arrows. The default is “middle”.
camera_dist (int, optional) – Camera distance. The default is 13.
camera_dist_noaxis (int, optional) – Camera distance when axes are off. The default is 10.
- show()
Display the 3D quiver plot with the loaded data.
- Raises:
NoDataException – The requisite data has not been supplied.
- Return type:
None.
- vector_to_barycentric(vector)
Convert a 4d vector location to its equivalent within a tetrahedron
- Parameters:
vector (array-like) – 4-D vector to be converted to a barycentric location.
- Returns:
barycentric_location – 3-D barycentric coordinates on a tetrahedron.
- Return type:
array-like
- class figure.Bar(**kwargs)
Bar chart abstract superclass.
- reset(x, y, xlabel, ylabel, bar_color='w', xlim=None, ylim=None, yscale=None)
Update figure parameters
- Parameters:
x (array-like) – x-axis coordinates.
y (array-like) – y-axis coordinates.
xlabel (str) – x-axis label.
ylabel (str) – y-axis label.
bar_color (str, optional) – Color of the bars. The default is “w”.
xlim (array-like, optional) – Minimum and maximum values of x-axis. The default is None.
ylim (array-like, optional) – Minimum and maximum values of y-axis. The default is None.
yscale (str, optional) – y-axis scaling i.e. linear or logarithmic. The default is None.
- Return type:
None.
- show()
Display the bar chart with the loaded data.
- Raises:
NoDataException – The requisite data has not been supplied. Bar charts need x-axis values and y-axis values.
- Return type:
None.
- class figure.Ternary(**kwargs)
Superclass for ternary (2-simplex) plots
- reset(right_corner_label, top_corner_label, left_corner_label, fontsize=10, colors=None)
Update figure parameters, which can then be plotted with self.show().
- Parameters:
right_corner_label (str) – Label for the right corner of the ternary plot.
top_corner_label (str) – Label for the top corner of the ternary plot.
left_corner_label (str) – Label for the left corner of the ternary plot.
fontsize (int) – Font size of the corner labels.
colors (list) – List of colors for the ternary plot. Each color corresponds to an orbit, i.e. an element of self.xyzs.
- Return type:
None.
- show()
Display the ternary plot with the loaded data.
- Raises:
NoDataException – The requisite data was not supplied. Ternary plots require an <xyzs> attribute.
- Return type:
None.
- class figure.Surface(**kwargs)
Superclass for 3D surface plots (e.g. colormap). Uses ax.plot_surface().
- reset(x=None, y=None, z=None, xlabel=None, ylabel=None, zlabel=None, xlim=None, ylim=None, zlim=None, cmap=<matplotlib.colors.LinearSegmentedColormap object>, linewidth=1, antialiased=False, elev=25.0, azim=245, dist=12) None
Update figure parameters, which can then be plotted with self.show().
- Parameters:
x (array-like) – x-axis values.
y (array-like) – y-axis values.
z (array-like) – z-axis values.
xlabel (str, optional) – x-axis label. The default is None.
ylabel (str, optional) – y-axis label. The default is None.
zlabel (str, optional) – z-axis label. The default is None.
xlim (array-like, optional) – Minimum and maximum values of x-axis. The default is None.
ylim (array-like, optional) – Minimum and maximum values of y-axis. The default is None.
zlim (array-like, optional) – Minimum and maximum values of z-axis. The default is None.
cmap (matplotlib.colors.LinearSegmentedColormap, optional) – Color mapping. The default is cm.coolwarm.
linewidth (float(?) or int, optional) – Width of the lines in the surface. The default is 1.
antialiased (bool, optional) – Whether the figure is antialiased. The default is False.
elev (float) – camera elevation
azim (int) – camera azimuth
dist (int) – camera distance
- Return type:
None.
Evolve objects evolve.py
Calculate equations to evolve populations in a game. Right now, we can calculate the replicator (-mutator) dynamics, with one or two populations, in discrete or continuous time
- class evolve.OnePop(game, playertypes)
Calculate the equations necessary to evolve one population. It takes as input a <game> and an array such that the <i,j> cell gives the expected payoff for the-strategist player of an encounter in which they follow strategy i and their opponent follows strategy j.
- random_player()
Return frequencies of a random sender population
- Returns:
Array of frequencies of a random sender population
- Return type:
array-like
- avg_payoff(player)
Return the average payoff that players get when the population vector is <player>
- Parameters:
player (array-like) – Population vector describing a mixed population.
- Returns:
Average payoff of the population.
- Return type:
- avg_payoff_vector(player)
Get expected payoffs of every type when population vector is <player>.
Depends on assortment.
p(s_i meets s_i) = p(s_i) + self.e * (1-p(s_i)) p(s_i meets s_j) = p(s_j) - self.e * p(s_j)
- Parameters:
player (array-like) – Population vector describing a mixed population.
- Returns:
Array of average payoffs of the population.
- Return type:
array-like
- replicator_dX_dt_odeint(X, t)
Calculate the rhs of the system of odes for scipy.integrate.odeint
- Parameters:
X (array-like) – Population vector at time t.
t (float) – Time.
- Returns:
Right-hand side of the system of ODEs.
- Return type:
array-like
- replicator_jacobian_odeint(X, t=0)
Calculate the Jacobian of the system of odes for scipy.integrate.odeint
- Parameters:
X (array-like) – Population vector at time t.
t (float) – Time.
- Returns:
Jacobian of the system of ODEs.
- Return type:
array-like
- discrete_replicator_delta_X(X)
Calculate a population vector for t’ given the vector for t, using the discrete time replicator dynamics (Huttegger 2007)
- Parameters:
X (array-like) – Population vector at time t.
- Returns:
Population vector at time t+1.
- Return type:
array-like
- replicator_odeint(init, time_vector, **kwargs)
Calculate one run of the game following the replicator(-mutator) dynamics, with starting points sinit and rinit, in times <times> (an evolve.Times instance), using scipy.integrate.odeint
- Parameters:
init (array-like) – Initial population vector.
time_vector (array-like) – Time vector.
kwargs (dict) – Additional keyword arguments for odeint.
- Returns:
Population vectors at each time point.
- Return type:
array-like
- replicator_discrete(initpop, steps)
Calculate one run of the game, following the discrete replicator(-mutator) dynamics, for <steps> steps with starting population vector <initpop> using the discrete time replicator dynamics.
- Parameters:
initpop (array-like) – Initial population vector.
steps (int) – Number of steps to take.
- Returns:
Population vectors at each time point.
- Return type:
array-like
- pop_to_mixed_strat(pop)
Take a population vector and output the average strat implemented by the whole population
- Parameters:
pop (array-like) – Population vector.
- Returns:
Average strategy implemented by the whole population.
- Return type:
array-like
- class evolve.TwoPops(game, sendertypes, receivertypes)
Calculate the equations necessary to evolve a population of senders and one of receivers. It takes as input a <game>, (which as of now only can be a Chance object), and a tuple: the first (second) member of the tuple is a nxm array such that the <i,j> cell gives the expected payoff for the sender (receiver) of an encounter in which the sender follows strategy i and the receiver follows strategy j.
- random_sender()
Return frequencies of a random sender population
- Returns:
Array of frequencies of a random sender population
- Return type:
array-like
- random_receiver()
Return frequencies of a random receiver population
- Returns:
Array of frequencies of a random receiver population
- Return type:
array-like
- sender_avg_payoff(sender, receiver)
Return the average payoff that senders get when the population vectors are <sender> and <receiver>
- Parameters:
sender (array-like) – Population vector describing a mixed sender population.
receiver (array-like) – Population vector describing a mixed receiver population.
- Returns:
Average payoff of the sender population.
- Return type:
- receiver_avg_payoff(receiver, sender)
Return the average payoff that receivers get when the population vectors are <sender> and <receiver>
- Parameters:
sender (array-like) – Population vector describing a mixed sender population.
receiver (array-like) – Population vector describing a mixed receiver population.
- Returns:
Average payoff of the receiver population.
- Return type:
- replicator_dX_dt_odeint(X, t)
Calculate the rhs of the system of odes for scipy.integrate.odeint
- Parameters:
X (array-like) – Population vector at time t.
t (float) – Time.
- Returns:
Right-hand side of the system of ODEs.
- Return type:
array-like
- replicator_dX_dt_ode(t, X)
Calculate the rhs of the system of odes for scipy.integrate.ode
- Parameters:
t (float) – Time.
X (array-like) – Population vector at time t.
- Returns:
Right-hand side of the system of ODEs.
- Return type:
array-like
- replicator_jacobian_odeint(X, t=0)
Calculate the Jacobian of the system for scipy.integrate.odeint
- Parameters:
X (array-like) – Population vector at time t.
t (float) – Time.
- Returns:
Jacobian of the system of ODEs.
- Return type:
array-like
- replicator_jacobian_ode(t, X)
Calculate the Jacobian of the system for scipy.integrate.ode
- Parameters:
t (float) – Time.
X (array-like) – Population vector at time t.
- Returns:
Jacobian of the system of ODEs.
- Return type:
array-like
- discrete_replicator_delta_X(X)
Calculate a population vector for t’ given the vector for t, using the discrete time replicator dynamics (Huttegger 2007)
- Parameters:
X (array-like) – Population vector at time t.
- Returns:
Population vector at time t+1.
- Return type:
array-like
- replicator_odeint(sinit, rinit, times, **kwargs)
Calculate one run of the game following the replicator(-mutator) dynamics, with starting points sinit and rinit, in times <times> (an evolve.Times instance), using scipy.integrate.odeint
- Parameters:
sinit (array-like) – Initial sender population vector.
rinit (array-like) – Initial receiver population vector.
times (evolve.Times object) –
kwargs (dict) – Additional keyword arguments for odeint.
- Returns:
Population vectors at each time point.
- Return type:
array-like
- replicator_ode(sinit, rinit, times, integrator='dopri5')
Calculate one run of the game, following the replicator(-mutator) dynamics in continuous time, in <times> (an evolve.Times instance) with starting points sinit and rinit using scipy.integrate.ode
- Parameters:
sinit (array-like) – Initial sender population vector.
rinit (array-like) – Initial receiver population vector.
times (evolve.Times object) –
integrator (str) – Name of the integrator to use.
- Returns:
Population vectors at each time point.
- Return type:
array-like
- replicator_discrete(sinit, rinit, times)
Calculate one run of the game, following the discrete replicator(-mutator) dynamics, in <times> (an evolve.Times object) with starting population vector <popvector> using the discrete time replicator dynamics. Note that this solver will just calculate n points in the evolution of the population, and will not try to match them to the times as provided.
- Parameters:
sinit (array-like) – Initial sender population vector.
rinit (array-like) – Initial receiver population vector.
times (evolve.Times object) –
- Returns:
Population vectors at each time point.
- Return type:
array-like
- vector_to_populations(vector)
Take one of the population vectors returned by the solvers, and output two vectors, for the sender and receiver populations respectively.
- Parameters:
vector (array-like) – Population vector.
- Returns:
Tuple of two arrays, one for the sender and one for the receiver populations.
- Return type:
- sender_to_mixed_strat(senderpop)
Take a sender population vector and output the average sender strat implemented by the whole population
- Parameters:
senderpop (array-like) – Sender population vector.
- Returns:
Average sender strategy implemented by the whole population.
- Return type:
array-like
- receiver_to_mixed_strat(receiverpop)
Take a receiver population vector and output the average receiver strat implemented by the whole population
- Parameters:
receiverpop (array-like) – Receiver population vector.
- Returns:
Average receiver strategy implemented by the whole population
- Return type:
array-like
- class evolve.Reinforcement(game, agents)
Evolving finite sets of agents by reinforcement learning.
- reset()
Initialise values and agents.
- Return type:
None.
- run(iterations, hide_progress=True, calculate_stats='step')
Run the simulation for <iterations> steps.
- is_pooling(epsilon=0.001)
Determine whether the current strategies are pooling or a signalling system.
If the mutual information between states and acts at the current population state is within <epsilon> of the maximum possible, it’s a signalling system. Otherwise, it’s pooling.
Clearly if the number of signals is lower than both the number of states and the number of acts, it will necessarily be pooling.
- class evolve.Matching(game, agents)
Reinforcement according to Richard Herrnstein’s matching law. The probability of choosing an action is proportional to its accumulated rewards.
- class evolve.MatchingSR(game, sender_strategies, receiver_strategies)
Matching simulation for two-player sender-receiver game.
- step(calculate_stats=True)
Implement the matching rule and increment one step.
- In each step:
Run one round of the game.
Update the agents’ strategies based on the payoffs they received.
Calculate and store any required variables e.g. information.
Update iteration.
- Parameters:
calculate_stats (bool) – Whether to calculate statistics at the end of the step.
- Return type:
None.
- calculate_stats()
Calculate and store informational quantities at this point.
- Return type:
None.
- class evolve.MatchingSRInvention(game, sender_strategies, receiver_strategies)
- Matching simulation for two-player sender-receiver game,
with the possibility of new signals at every step.
- step(calculate_stats=True)
Implement the matching rule and increment one step.
- In each step:
Run one round of the game.
Update the agents’ strategies based on the payoffs they received.
Calculate and store any required variables e.g. information.
Update iteration.
- Parameters:
calculate_stats (bool) – Whether to calculate statistics at the end of the step.
- Return type:
None.
- calculate_stats()
Calculate and store informational quantities at this point.
- Return type:
None.
- class evolve.MatchingSIR(game, sender_strategies, intermediary_strategies, receiver_strategies)
Reinforcement game for sender, intermediary, receiver.
- step(calculate_stats=True)
Implement the matching rule and increment one step.
- In each step:
Run one round of the game.
Update the agents’ strategies based on the payoffs they received.
Calculate and store any required variables e.g. probability of success.
Update iteration.
- Parameters:
calculate_stats (bool) – Whether to calculate statistics at the end of the step.
- Return type:
None.
- calculate_stats()
Just call the record_probability_of_success method.
- record_probability_of_success()
For now, just store “probability of success.”
- Return type:
None.
- class evolve.BushMostellerSR(game, sender_strategies, receiver_strategies, learning_parameter)
Bush_mosteller reinforcement simulation for two-player sender-receiver game.
- step(calculate_stats=True)
Implement the matching rule and increment one step.
- In each step:
Run one round of the game.
Update the agents’ strategies based on the payoffs they received.
Calculate and store any required variables e.g. information.
Update iteration.
- Parameters:
calculate_stats (bool) – Whether to calculate statistics at the end of the step.
- Return type:
None.
- calculate_stats()
Calculate and store informational quantities at this point.
- Return type:
None.
- class evolve.Agent(strategies)
Finite, discrete agent used in Reinforcement() objects.
- choose_strategy(input_data)
Sample from self.strategies[input_data] to get a concrete response.
- When the strategies are simply a matrix,
with each row defining a distribution over possible responses, <input_data> is an integer indexing a row of the array.
- So we choose that row and choose randomly from it,
according to the conditional probabilities of the responses, which are themselves listed as entries in each row.
- E.g. if this is a sender, <input_data> is the index of the current state of the world,
and the possible responses are the possible signals.
- If this is a receiver, <input_data> is the index of the signal sent,
and the possible responses are the possible acts.
- Parameters:
input_data (int) – The state (if sender) or signal (if receiver) the agent just observed.
- Returns:
response – The index of the agent’s response.
- Return type:
int.
- update_strategies(input_data, response, payoff)
- The agent has just played <response> in response to <input_data>,
and received <payoff> as a result.
- They now update the probability of choosing that response for
that input data, proportionally to <payoff>.
- update_strategies_bush_mosteller(input_data, response, payoff, learning_parameter)
Update strategies according to the Bush-Mosteller reinforcement rule.
From Skyrms 2010 page 86:
- “If an act is chosen and a reward is gotten
the probability is incremented by adding some fraction of the distance between the original probability and probability one. Alternative action probabilities are decremented so that everything adds to one. The fraction used is the product of the reward and some learning parameter.”
- Parameters:
input_data (int) – The state (if sender) or signal (if receiver) the agent just observed.
response (int) – The signal (if sender) or act (if receiver) the agent just performed.
payoff (int) – The payoff the agent just received.
learning_parameter (float) – Learning parameter for Bush-Mosteller reinforcement.
- Return type:
None.
- abstract add_signal()
Add a new signal to the player’s repertoire.
- class evolve.Sender(strategies)
Agent type that observes a state of the world and sends a signal.
- class evolve.Receiver(strategies)
Agent that receives a signal and performs an action.
- class evolve.Times(initial_time, final_time, time_inc)
Provides a way of having a single time input to both odeint and ode
Game objects games.py
Set up an asymmetric evolutionary game, that can be then fed to the evolve module. There are two main classes here:
Chance: Games with a chance playerNonChance: Games without a chance player
- class games.Chance(state_chances, sender_payoff_matrix, receiver_payoff_matrix, messages)
Construct a payoff function for a game with a chance player, that chooses a state, among m possible ones; a sender that chooses a message, among n possible ones; a receiver that chooses an act among o possible ones; and the number of messages
- choose_state()
Return a random state, relying on the probabilities given by self.state_chances
- Returns:
Index of the chosen state
- Return type:
- sender_payoff(state, act)
Return the sender payoff for a combination of <state> and <act>
- receiver_payoff(state, act)
Return the receiver payoff for a combination of <state> and <act>
- sender_pure_strats()
Return the set of pure strategies available to the sender
- Returns:
Array with all pure sender strategies
- Return type:
numpy array
- receiver_pure_strats()
Return the set of pure strategies available to the receiver
- Returns:
Array with all pure receiver strategies
- Return type:
numpy array
- payoff(sender_strat, receiver_strat)
Calculate the average payoff for sender and receiver given concrete sender and receiver strats
- Parameters:
sender_strat (numpy array) – Sender strategy
receiver_strat (numpy array) – Receiver strategy
- Returns:
Tuple with the average payoff for the sender and the receiver
- Return type:
- avg_payoffs(sender_strats, receiver_strats)
Return an array with the average payoff of sender strat i against receiver strat j in position <i, j>
- Parameters:
sender_strats (numpy array) – Array with multiple sender strategies
receiver_strats (numpy array) – Array with multiple receiver strategies
- Returns:
Array with the average payoff for each combination of sender and receiver strategies
- Return type:
numpy array
- calculate_sender_mixed_strat(sendertypes, senderpop)
Calculate the mixed strategy of the sender given the types and the population
- Parameters:
sendertypes (numpy array) – Array with the sender types
senderpop (numpy array) – Population proportion of each of the strategy types in sendertype
- Returns:
Effective mixed strategy of this sender population
- Return type:
numpy array
- create_gambit_game()
Create a gambit object based on this game.
[SFM: UPDATE: this method has changed significantly to comply with pygambit 16.1.0. Original note: For guidance creating this method I followed the tutorial at https://nbviewer.org/github/gambitproject/gambit/blob/master/contrib/samples/sendrecv.ipynb and adapted as appropriate.]
- Returns:
g
- Return type:
Game() object from pygambit package.
- property has_info_using_equilibrium: bool
Does this game have an information-using equilibrium? This is a lazy property: it only calculates the answer once, and then stores it for later use.
- Returns:
If True, the game has at least one information-using equilibrium. If False, the game does not have an information-using equilibrium.
- Return type:
- property highest_info_using_equilibrium: tuple
Get the mutual information between states and acts at the equilibrium with the highest such value. Also get the strategies at this equilibrium
Note that if the game has no information-using equilibria, the value of mutual information will be 0. The strategies returned will then be an arbitrary equilibrium.
- Returns:
First element is a list containing the highest-info-using sender and receiver strategies. Second element is the mutual information between states and acts given these strategies.
- Return type:
- class games.ChanceSIR(state_chances=array([0.5, 0.5]), sender_payoff_matrix=array([[1., 0.], [0., 1.]]), intermediary_payoff_matrix=array([[1., 0.], [0., 1.]]), receiver_payoff_matrix=array([[1., 0.], [0., 1.]]), messages_sender=2, messages_intermediary=2)
A sender-intermediary-receiver game with Nature choosing the state.
- choose_state()
Randomly get a state according to self.state_chances
- Returns:
state – Index of the chosen state.
- Return type:
- payoff_sender(state, act)
Get the sender’s payoff when this combination of state and act occurs.
- payoff_intermediary(state, act)
Get the intermediary’s payoff when this combination of state and act occurs.
- payoff_receiver(state, act)
Get the receiver’s payoff when this combination of state and act occurs.
- avg_payoffs_regular(snorm, inorm, rnorm)
Return the average payoff of all players given these strategy profiles.
Requires game to be regular.
- Parameters:
snorm (array-like) – Sender’s strategy profile, normalised.
inorm (array-like) – Intermediary player’s strategy profile, normalised.
rnorm (array-like) – Receiver’s strategy profile, normalised.
- Returns:
payoff – The average payoff given these strategies. The payoff is the same for every player.
- Return type:
- class games.NonChance(sender_payoff_matrix, receiver_payoff_matrix, messages)
Construct a payoff function for a game without chance player: a sender that chooses a message, among n possible ones; a receiver that chooses an act among o possible ones; and the number of messages
- sender_pure_strats()
Return the set of pure strategies available to the sender. For this sort of games, a strategy is a tuple of vector with probability 1 for the sender’s state, and an mxn matrix in which the only nonzero row is the one that correspond’s to the sender’s type.
- Returns:
Array with all pure sender strategies
- Return type:
numpy array
- receiver_pure_strats()
Return the set of pure strategies available to the receiver
- Returns:
Array with all pure receiver strategies
- Return type:
numpy array
- payoff(sender_strat, receiver_strat)
Calculate the average payoff for sender and receiver given concrete sender and receiver strats
- Parameters:
sender_strat (numpy array) – Sender strategy
receiver_strat (numpy array) – Receiver strategy
- Returns:
Tuple with the average payoff for the sender and the receiver
- Return type:
- avg_payoffs(sender_strats, receiver_strats)
Return an array with the average payoff of sender strat i against receiver strat j in position <i, j>
- Parameters:
sender_strats (numpy array) – Array with multiple sender strategies
receiver_strats (numpy array) – Array with multiple receiver strategies
- Returns:
Array with the average payoff for each combination of sender and receiver strategies
- Return type:
numpy array
- calculate_sender_mixed_strat(sendertypes, senderpop)
Calculate the mixed strategy of the sender given the types and the population
- Parameters:
sendertypes (numpy array) – Array with the sender types
senderpop (numpy array) – Population proportion of each of the strategy types in sendertypes
- Returns:
Effective mixed strategy of this sender population
- Return type:
numpy array
- calculate_receiver_mixed_strat(receivertypes, receiverpop)
Calculate the mixed strategy of the receiver given the types and the population
- Parameters:
receivertypes (numpy array) – Array with the receiver types
receiverpop (numpy array) – Population proportion of each of the strategy types in receivertypes
- Returns:
Effective mixed strategy of this receiver population
- Return type:
numpy array
- create_gambit_game()
Create a gambit object based on this game.
[SFM: UPDATE: this method has changed significantly to comply with pygambit 16.1.0. Original note: For guidance creating this method I followed the tutorial at https://nbviewer.org/github/gambitproject/gambit/blob/master/contrib/samples/sendrecv.ipynb and adapted as appropriate.]
- Returns:
g
- Return type:
Game() object from pygambit package.
- class games.NoSignal(payoff_matrix)
Construct a payoff function for a game without chance player: and in which no one signals. Both players have the same payoff matrix
- pure_strats()
Return the set of pure strategies available to the players. For this sort of games, a strategy is a probablity vector over the set of states
- Returns:
Array with all pure strategies
- Return type:
numpy array
- payoff(first_player, second_player)
Calculate the average payoff for first and second given concrete strats
- Parameters:
first_player (numpy array) – First player strategy
second_player (numpy array) – Second player strategy
- Returns:
The average payoff for both players given these strategies. In this class both players have the same payoff matrix.
- Return type:
- avg_payoffs(player_strats)
Return an array with the average payoff of strat i against strat j in position <i, j>
- Parameters:
player_strats (numpy array) – Array with multiple strategies
- Returns:
Array with the average payoff for each combination of strategies
- Return type:
numpy array
- calculate_mixed_strat(types, pop)
Calculate the mixed strategy of the population given the types and the population
- Parameters:
types (numpy array) – Array with the types
pop (numpy array) – Population proportion of each of the strategy types in types
- Returns:
Effective mixed strategy of this population
- Return type:
numpy array
- class games.ActAct(sender_payoff_matrix, receiver_payoff_matrix)
Construct a payoff function for a game without a chance player: a sender that chooses an act among m possible ones; and a receiver that chooses an act among o possible ones. There are no messages, though “sender” and “receiver” terminology is retained for easy comparison to other classes. Payoffs are determined by both acts, and are not necessarily the same for both players.
- sender_pure_strats()
Return the set of pure strategies available to the sender. It’s an mxm matrix where each row specifies the probabilities of playing each of the m acts. Because pure strategies are deterministic, each row is a unit vector with a single 1 and the rest 0s. Therefore, the result is an identity matrix of size m.
- Returns:
Array with all pure sender strategies
- Return type:
numpy array
- receiver_pure_strats()
Return the set of pure strategies available to the sender. It’s an oxo matrix where each row specifies the probabilities of playing each of the o acts. Because pure strategies are deterministic, each row is a unit vector with a single 1 and the rest 0s. Therefore, the result is an identity matrix of size o.
- Returns:
Array with all pure receiver strategies
- Return type:
numpy array
- payoff(sender_strat, receiver_strat)
Calculate the expected payoff for sender and receiver given concrete sender and receiver strats.
- Parameters:
sender_strat (numpy array) – Sender strategy. A list of probabilities of length self.acts_sender
receiver_strat (numpy array) – Receiver strategy. A list of probabilities of length self.acts_receiver
- Returns:
Tuple with the expected payoff for the sender and the receiver
- Return type:
- avg_payoffs(sender_strats, receiver_strats)
Kind of a souped-up version of payoff(). Basically we run payoff() once for each combination of sender and receiver strategies and return the results in a matrix.
Return an array with the average payoff of sender strategy i against receiver strategy j in position <i, j>.
- Parameters:
sender_strats (numpy array) – Array with multiple sender strategies. Must have m columns.
receiver_strats (numpy array) – Array with multiple receiver strategies. Must have o columns.
- Returns:
Array with the average payoff for each combination of sender and receiver strategies
- Return type:
numpy array
- calculate_sender_mixed_strat(sendertypes, senderpop)
Calculate the mixed strategy of the sender given the types and the population.
- Parameters:
sendertypes (numpy array) – Array such that each element is a sender type (itself a 1D numpy array with probabilities of playing each act).
senderpop (vector (numpy array)) – 1D array where each entry is the population proportion playing the corresponding strategy in sendertypes.
- Returns:
Effective mixed strategy of this sender population
- Return type:
vector (numpy array)
- calculate_receiver_mixed_strat(receivertypes, receiverpop)
Calculate the mixed strategy of the receiver given the types and the population
- Parameters:
receivertypes (numpy array) – Array such that each element is a receiver type (itself a 1D numpy array with probabilities of playing each act).
receiverpop (vector (numpy array)) – 1D array where each entry is the population proportion playing the corresponding strategy in receivertypes.
- Returns:
Effective mixed strategy of this receiver population
- Return type:
vector (numpy array)
- games.lewis_square(n=2)
Factory method to produce a cooperative nxnxn signalling game (what Skyrms calls a “Lewis signalling game”).
- Returns:
game – A nxnxn cooperative signalling game.
- Return type:
Chance object.
- games.gambit_example(n=2, export=False, fpath='tester.efg')
- Create the gambit representation of a cooperative nxnxn game
and compute its Nash equilibria.
- Optionally output as an extensive-form game, which can be
loaded into the Gambit GUI.
- Return type:
None.
Calculations calculate.py
Solve large batches of games. There are a bunch of idyosincratic functions here. This module is mostly for illustration of use cases.
- calculate.one_basin_discrete(game, trials, times)
Calculate evolutions for <trials> starting points of <game> (which is an instance of game.Evolve), in <times> (an instance of game.Times).
- Parameters:
game (One of the Evoke game classes.) – Game to be solved.
trials (int) – Number of starting points to be used.
times (evolve.Times object.) –
- calculate.one_basin_discrete_aux(triple)
Calculate the one_basin loop using replicator_discrete.
- Parameters:
triple (tuple) – A tuple with the following elements: int – The index of the trial One of the Evoke game classes – The game to be solved evolve.Times object
- calculate.one_basin_mixed(game, trials, times)
Calculate evolutions for <trials> starting points of <game> (which is an instance of game.Evolve), in <times> (an instance of game.Times)
- Parameters:
game (One of the Evoke game classes) – Game to be solved
trials (int) – Number of starting points to be used
times (evolve.Times object) –
- calculate.one_basin_aux_mixed(triple, print_trials=True)
Calculate the one_basin loop. First lsoda, then dopri5 if error
- calculate.one_basin_aux(triple)
Calculate the one_basin loop using replicator_odeint
- Parameters:
triple (tuple) – A tuple with the following elements: int – The index of the trial One of the Evoke game classes – The game to be solved evolve.Times object
- calculate.one_basin_ode_aux(triple)
Calculate the one_basin loop using one_run_ode
- Parameters:
triple (tuple) – A tuple with the following elements: int – The index of the trial One of the Evoke game classes – The game to be solved evolve.Times object
- calculate.one_batch(fileinput, directory, alreadydone='')
Take all games in <fileinput> and calculate one_basin on each. Save in <directory>
- calculate.pop_vector(vector)
Test if <vector> is a population vector: sums a total of 2, and every value is larger or equal than zero
- Parameters:
vector (numpy.array) – The vector to be tested
- calculate.test_endstate(array)
Test if <array> is composed by two concatenated probability vectors
- Parameters:
array (numpy.array) – The array to be tested
Calculations relating to common interest common_interest.py
Analyses of common interest
- class common_interest.CommonInterest_1_pop(game)
Calculate quantities useful for the study of the degree of common interest between senders and receivers
- K(array)
Calculate K as defined in Godfrey-Smith and Martinez (2013) – but using scipy.stats.kendalltau
- Parameters:
array (2D numpy array) – The payoff array to be analyzed
- Returns:
The K value for the array
- Return type:
- C_chance()
Calculate C as defined in Godfrey-Smith and Martinez (2013) – but using scipy.stats.kendalltau
- Returns:
The C value for the chance node game
- Return type:
- common_interest.intra_tau(unconds, array)
Calculate the average (weighted by <unconds> of the pairwise Kendall’s tau distance between rows (states) of <array>
- Parameters:
unconds (1D numpy array) – The unconditioned probabilities of the states
array (2D numpy array) – The payoff array to be analyzed
- class common_interest.CommonInterest_2_pops(game)
Calculate quantities useful for the study of the degree of common interest between senders and receivers
- K(array)
Calculate K as defined in Godfrey-Smith and Martinez (2013) – but using scipy.stats.kendalltau
- Parameters:
array (2D numpy array) – The payoff array to be analyzed
- Returns:
The K value for the array
- Return type:
- C_chance()
Calculate C as defined in Godfrey-Smith and Martinez (2013) – but using scipy.stats.kendalltau
- Returns:
The C value for the chance node game
- Return type:
- common_interest.C(vector1, vector2)
Calculate C for two vectors
- Parameters:
vector1 (1D numpy array) – The first vector to be compared
vector2 (1D numpy array) – The second vector to be compared
- Returns:
The C value for the two vectors
- Return type:
- common_interest.tau(vector1, vector2)
Calculate the Kendall tau statistic among two vectors
- Parameters:
vector1 (1D numpy array) – The first vector to be compared
vector2 (1D numpy array) – The second vector to be compared
- Returns:
The Kendall tau statistic for the two vectors
- Return type:
- common_interest.total_tau(array1, array2)
Calculate the KTD between the flattened <array1> and <array2>. Useful for NonChance games
- Parameters:
array1 (2D numpy array) – The first array to be compared
array2 (2D numpy array) – The second array to be compared
- Returns:
The KTD between the two arrays
- Return type:
- common_interest.tau_per_rows(unconds, array1, array2)
Calculate the average (weighted by <unconds> of the Kendall’s tau distance between the corresponding rows (states) of <array1> and <array2>
- Parameters:
unconds (1D numpy array) – The unconditioned probabilities of the states
array1 (2D numpy array) – The first array to be compared
array2 (2D numpy array) – The second array to be compared
- Returns:
The KTD between the two arrays
- Return type:
- class common_interest.Nash(game)
Calculate Nash equilibria
- receivers_vs_sender(sender)
Calculate the list a receiver’s average payoff against all possible senders
- Parameters:
sender (1D numpy array) – The sender to be analyzed
- Returns:
The list of average payoffs for the receiver against all possible senders
- Return type:
- senders_vs_receiver(receiver)
Calculate the list a sender’s average payoff against all possible receivers
- Parameters:
receiver (1D numpy array) – The receiver to be analyzed
- Returns:
The list of average payoffs for the sender against all possible receivers
- Return type:
- common_interest.stability(array)
Compute a coarse grained measure of the stability of the array
- Parameters:
array (2D numpy array) – The array to be analyzed
- Returns:
“stable” if the array is stable, “periodic” if it is periodic, and “nonstable” if it is not stable
- Return type:
- common_interest.stable_vector(vector)
Return true if the vector does not move
- Parameters:
vector (1D numpy array) – The vector to be analyzed
- Returns:
True if the vector is stable
- Return type:
- common_interest.periodic_vector(vector)
We take the FFT of a vector, and eliminate all components but the two main ones (i.e., the static and biggest sine amplitude) and compare the reconstructed wave with the original. Return true if close enough
- Parameters:
vector (1D numpy array) – The vector to be analyzed
- Returns:
True if the vector is periodic
- Return type:
Calculations relating to information theory info.py
Information-theoretic analyses
- class info.Information(game, sender, receiver)
Calculate information-theoretic quantities between strats. It expects a game, as created by game.Chance or game.NonChance, a sender strategy, and a receiver strategy
- joint_states_messages()
Get the joint distribution of states and messages
- Return type:
A (n x m) numpy array of joint probabilities [[P(A1,B1), … , P(An,B1)], … , [P(A1,Bm), …, P(An,Bm)]]
- joint_messages_acts()
Get the joint distribution of messages and acts
- Return type:
A (m x p) numpy array of joint probabilities [[P(B1,C1), … , P(Bm,C1)], … , [P(B1,Cp), …, P(Bm,Cp)]]
- joint_states_acts()
Get the joint distribution of states and acts
- Return type:
A (n x p) numpy array of joint probabilities [[P(A1,C1), … , P(An,C1)], … , [P(A1,Cp), …, P(An,Cp)]]
- mutual_info_states_acts()
Calculate the mutual info between states and acts
- Return type:
A float with the mutual information between states and acts
- mutual_info_states_messages()
Calculate the mutual info between states and messages
- Return type:
A float with the mutual information between states and messages
- mutual_info_messages_acts()
Calculate the mutual info between messages and acts
- Return type:
A float with the mutual information between messages and acts
- class info.RDT(game, dist_tensor=None, epsilon=0.001)
Calculate the rate-distortion function for a game and any number of distortion measures
- dist_tensor_from_game()
Return normalize_distortion() for sender and receiver payoffs
- Return type:
A (2 x n x n) numpy array of distortion matrices
- blahut(lambda_DUMMY, max_rounds=100, return_cond=False)
Calculate the point in the R(D, D’) surface with slopes given by lambda_DUMMY and mu. Follows Cover & Thomas 2006, p. 334
- Parameters:
lambda_DUMMY (a tuple of floats, the Lagrange multipliers for the) –
measures (distortion) –
max_rounds (the maximum number of iterations to calculate the point) –
return_cond (whether to return the conditional matrix) –
- update_conditional(lambda_DUMMY, output)
Calculate a new conditional distribution from the <output> distribution and the <lambda_DUMMY> parameters. The conditional probability matrix is such that cond[i, j] corresponds to P(x^_j | x_i)
- Parameters:
lambda_DUMMY (a tuple of floats, the Lagrange multipliers for the) –
measures (distortion) –
output (a numpy array with the output distribution) –
- Return type:
A numpy array with the conditional distribution
- calc_distortion(cond, matrix)
Calculate the distortion for a given channel (individuated by the conditional matrix in <cond>), for a certain slice of self.dist_tensor
- Parameters:
cond (a numpy array with the conditional distribution characterising a channel) –
matrix (an integer with the index of the distortion matrix in self.dist_tensor) –
- calc_rate(cond, output)
Calculate the rate for a channel (given by <cond>) and output distribution (given by <output>)
- Parameters:
cond (a numpy array with the conditional distribution characterising a channel) –
output (a numpy array with the output distribution) –
- Return type:
A float with the rate
- from_cond_to_RD(cond, dist_measures)
Take a channel matrix, cond, where cond[i, j] gives P(q^[j] | q[i]), and calculate rate and distortions for it. <dist_measures> is a list of integers stating which distortion measures we want.
- Parameters:
cond (a numpy array with the conditional distribution characterising a channel) –
dist_measures (a list of integers with the indices of the distortion matrices) –
self.dist_tensor (in) –
- Return type:
A tuple with the rate and the distortions
- class info.OptimizeRate(game, dist_measures=None, dist_tensor=None, epsilon=0.0001)
A class to calculate rate-distortion surface with a scipy optimizer
- make_calc_RD()
Return a function that calculates an RD (hyper-)surface using the trust-constr scipy optimizer, for a given list of distortion objectives.
- Return type:
A function that calculates the RD surface for a given list of distortions
- rate(cond_flat)
Calculate rate for make_calc_RD()
- Parameters:
cond_flat (a numpy array with the conditional distribution characterising a channel) –
- Return type:
A float with the rate
- cond_init()
Return an initial conditional matrix
- Return type:
A numpy array with the conditional distribution characterising a channel
- gen_lin_constraint(distortions)
Generate the LinearConstraint object
- Parameters:
distortions (A list of distortion objectives) –
- Return type:
A LinearConstraint object
- lin_constraint()
Collate all constraints
- Return type:
A numpy array with the constraints
- dist_constraint()
Present the distortion constraint (which is linear) the way scipy.optimize expects it
- Return type:
A numpy array with the distortion constraint
- prob_constraint()
Present the constraint that all rows in cond be probability vectors. We use a COO sparse matrix
- Return type:
A COO sparse matrix with the probability constraint
- class info.OptimizeMessages(game, dist_measures=None, dist_tensor=None, epsilon=0.0001)
A class to calculate number-of-messges/distortion curves with a scipy optimizer
- make_calc_MD()
Return a function that calculates the minimum distortion attainable for a certain number of messages, using a trust-constr scipy optimizer. Right now it only works for one distortion measure. <distortion> is the distortion matrix in <dist_tensor> that we should care about.
- Return type:
A function that calculates the minimum distortion for a certain number
- distortion(codec_flat, messages, matrix)
Calculate the distortion for a given channel (individuated by the conditional matrix in <cond>), for a certain slice of self.dist_tensor
- Parameters:
codec_flat (a numpy array with the conditional distribution characterising a channel) –
messages (an integer with the number of messages) –
matrix (an integer with the index of the distortion matrix in self.dist_tensor) –
- Return type:
A float with the distortion
- codec_init_random(messages)
Return an initial conditional matrix
- Parameters:
messages (an integer with the number of messages) –
- Return type:
A numpy array with the conditional distribution characterising a channel
- codec_init(messages)
Return an initial conditional matrix
- Parameters:
messages (an integer with the number of messages) –
- Return type:
A numpy array with the conditional distribution characterising a channel
- gen_lin_constraint(messages)
Generate the LinearConstraint object
- Parameters:
distortions (A list of distortion objectives) –
- Return type:
A LinearConstraint object
- prob_constraint(messages)
Present the constraint that all rows in cond be probability vectors. We use a COO sparse matrix
- Parameters:
messages (an integer with the number of messages) –
- Return type:
A COO sparse matrix with the probability constraint
- class info.OptimizeMessageEntropy(game, dist_measures=None, dist_tensor=None, messages=None, epsilon=0.0001)
A class to calculate rate-distortion (where rate is actually the entropy of messages with a scipy optimizer).
- make_calc_RD()
Return a function that calculates an RD (hyper-)surface using the trust-constr scipy optimizer, for a given list of distortion objectives.
- Return type:
A function that calculates the RD surface for a given list of distortions
- minimize_distortion(matrix)
Return a function that finds an encoder-decoder pair, with the requisite dimension, that minimizes a single distortion objective, using a trust-constr scipy optimizer
- Parameters:
matrix (an integer with the index of the distortion matrix in self.dist_tensor) –
- Return type:
A function that minimizes a distortion objective
- message_entropy(encode_decode)
Calculate message entropy given an encoder-decoder pair, where the two matrices are flattened and then concatenated
- Parameters:
encode_decode (a numpy array with the encoder-decoder pair) –
- Return type:
A float with the message entropy
- reconstruct_enc_dec(encode_decode, reconstruct_decoder=True)
Reconstruct the encoder and decoder matrices from a flattened encoder-decoder pair
- Parameters:
encode_decode (a numpy array with the encoder-decoder pair) –
reconstruct_decoder (whether to reconstruct the decoder matrix) –
- Return type:
The encoder matrix, or a tuple with the encoder and decoder matrices
- enc_dec_init()
Return an initial conditional matrix
- Return type:
A numpy array with the encoder-decoder pair
- gen_nonlin_constraint(distortions)
Generate a list of NonLinearConstraint objects
- Parameters:
distortions (A list of distortion objectives) –
- Return type:
A list of NonLinearConstraint objects
- gen_lin_constraint()
Generate the LinearConstraint object
- Return type:
A LinearConstraint object
- gen_dist_func(matrix)
Return the function that goes into the NonLinearConstraint objects
- Parameters:
matrix (an integer with the index of the distortion matrix in self.dist_tensor) –
- Return type:
A function that calculates the distortion
- prob_constraint()
Present the constraint that all rows in encoder and decoder be probability vectors
- Return type:
A numpy array with the probability constraint
- class info.Shea(game)
Calculate functional content vectors as presented in Shea, Godfrey-Smith andand Cao 2017.
- baseline_payoffs()
Give a vector with the payoffs for sender, and another for receiver, when the receiver does the best possible act for it in the absence of any communication. I will choose, for now, the receiver act that gives the best possible sender payoff (this is not decided by Shea et al.; see fn.14)
- Return type:
A tuple with the sender and receiver payoffs
- expected_for_act(act)
Calculate the expected payoff for sender and receiver of doing one act, in the absence of communication
- Parameters:
act (an integer with the act) –
- Return type:
A tuple with the expected payoffs for sender and receiver
- normal_payoffs()
Calculate payoffs minus the baseline
- Return type:
A tuple with the normalised sender and receiver payoffs
- calc_dmin()
Calculate dmin as defined in Shea et al. (2917, p. 24)
- Return type:
A float with the dmin
- calc_summation(norm_payoff, receiver_strat)
Calculate the summation in the entries of the functional content vector
- Parameters:
norm_payoff (a numpy array with the normalised payoffs) –
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the summation
- calc_entries(sender_strat, receiver_strat, payoff_matrix)
Calculate the entries of the functional vector, given one choice for the (baselined) payoff matrix
- Parameters:
sender_strat (a numpy array with the sender strategy) –
receiver_strat (a numpy array with the receiver strategy) –
payoff_matrix (a numpy array with the payoff matrix) –
- Return type:
A numpy array with the entries of the functional vector
- calc_entries_dmin(sender_strat, receiver_strat)
Calculate the entries of the functional vector, given one choice for the official dmin
- Parameters:
sender_strat (a numpy array with the sender strategy) –
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the entries of the functional vector
- calc_entries_sender(sender_strat, receiver_strat)
Calculate the entries of the functional vector, for the baselined sender
- Parameters:
sender_strat (a numpy array with the sender strategy) –
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the entries of the functional vector
- calc_entries_receiver(sender_strat, receiver_strat)
Calculate the entries of the functional vector, for the baselined receiver
- Parameters:
sender_strat (a numpy array with the sender strategy) –
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the entries of the functional vector
- calc_condition(receiver_strat, payoff_matrix, baseline)
Calculate the condition for nonzero vector entries
- Parameters:
receiver_strat (a numpy array with the receiver strategy) –
payoff_matrix (a numpy array with the payoff matrix) –
baseline (a float with the baseline payoff) –
- Return type:
A numpy array with the condition for nonzero vector entries
- calc_condition_sender(receiver_strat)
Calculate condition() for the sender payoff matrix and baseline
- Parameters:
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the condition for nonzero vector entries
- calc_condition_receiver(receiver_strat)
Calculate condition() for the receiver payoff matrix and baseline
- Parameters:
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the condition for nonzero vector entries
- calc_condition_common(receiver_strat)
Calculate the condition for a nonzero functional vector entry in the definition in (op. cit., p. 24)
- Parameters:
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the condition for nonzero vector entries
- functional_content(entries, condition)
Put everything together in a functional vector per message
- Parameters:
entries (a numpy array with the entries of the functional vector) –
condition (a numpy array with the condition for nonzero vector entries) –
- Return type:
A numpy array with the functional vector
- functional_content_sender(sender_strat, receiver_strat)
Calculate the functional content from the perspective of the sender
- Parameters:
sender_strat (a numpy array with the sender strategy) –
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the functional content from the perspective of the sender
- functional_content_receiver(sender_strat, receiver_strat)
Calculate the functional content from the perspective of the receiver
- Parameters:
sender_strat (a numpy array with the sender strategy) –
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the functional content from the perspective of the receiver
- functional_content_dmin(sender_strat, receiver_strat)
Calculate the functional content from the perspective of dmin
- Parameters:
sender_strat (a numpy array with the sender strategy) –
receiver_strat (a numpy array with the receiver strategy) –
- Return type:
A numpy array with the functional content from the perspective of dmin
- info.conditional_entropy(conds, unconds)
Take a matrix of probabilities of the column random variable (r. v.) conditional on the row r.v.; and a vector of unconditional probabilities of the row r. v.. Calculate the conditional entropy of column r. v. on row r. v. That is: Input:
>>> [[P(B1|A1), ...., P(Bn|A1)],..., [P(B1|Am),...,P(Bn|Am)]] >>> [P(A1), ..., P(Am)]
Output:
>>> H(B|A)
- Parameters:
conds (a (m x n) numpy array of conditional probabilities) –
unconds (a (m x 1) numpy array of unconditional probabilities) –
- Return type:
A float with the conditional entropy
- info.mutual_info_from_joint(matrix)
Take a matrix of joint probabilities and calculate the mutual information between the row and column random variables
- Parameters:
matrix (a (m x n) numpy array of joint probabilities) –
- Return type:
A float with the mutual information
- info.unconditional_probabilities(unconditional_input, strategy)
Calculate the unconditional probability of messages for sender, or signals for receiver, given the unconditional probability of states (for sender) or of messages (for receiver)
- Parameters:
unconditional_input (a numpy array with the unconditional probabilities) –
strategy (a numpy array with the conditional probabilities) –
- Returns:
A numpy array with the unconditional probabilities of messages (for sender)
or signals (for receiver)
- info.normalize_axis(array, axis)
Normalize a matrix along <axis>, being sensible with all-zero rows
- Parameters:
array (a numpy array) –
axis (an integer with the axis along which to normalize) –
- Return type:
A numpy array with the normalized matrix
- info.from_joint_to_conditional(array)
Convert a joint probability matrix to a conditional probability matrix along the row random variable
- Parameters:
array (a numpy array) –
- Return type:
A numpy array with the conditional probabilities
- info.from_conditional_to_joint(unconds, conds)
Take a matrix of conditional probabilities of the column random variable on the row r. v., and a vector of unconditional probabilities of the row r. v. and output a matrix of joint probabilities.
Input: >>> [[P(B1|A1), …., P(Bn|A1)],…, [P(B1|Am),…,P(Bn|Am)]] >>> [P(A1), …, P(Am)] Output: >>> [[P(B1,A1), …., P(Bn,A1)],…, [P(B1,Am),…,P(Bn,Am)]]
- Parameters:
unconds (a (m x 1) numpy array of unconditional probabilities) –
conds (a (m x n) numpy array of conditional probabilities) –
- Return type:
A (m x n) numpy array of joint probabilities
- info.bayes_theorem(unconds, conds)
Perform Bayes’ theorem on a matrix of conditional probabilities
- Parameters:
unconds (a (n x 1) numpy array of unconditional probabilities [P(A1), ... , P(An)]) –
conds (a (m x n) numpy array of conditional probabilities [[P(B1|A1), ... , P(Bm|A1)], ... , [P(B1|An), ..., P(Bm|An)]]) –
- Return type:
A (n x m) numpy array of conditional probabilities [[P(A1|B1), … , P(An|B1)], … , [P(PA1|Bm), … , P(An|Bm)]]
- info.entropy(vector)
Calculate the entropy of a vector
- Parameters:
vector (a numpy array) –
- Return type:
A float with the entropy in bits
- info.escalar_product_map(matrix, vector)
Take a matrix and a vector and return a matrix consisting of each element of the vector multiplied by the corresponding row of the matrix
- Parameters:
matrix (a numpy array) –
vector (a numpy array) –
- Return type:
A numpy array with the element-wise product of the vector and the matrix
- info.normalize_vector(vector)
Normalize a vector, converting all-zero vectors to uniform ones
- Parameters:
vector (a numpy array) –
- Return type:
A numpy array with the normalized vector
- info.normalize_distortion(matrix)
Normalize linearly so that max corresponds to 0 distortion, and min to 1 distortion It must be a matrix of floats!
- Parameters:
matrix (a numpy array) –
- Return type:
A numpy array with the normalized matrix
Exceptions exceptions.py
Some custom exceptions and errors
- exception exceptions.ChanceNodeError
Error to raise when the user is attempting to do something with a chance node that doesn’t exist
- exception exceptions.NoDataException
Error to raise when the user tries to show a plot but the figure object doesn’t have the required data. Also raised when the user tries to load data from disk that is not found.
- exception exceptions.InconsistentDataException
Error to raise when the user provides data that is inconsistent e.g. payoff matrices that do not have a shape corresponding to the set of states or set of acts.
- exception exceptions.ModuleNotInstalledException
Error to raise when a method requires a module that is not yet installed.