In [27]:
from mesa import Agent, Model
from mesa.datacollection import DataCollector
from mesa.time import SimultaneousActivation
from mesa.space import ContinuousSpace
import numpy as np
import pandas as pd
import random
from AdjacencyGrid import AdjacencyGrid


class LanguageAgent(Agent):
    def __init__(self, model, unique_id, initial_population, initial_prob_v):
        super().__init__(unique_id, model)
        self.population = initial_population
        self.probability = np.array(initial_prob_v)
        self.next_probability = np.array(self.probability, copy=True)
        self.diffusion = self.model.diffusion

    def calculate_contribution(self, other):
        '''
        args:
            other(LanguageAgent): an adjacent or otherwise relevant other LanguageAgent
        '''
        return ((other.population * other.probability) / (4 * np.pi * self.diffusion)) * np.exp(
            -np.square(self.model.grid.get_distance(self.pos, other.pos))) / (4 * self.diffusion)

    def step(self):
        f = np.zeros(len(self.probability))
        for neighbor in self.model.grid.get_neighbors(self.pos, moore=True, include_center=False, radius=1):
            f += self.calculate_contribution(neighbor)

        self.next_probability = ((self.population * self.probability) + f) / (np.sum(f) + self.population)

    def advance(self):
        self.probability, self.next_probability = self.next_probability, self.probability


class LanguageModel(Model):
    def __init__(self, diffusivity, filename):
        super()
        self.num_agents = 0
        #self.grid = ContinuousSpace(1000, 1000, torus=False)
        self.grid = AdjacencyGrid()
        self.schedule = SimultaneousActivation(self)
        self.diffusion = np.array(diffusivity)
        self.pop_data = self.read_file(filename)

        for loc in self.pop_data.loc[:]['location_id']:
                #print('id: ' + str(idx))
                self.num_agents += 1
                # Create agents, add them to scheduler
                a = LanguageAgent(self, loc, 1000 + 500 * random.random(), [random.random(), random.random()])
                self.schedule.add(a)

                # add the agent at position (x,y)
                #print('lat: ' + str(self.pop_data.loc[idx]['latitude']))
                #print('long ' + str(self.pop_data.loc[idx]['longitude']))
                self.grid.place_agent(a, (float(self.pop_data.loc[a.unique_id - 1]['latitude']), float(self.pop_data.loc[a.unique_id - 1]['longitude'])))
                #print('added')

        self.grid.find_neighbors()

        self.datacollector = DataCollector(
            model_reporters={},
            agent_reporters={"diff": lambda x: x.next_probability - x.probability})

    def read_file(self, filename):
        data = pd.read_csv(filename)
        return data.dropna()


    def step(self):
        '''Advance the model by one step.'''
        self.datacollector.collect(self)
        self.schedule.step()

    def run(self, timesteps):
        for t in range(timesteps):
            self.step()
            print('Model Step: ' + str(t+1))

In [28]:
import matplotlib.pyplot as plt

model = LanguageModel([.5, .5], 'speakers.csv')

print("diffusivities: " + str(model.diffusion))


diffusivities: [ 0.5  0.5]

In [31]:
model.datacollector.get_agent_vars_dataframe()


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-31-1b5020d8255d> in <module>()
----> 1 model.datacollector.get_agent_vars_dataframe()

/home/pawlactb/Dropbox/language/lib/python3.5/site-packages/mesa/datacollection.py in get_agent_vars_dataframe(self)
    189                     data[(step, agent_id)][var] = val
    190         df = pd.DataFrame.from_dict(data, orient="index")
--> 191         df.index.names = ["Step", "AgentID"]
    192         return df
    193 

/home/pawlactb/Dropbox/language/lib/python3.5/site-packages/pandas/core/indexes/base.py in _set_names(self, values, level)
   1059         if len(values) != 1:
   1060             raise ValueError('Length of new names must be 1, got %d' %
-> 1061                              len(values))
   1062         self.name = values[0]
   1063 

ValueError: Length of new names must be 1, got 2

In [ ]: