abm package

Submodules

abm.analysis

Some functions for training/analyzing networks

abm.analysis.get_attrs(pop, ix)[source]

Get features from node ix in pop.

Parameters:
  • pop – an Environment
  • ix – a node label
Returns:

key-value pairs of the node’s features

Return type:

dict

Example:
>>> from abm import analysis, nxpops, io
>>> cfg = io.ConfigReader('../setup.json').get_config()
>>> pop = nxpops.SoftmaxNxEnvironment(**cfg)
>>> analysis.get_attrs(pop, 3)
{u'color': u'blue', u'region': u'east'}

Note

the keys in the returned dict are read from pop.attributes

See also

get_dyad_data()

Warning

ix must be a valid node index

abm.analysis.get_dyad_data(env, dyads)[source]

Create a dictionary of per-dyad information used in performance monitoring

abm.analysis.get_dyads(env, target_len=1000)[source]
abm.analysis.get_env_likelihood_samples(env, as_df=True, n_tasks=36000, sample_each=400, n_dyads=1000)[source]
abm.analysis.get_shortest_path_likelihood(env, start, end, paths=None)[source]

Return the probability of following any the shortest-length paths from start to end

abm.analysis.learnt_over_shortest_path_len(env, start, end, shortest_len=None)[source]

Return the ratio of learnt likeliest path to shortest path len

abm.analysis.path_likelihood_with_dyad_traits(env, dyads, dyad_data)[source]
abm.analysis.plot_learning_df(df, key='li', **kwargs)[source]
abm.analysis.plot_segment_stats(segments, segment_keys=['full_mismatch', 'full_match', 'some_mismatch'], colors=['red', 'blue', 'green'], measure_key='li')[source]
abm.analysis.segment_learning_df(df, prefixes=['start_', 'end_'])[source]

Separates dyad learning stats df based on whether dyad members have matching / nonmatching / partially matching attributes :param prefixes: specify the column prefixes for dyad attributes returns {segment_name: dataframe slice}

abm.entities

Individual objects from agent world

class abm.entities.DunceNode(environment, index, **kwargs)[source]

Bases: abm.learners.DunceMixin, abm.entities.NxEntity

Nx compatible node that doesn’t learn and just randomly draws its recipients

class abm.entities.Entity(environment, index)[source]

Bases: object

An entity in our world

award(value)[source]

Accepts <value> as award to register the outcome of recent decision(s). Calls self._learn() and then cleans up to prepare for the next message.

log(msg)[source]
next(task, sender)[source]

Called by environment to get the next step in the path

class abm.entities.NxEntity(environment, index, **kwargs)[source]

Bases: abm.entities.Entity

An entity that can be a Nx graph node It can have more freeform attributes and doesn’t need x, y positions for viz

adjacencies

List connected nodes via the parent graph

update(kwargs)[source]
class abm.entities.SoftmaxNode(environment, index, **kwargs)[source]

Bases: abm.learners.SoftmaxLearnerMixin, abm.entities.NxEntity

Nx nodes with softmax learning

class abm.entities.Task(target, features=None)[source]

Bases: object

Represents a message to be routed.

class abm.entities.XyDunceNode(environment, index, x, y, cluster)[source]

Bases: abm.learners.DunceMixin, abm.entities.XyEntity

Xy compatible node that doesn’t learn and just randomly draws its recipients

class abm.entities.XyEntity(environment, index, x, y, cluster)[source]

Bases: abm.entities.Entity

An entity in x-y world

set_adjacencies(adjacencies)[source]

Builds the adjacency list for this Entity. :param adjacencies: set of integers referencing other entities in self.population

abm.generators

Objects for distributing node attributes and edges

class abm.generators.AttributeGenerator(attributes, scale)[source]

Bases: object

get_value(attribute)[source]
class abm.generators.EdgeGenerator(attributes, edge_probs, density)[source]

Bases: object

set_edge(node1, node2)[source]
abm.generators.random() → x in the interval [0, 1).

abm.io

Reading and writing network configuration files, through ConfigReader.

class abm.io.ConfigReader(filename)[source]

Bases: object

Interface to reading network settings from a file.

Read a json configuration file, filename, and validate and augment settings for use in network generation. The final settings are stored in self.config.

abm configuration files are used for determining the properties of a network, based on which the network is randomly created.

Example:

A typical configuration file looks like this:

{
  "attributes": {
    "color": {
      "blue": 40,
      "green": 25,
      "red": 35
    },
    "region": {
      "west": 45,
      "east": 50
    }
  },
  "size": 100,
  "entity_kwargs":{
    "policy_duration": 1
  },
  "edge_probs": {
    "color": {
      "blue": 0.2,
      "diff": 0.1,
      "green": 0.25,
      "red": 0.15
    },
    "region": {
      "west": 0.2,
      "east": 0.2,
      "diff": 0.08
    }
  },
  "density": 0.1
}

This defines a network with 100 nodes (size) and desired edge density of 0.1 (density).

The keys of the attributes dict are used as features to define each node’s identity, and the values are the desired proportion of nodes that will have this feature, normalaized to 100. This configuration file defines a network in which 40% of the nodes are of color blue.

The keys of the edge_probs dict are the same features as before, but now the values are the probabilities with which an edge joining two nodes with the same value in this feature will be connected. There is also a probability for forming an edge between nodes with different values for this attribute. In the above example, the network will be built so that two nodes with the value ‘blue’ for the attribute color will be joined with 0.2 probability, while two nodes with different color values will be joined with 0.1 probability, coming from the value for diff.

