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.

property properties

Get a dict of all the editable properties of the figure, with their current values.

Typically includes properties like plot color, axis labels, plot scale etc.

Returns:

list_of_properties – A list of the editable properties of the object.

Return type:

list

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.

Parameters:

line (bool, optional) – Whether to show a line connecting the datapoints. The default is False.

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)

Reset parameters for the figure.

This is an abstract method that must be redefined for each subclass.

Return type:

None.

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(x, y)
Parameters:
  • x (float) – Current proportion of the first sender strategy.

  • y (float) – Current proportion of the first receiver strategy.

  • Returns

  • strategy. (velocity of SECOND receiver) –

  • strategy.

class figure.Quiver3D(color='k', normalize=True, length=0.5, arrow_length_ratio=0.5, pivot='middle', **kwargs)

Plot a 3D quiver plot.

reset()

Reset parameters for the figure.

This is an abstract method that must be redefined for each subclass.

Return type:

None.

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 (TYPE) – DESCRIPTION.

Returns:

barycentric_location – DESCRIPTION.

Return type:

TYPE

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.

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)

Reset parameters for the figure.

This is an abstract method that must be redefined for each subclass.

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.

  • 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.

show() None

Show figure with current parameters.

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

avg_payoff(player)

Return the average payoff that players get when the population vector is <player>

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 (TYPE) – DESCRIPTION.

Return type:

None.

replicator_dX_dt_odeint(X, t)

Calculate the rhs of the system of odes for scipy.integrate.odeint

replicator_jacobian_odeint(X, t=0)

Calculate the Jacobian of the system of odes for scipy.integrate.odeint

discrete_replicator_delta_X(X)

Calculate a population vector for t’ given the vector for t, using the discrete time replicator dynamics (Huttegger 2007)

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

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.

pop_to_mixed_strat(pop)

Take a population vector and output the average strat implemented by the whole population

assortment(e)

Set assortment level

Parameters:

e (TYPE) – DESCRIPTION.

Return type:

None.

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

random_receiver()

Return frequencies of a random receiver population

sender_avg_payoff(sender, receiver)

Return the average payoff that senders get when the population vectors are <sender> and <receiver>

receiver_avg_payoff(receiver, sender)

Return the average payoff that receivers get when the population vectors are <sender> and <receiver>

replicator_dX_dt_odeint(X, t)

Calculate the rhs of the system of odes for scipy.integrate.odeint

replicator_dX_dt_ode(t, X)

Calculate the rhs of the system of odes for scipy.integrate.ode

replicator_jacobian_odeint(X, t=0)

Calculate the Jacobian of the system for scipy.integrate.odeint

replicator_jacobian_ode(t, X)

Calculate the Jacobian of the system for scipy.integrate.ode

discrete_replicator_delta_X(X)

Calculate a population vector for t’ given the vector for t, using the discrete time replicator dynamics (Huttegger 2007)

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

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

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.

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.

sender_to_mixed_strat(senderpop)

Take a sender population vector and output the average sender strat implemented by the whole population

receiver_to_mixed_strat(receiverpop)

Take a receiver population vector and output the average receiver strat implemented by the whole population

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.

Parameters:
  • iterations (int) – Number of times to call self.step().

  • hide_progress (bool) – Whether to display tqdm progress bar

  • calculate_stats (str) – When to calculate stats “step”: every step “end”: only at the last step

Return type:

None.

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.

Parameters:

epsilon (float) – How close to the maximum possible mutual information must the current mutual information be in order to count as a signalling system?

Returns:

pooling – True if the current strategies constitute a pooling equilibrium.

Return type:

bool

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:
  1. Run one round of the game.

  2. Update the agents’ strategies based on the payoffs they received.

  3. Calculate and store any required variables e.g. information.

  4. Update iteration.

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:
  1. Run one round of the game.

  2. Update the agents’ strategies based on the payoffs they received.

  3. Calculate and store any required variables e.g. information.

  4. Update iteration.

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:
  1. Run one round of the game.

  2. Update the agents’ strategies based on the payoffs they received.

  3. Calculate and store any required variables e.g. probability of success.

  4. Update iteration.

Return type:

None.

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:
  1. Run one round of the game.

  2. Update the agents’ strategies based on the payoffs they received.

  3. Calculate and store any required variables e.g. information.

  4. Update iteration.

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.

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>.