Note

Neither the total of the values in attributes has to add up to 100, nor the total of the probabilities in edge_probs has to add up to 1.0. If they don’t, ConfigReader fills in the missing data.

get_config()[source]

abm.learners

Learning mixins to add to entity subclasses Should implement _get_next_recipient and _learn

class abm.learners.DunceMixin[source]

Bases: object

A learner that doesn’t learn

class abm.learners.SoftmaxLearnerMixin[source]

Bases: object

flush_updates()[source]
last_recipient = None
policy_duration = 1
update_buffer = None
w_container = None

abm.nxpops

Network-x backed populations

class abm.nxpops.NxEnvironment(attributes, edge_probs, size=100, density=0.1, path_cutoff=20, entity_class=<class 'abm.entities.NxEntity'>, edge_gen_class=<class 'abm.generators.EdgeGenerator'>, attr_gen_class=<class 'abm.generators.AttributeGenerator'>, entity_kwargs={}, debug=True)[source]

Bases: abm.pops.Environment

A network graph (with NetworkX)

describe()[source]

Provide summary statistics about the generated graph Logs (prints; todo: use logger) a human readable string

display(current=None, target=None)[source]
class abm.nxpops.PathTreeMixin[source]

Bases: object

Track the message traversals in a nx graph datastructure Give awards based on direct distance from element to target

gamma = 0.91
class abm.nxpops.SoftmaxNxEnvironment(attributes, edge_probs, size=100, density=0.1, entity_class=<class 'abm.entities.SoftmaxNode'>, edge_gen_class=<class 'abm.generators.EdgeGenerator'>, node_index_indicator=False, bias=False, path_cutoff=20, policy_duration=1, attr_gen_class=<class 'abm.generators.AttributeGenerator'>, entity_kwargs={}, debug=True)[source]

Bases: abm.pops.TaskFeatureMixin, abm.nxpops.NxEnvironment

A NetworkX environment where tasks have categorical feature vectors and nodes use that vector to select the appropriate neighbor

flush_updates()[source]

Checks for flushing condition, and tells entities to flush if necessary

class abm.nxpops.SoftmaxNxPathTreeEnvironment(attributes, edge_probs, size=100, density=0.1, entity_class=<class 'abm.entities.SoftmaxNode'>, edge_gen_class=<class 'abm.generators.EdgeGenerator'>, node_index_indicator=False, bias=False, path_cutoff=20, policy_duration=1, attr_gen_class=<class 'abm.generators.AttributeGenerator'>, entity_kwargs={}, debug=True)[source]

Bases: abm.nxpops.PathTreeMixin, abm.nxpops.SoftmaxNxEnvironment

A NetworkX environment where tasks have categorical feature vectors and nodes use that vector to select the appropriate neighbor

Track the message traversals in a nx graph datastructure Give awards based on direct distance from element to target

abm.pops

Environments of interconnected agents

class abm.pops.Environment(debug=True, path_cutoff=20)[source]

Bases: object

clear()[source]

Clear every Entity’s history. Called when the package is stuck in a cycle.

initiate_task(fixed_pair=None)[source]

Initializes a task, and calls pass_message().

log(msg)[source]

Prints a message to stdout, only if self.debug=True.

class abm.pops.TaskFeatureMixin[source]

Bases: object

Overrides _generate_task with a feature-defining version

bias = False
node_index_indicator = False

abm.viz

Displaying agent population

abm.viz.construct_network(pts, connectivity_matrix, current=None, target=None)[source]
abm.viz.display_network(pts, connectivity_matrix, current=None, target=None)[source]

abm.xypops

Environments not backed by networkx whose x, y traits are used in visualization

class abm.xypops.CappedPreferentialEnvironment(alpha=0.8, beta=0.4, *args, **kwargs)[source]

Bases: abm.xypops.XyEnvironment

A set of connected Entities. Handles message passing and displaying. Connections are laid out such that entities of the same cluster are more likely to be tied together, proportionally to a parameter alpha. The overall density of the network is controlled by a parameter beta.

class abm.xypops.NearestNeighborsEnvironment(y_pos_dist=<scipy.stats._distn_infrastructure.rv_frozen object>, cluster_x_dists={'A': <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f4e08e57410>, 'C': <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f4e08e57810>, 'B': <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f4e08e57610>}, cluster_sizes={'A': 8, 'C': 8, 'B': 10}, single_component=True, entity_class=<class 'abm.entities.XyEntity'>, **kwargs)[source]

Bases: abm.xypops.XyEnvironment

A set of connected Entities. Handles message passing and displaying. Connections laid out geographically: each point is connected to some of its nearest neighbors.

class abm.xypops.XyEnvironment(y_pos_dist=<scipy.stats._distn_infrastructure.rv_frozen object>, cluster_x_dists={'A': <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f4e08e57410>, 'C': <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f4e08e57810>, 'B': <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f4e08e57610>}, cluster_sizes={'A': 8, 'C': 8, 'B': 10}, single_component=True, entity_class=<class 'abm.entities.XyEntity'>, **kwargs)[source]

Bases: abm.pops.Environment

A set of connected Entities. Handles message passing and displaying. Entities are connected randomly.

display(current=None, target=None)[source]

Plots the state of the task. If <show> = False, doesn’t plot anything and the simulation can run faster.

abm.xypops.make_points(cluster, size, y_dist, x_dist)[source]

Creates a set of points using y_dist and x_dist to draw the location.

Module contents