Parameters:
  • input_data (TYPE) – DESCRIPTION.

  • response (TYPE) – DESCRIPTION.

  • payoff (TYPE) – DESCRIPTION.

Return type:

None.

update_strategies_bush_mosteller(input_data, response, payoff, learning_parameter)

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 (TYPE) – DESCRIPTION.

  • response (TYPE) – DESCRIPTION.

  • payoff (TYPE) – DESCRIPTION.

  • learning_parameter (TYPE) – DESCRIPTION.

Return type:

None.

add_signal_sender()

TODO: consolidate with add_signal_receiver(), and tell the agent who it is

Return type:

None.

add_signal_receiver()

TODO: consolidate with add_signal_sender(), and tell the agent who it is

Return type:

None.

class evolve.Times(initial_time, final_time, time_inc)

Provides a way of having a single time input to both odeint and ode

evolve.mutationmatrix(mutation, dimension)

Calculate a (square) mutation matrix with mutation rate given by <mutation> and dimension given by <dimension>

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 player

  • NonChance: 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

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

receiver_pure_strats()

Return the set of pure strategies available to the receiver

one_pop_pure_strats()

Return the set of pure strategies available to players in a one-population setup

payoff(sender_strat, receiver_strat)

Calculate the average payoff for sender and receiver given concrete sender and receiver strats

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>

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?

Parameters:

sigfig (int, optional) – The number of significant figures to report values in. Since gambit sometimes has problems rounding, it generates values like 0.9999999999996. We want to report these as 1.0000, especially if we’re dumping to a file. The default is 5.

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:

bool

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.

Parameters:

sigfig (int, optional) – The number of significant figures to report values in. Since gambit sometimes has problems rounding, it generates values like 0.9999999999996. We want to report these as 1.0000, especially if we’re dumping to a file. The default is 5.

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:

tuple

property max_mutual_info

Maximum possible mutual information between states and acts. Depends on self.state_chances.

Lazy instantiation

Returns:

_max_mutual_info – The maximum mutual information between states and acts for this game.

Return type:

float

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:

int

payoff_sender(state, act)

Get the sender’s payoff when this combination of state and act occurs.

Parameters:
  • state (TYPE) – DESCRIPTION.

  • act (TYPE) – DESCRIPTION.

Returns:

payoff – DESCRIPTION.

Return type:

TYPE

payoff_intermediary(state, act)

Get the intermediary’s payoff when this combination of state and act occurs.

Parameters:
  • state (TYPE) – DESCRIPTION.

  • act (TYPE) – DESCRIPTION.

Returns:

payoff – DESCRIPTION.

Return type:

TYPE

payoff_receiver(state, act)

Get the receiver’s payoff when this combination of state and act occurs.

Parameters:
  • state (TYPE) – DESCRIPTION.

  • act (TYPE) – DESCRIPTION.

Returns:

payoff – DESCRIPTION.

Return type:

TYPE

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:

float

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.

receiver_pure_strats()

Return the set of pure strategies available to the receiver

payoff(sender_strat, receiver_strat)

Calculate the average payoff for sender and receiver given concrete sender and receiver strats

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>

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

payoff(first_player, second_player)

Calculate the average payoff for first and second given concrete strats

avg_payoffs(player_strats)

Return an array with the average payoff of strat i against strat j in position <i, j>

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)

calculate.one_basin_discrete_aux(triple)

Calculate the one_basin loop using replicator_discrete

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)

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

calculate.one_basin_ode_aux(triple)

Calculate the one_basin loop using one_run_ode

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

calculate.test_endstate(array)

Test if <array> is composed by two concatenated probability vectors

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

sender_K()

Calculate K for the sender

receiver_K()

Calculate K for the receiver

C_chance()

Calculate C as defined in Godfrey-Smith and Martinez (2013) – but using scipy.stats.kendalltau

C_nonchance()

Calculate the C for non-chance games (using the total KTD)

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

sender_K()

Calculate K for the sender

receiver_K()

Calculate K for the receiver

C_chance()

Calculate C as defined in Godfrey-Smith and Martinez (2013) – but using scipy.stats.kendalltau

C_nonchance()

Calculate the C for non-chance games (using the total KTD)

common_interest.C(vector1, vector2)

Calculate C for two vectors

common_interest.tau(vector1, vector2)

Calculate the Kendall tau statistic among two vectors

common_interest.intra_tau(unconds, array)

Calculate the average (weighted by <unconds> of the pairwise Kendall’s tau distance between rows (states) of <array>

common_interest.total_tau(array1, array2)

Calculate the KTD between the flattened <array1> and <array2>. Useful for NonChance games

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>

class common_interest.Nash(game)

Calculate Nash equilibria

is_Nash(sender, receiver)

Find out if sender and receiver are a Nash eqb

common_interest.stability(array)

Compute a coarse grained measure of the stability of the array

common_interest.stable_vector(vector)

Return true if the vector does not move

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

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

mutual_info_states_acts()

Calculate the mutual info between states and acts

mutual_info_states_messages()

Calculate the mutual info between states and messages

mutual_info_messages_acts()

Calculate the mutual info 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

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

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)

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

calc_rate(cond, output)

Calculate the rate for a channel (given by <cond>) and output distribution (given by <output>)

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.

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.

rate(cond_flat)

Calculate rate for make_calc_RD()

cond_init()

Return an initial conditional matrix

gen_lin_constraint(distortions)

Generate the LinearConstraint object

Parameters:

distortions (A list of distortion objectives) –

lin_constraint()

Collate all constraints

dist_constraint()

Present the distortion constraint (which is linear) the way scipy.optimize expects it

prob_constraint()

Present the constraint that all rows in cond be probability vectors. We use a COO sparse matrix

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.

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

codec_init_random(messages)

Return an initial conditional matrix

codec_init(messages)

Return an initial conditional matrix

gen_lin_constraint(messages)

Generate the LinearConstraint object

Parameters:

distortions (A list of distortion objectives) –

prob_constraint(messages)

Present the constraint that all rows in cond be probability vectors. We use a COO sparse matrix

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.

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

message_entropy(encode_decode)

Calculate message entropy given an encoder-decoder pair, where the two matrices are flattened and then concatenated

enc_dec_init()

Return an initial conditional matrix

gen_nonlin_constraint(distortions)

Generate a list of NonLinearConstraint objects

Parameters:

distortions (A list of distortion objectives) –

gen_lin_constraint()

Generate the LinearConstraint object

Parameters:

distortions (A list of probability objectives) –

gen_dist_func(matrix)

Return the function that goes into the NonLinearConstraint objects

prob_constraint()

Present the constraint that all rows in encoder and decoder be probability vectors

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)

expected_for_act(act)

Calculate the expected payoff for sender and receiver of doing one act, in the absence of communication

normal_payoffs()

Calculate payoffs minus the baseline

calc_dmin()

Calculate dmin as defined in Shea et al. (2917, p. 24)

calc_summation(norm_payoff, receiver_strat)

Calculate the summation in the entries of the functional content vector

calc_entries(sender_strat, receiver_strat, payoff_matrix)

Calculate the entries of the functional vector, given one choice for the (baselined) payoff matrix

calc_entries_dmin(sender_strat, receiver_strat)

Calculate the entries of the functional vector, given one choice for the official dmin

calc_entries_sender(sender_strat, receiver_strat)

Calculate the entries of the functional vector, for the baselined sender

calc_entries_receiver(sender_strat, receiver_strat)

Calculate the entries of the functional vector, for the baselined receiver

calc_condition(receiver_strat, payoff_matrix, baseline)

Calculate the condition for nonzero vector entries

calc_condition_sender(receiver_strat)

Calculate condition() for the sender payoff matrix and baseline

calc_condition_receiver(receiver_strat)

Calculate condition() for the receiver payoff matrix and baseline

calc_condition_common(receiver_strat)

Calculate the condition for a nonzero functional vector entry in the definition in (op. cit., p. 24)

functional_content(entries, condition)

Put everything together in a functional vector per message

functional_content_sender(sender_strat, receiver_strat)

Calculate 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

functional_content_dmin(sender_strat, receiver_strat)

Calculate 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)
info.mutual_info_from_joint(matrix)

Take a matrix of joint probabilities and calculate the mutual information between the row and column random variables

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)

info.normalize_axis(array, axis)

Normalize a matrix along <axis>, being sensible with all-zero rows

info.from_joint_to_conditional(array)

Normalize row-wise

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)]]

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

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

info.normalize_vector(vector)

Normalize a vector, converting all-zero vectors to uniform ones

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!

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.