Commit 3f8f2569 authored by Amit Goldenberg's avatar Amit Goldenberg

Some error fixing and making sure that the averages are being kept constantly.

The next thing that should be added to the model is the fact that the chance for the bump decreases in time.

This would allow us to predict situations better.
parent d2603401
......@@ -7,19 +7,18 @@ import matplotlib.animation as animation
from ComplexNetworkSim import NetworkAgent, Sim
# all the packages
class ColEmo(NetworkAgent):
def __init__(self, state, initialiser):
NetworkAgent.__init__(self, state, initialiser)
self.preference = np.random.normal(0,self.globalSharedParameters['preference']) #this is the defree of preference (regulation) each participants has.
self.gamma = self.globalSharedParameters['gamma'] # the decay term.
#fixed variables (for now)
self.event = 0.5 #self.globalSharedParameters['event'] # rate of experience
self.bump = 1#globalSharedParameters['bump']
self.event = 0.9 #self.globalSharedParameters['event'] # rate of experience
self.bump = 2#globalSharedParameters['bump']
self.noise = 0.02 # noise term
self.conform = truncnorm.rvs(0.2,0.6) # this is the degree of conformity each participant has.
self.thresh = np.random.normal(4,0.5)
#print "thresh %s" %self.thresh
# define selfstatevector to be similar to state (for the animation)
self.stateVector = self.state # each participant in this package recieves a variable (state)
# get local_avg action once to economize on computation
......@@ -28,6 +27,11 @@ class ColEmo(NetworkAgent):
while True:
self.set_local_avg()
influence = (self.state-self.local_avg)*self.conform # certain conform ratio
if influence >0:
influence = influence
else:
influence = 0
#print "influence %s" %influence
emotion = (self.state*self.gamma) - influence + self.preference # the individual emotion
# this part forms the emotional bump that a participant recieves using the experience ratio.
if self.flip() == "bump": # if the flip condition fit the bump - than we need to bump.
......@@ -40,21 +44,31 @@ class ColEmo(NetworkAgent):
# a certain threshold - the average of nb is taken of all the numbers that does not include None
if self.state > self.thresh:
self.stateVector = self.state
#print "stateVector %s" %self.stateVector
#print "state %s" %self.state
else:
self.stateVector = None
#print "stateVector %s" %self.stateVector
#print "state %s" %self.state
yield Sim.hold, self, NetworkAgent.TIMESTEP_DEFAULT # This yield function defines how long each agent waits.
def set_local_avg(self):
nbrs = self.getNeighbouringAgentsIter()
# TODO edge weights (here is just using unweighted)
a = [nb.stateVector for nb in nbrs]
#print "neighbor %s" %a
self.local_avg = np.mean(filter(None, a)) # create a filter the removes nones from average.
#print "average %s" %self.local_avg
"""
nbrs = self.getNeighbouringAgentsIter()
try:
a = [nb.stateVector for nb in nbrs]
print a
self.local_avg = np.mean(filter(None, a)) # create a filter the removes nones from average.
print self.local_avg
print "average %s" %self.local_avg
print "neighbor %s" %a
except RuntimeWarning:
self.local_avg = self.stateVector
"""
def flip(self):
......
""" simluation of the agents
- we define network structure here as well
"""
#test
# NOTE: this uses sequential dynamics -- agents act in turn, not simultaneously
from __future__ import division, print_function
import numpy as np
import matplotlib
import networkx as nx
import pandas as pd
from time import time
import matplotlib.animation as animation
from script_ABM_collective_emotion import ColEmo
from ComplexNetworkSim import NetworkSimulation, utils, PlotCreator
#get_ipython().magic(u'matplotlib inline')
"""network"""
nodes = 30 # the amount of nodes for the graph.
#typologt
#G = nx.gnm_random_graph (nodes,nodes*2.5) # the type of network we are building.
G=nx.complete_graph(nodes) # complete network
#G = nx.gnm_random_graph (nodes,nodes*2.5)
#G = nx.barbell_graph (nodes,0) # the graph is connected by just one person.
#G = [complete,randomg] # we can create a list of networks and activate it.
nx.draw_networkx(G) # draw the network
""" parameter combination """
#event_set = [0.1,0,2] # the rate of emotion eliciting events (the change that an agent will experience)
preference_set = [0.5 ]
gamma_set = [0.90, 0.95]
#bump_set = [2]
param_combos = [ {'preference':preference, 'gamma':gamma}
for preference in preference_set for gamma in gamma_set]
"""simulation routine"""
MAX_SIMULATION_TIME = 100 # the amounts of simulations
TRIALS = 1 # how many repititions is the system doing
mean_total = []#pd.DataFrame(range(MAX_SIMULATION_TIME))
sim_name = 'wide'
states = [ np.random.normal(3,1) for n in G.nodes()] # initiation state of all agenges
states[0] = np.random.normal(3,1) # infecting partcipiant 0
states[0] = sorted([1, states[0], 8])[1] # define an upper limit.
def main(): # we are defining a function that activates the sumulation.
directory = 'test' #output directory
# run simulation with parameters
# - complex network structure
# - initial state list
# - agent behaviour class
# - output directory
# - maximum simulation time
# - number of trials
#use this is you are using the infection ration that you built in the main code
for global_params in param_combos:
t = time()
directory =(
'results/'
'{gamma}--{preference}'.format(
preference = global_params['preference'],
gamma = global_params['gamma'])
)
simulation = NetworkSimulation(G,states,ColEmo,directory,MAX_SIMULATION_TIME,TRIALS,**global_params)
simulation.runSimulation()
"""
plotting
1. Single graphe (trial 0).
2. average and std of all trials.
"""
# assuming that you have multiple trials - this code will consolidate all the trails data sets
data = []
for j in range(TRIALS): # for all j (wich are all the trials).
from ComplexNetworkSim import utils
contents = utils.retrieve('%s/log_trial_%d_states.pickled' % (directory,j) ) # get the pickeled data
# you can change the name of the data set.
ra = [] # form and empty list in which this data will look
for i in contents: # we need to manipulate the list because it has the number of each person in it
y = (i[1]) # each list comes as [1,[content]] so we need to remove the first part.
ra.append (y) # once we are done we have ra which is a list of lists of the first trial
data.append (pd.DataFrame (np.array (ra)))
plot_state =data[0].plot (title="collective emotion- single trial %s" % (directory), legend = None, ylim = (1,8))
plot_state.set_xlabel("time")
plot_state.set_ylabel("intensity")
# save the picture
fig = plot_state.get_figure()
fig.savefig('%s.png' %(directory))
"""average and std """
# create a data fram that I could use to capture all the data.
data_t=sum (data)/len(data) # we are adding all the data sets to each other.
m=[]
std =[]
m.append(data_t.mean(1)) # take the mean of every time (every row).
std.append(data_t.std(1)) # take the sd of every time (every row).
m = pd.DataFrame(np.array(m)) # transform into a dataset
#m = m.T # transport - for the graph
#m.columns =['n=10', 'n=50' , 'n=100']
mean_total.append (m)
std = pd.DataFrame (np.array (std)) # transform into a data set.
std = std.fillna(value=0) # fill the nas with 0
std = std.T
#std.columns = ['n=10
""""
# this can be the plot of each of the averages. I don't need it.
plot_m =m.plot (title="mean collective emotion - average of trials %s" % (directory), legend = None, ylim = (1,8))
plot_m.set_xlabel("time")
plot_m.set_ylabel("collective emotion")
fig = plot_m.get_figure()
fig.savefig('%s.png' %(directory))
plot_std =std.plot (title="std collective emotion %s" % directory)
plot_std.set_xlabel("time")
plot_std.set_ylabel("collective emotion")
fig = plot_std.get_figure()
fig.savefig('%s.png' %(directory))
"""
# run main
if __name__ == '__main__':
main()
""" in this part I print mean total which is the list of all the means"""
mean_total = np.vstack(mean_total) # stack them. I could not combine the arrays for some reason.
mean_total = pd.DataFrame(np.array(mean_total)) # transform into dataset
mean_total = mean_total.T # transform to long
param_title = [] #create a list of the parameters for the table
for i in param_combos:
param_title.append( 'pre:%s-gamma:%s' % (i.get('preference'),i.get('gamma')))
mean_total.columns = param_title
get_ipython().magic(u'matplotlib inline')
plot_m =mean_total.plot (title="mean collective emotion - average of trials " , ylim = (1,8))
plot_m.set_xlabel("time")
plot_m.set_ylabel("collective emotion")
# assuming that you have multiple trials - this code will consolidate all the trails data sets
"""data = []
for j in range(TRIALS): # for all j (wich are all the trials).
from ComplexNetworkSim import utils
contents = utils.retrieve('test/log_trial_%d_statevectors.pickled' % j) # get the pickeled data
# you can change the name of the data set.
ra = [] # form and empty list in which this data will look
for i in contents: # we need to manipulate the list because it has the number of each person in it
y = (i[1]) # each list comes as [1,[content]] so we need to remove the first part.
ra.append (y) # once we are done we have ra which is a list of lists of the first trial
data.append (pd.DataFrame (np.array (ra))) # data is a list of lists of lists we want to make in into just a list of arrays.
#print len(data)
#print len(data[0])
# In[38]:
plot_state =data[0].plot (title="collective emotion", legend = None, ylim = (1,8))
plot_state.set_xlabel("time")
plot_state.set_ylabel("intensity")
# In[12]:
data_t=sum (data)/len(data) # we are adding all the data sets to each other.
m=[]
std =[]
m.append(data_t.mean(1)) # take the mean of every time (every row).
std.append(data_t.std(1)) # take the sd of every time (every row).
m = pd.DataFrame(np.array(m)) # transform into a dataset
m = m.T # transport - for the graph
#m.columns =['n=10', 'n=50' , 'n=100']
std = pd.DataFrame (np.array (std)) # transform into a data set.
std = std.fillna(value=0) # fill the nas with 0
std = std.T
#std.columns = ['n=10
get_ipython().magic(u'matplotlib inline')
plot_m =m.plot (title="mean collective emotion", legend = None, ylim = (1,8))
plot_m.set_xlabel("time")
plot_m.set_ylabel("collective emotion")
plot_std =std.plot (title="std collective emotion")
plot_std.set_xlabel("time")
plot_std.set_ylabel("collective emotion")"""
# In[13]:
"""# animation
from ComplexNetworkSim import PlotCreator, AnimationCreator
directory = 'r_1' #location of simulation result files
myName = "collective_emotion" #name that you wish to give your image output files
title = "collective_emotion"
#define three simulation-specific constants:
statesToMonitor = ["1", "2", "3", "4"] #even if we have states 0,1,2,3,... plot only 1 and 0
colours = ["kakhi1", "yellow2", "sienna1", "red2"] #state 1 in red, state 0 in green
labels = ["1", "2", "3", "4"]
mapping = {"1":"0" , "2":".4", "3": ".7", "4": "1"}
trialToVisualise = 0
visualiser = AnimationCreator(directory, myName, title, mapping, trial=trialToVisualise, delay = 60)
#gif speed can be changed by giving a parameter 'delay' (default=100) to AnimationCreator
visualiser.create_gif(verbose=True)"""
......@@ -17,7 +17,7 @@ from ComplexNetworkSim import NetworkSimulation, utils, PlotCreator
"""network"""
nodes = 30 # the amount of nodes for the graph.
nodes = 40 # the amount of nodes for the graph. which is also the amount of particiaptns
#typologt
......@@ -31,8 +31,8 @@ nx.draw_networkx(G) # draw the network
""" parameter combination """
#event_set = [0.1,0,2] # the rate of emotion eliciting events (the change that an agent will experience)
preference_set = [0.5 ]
gamma_set = [0.90, 0.95]
preference_set = [0.01,0.2,0.5]
gamma_set = [0.95]
#bump_set = [2]
param_combos = [ {'preference':preference, 'gamma':gamma}
......@@ -46,8 +46,8 @@ TRIALS = 1 # how many repititions is the system doing
mean_total = []#pd.DataFrame(range(MAX_SIMULATION_TIME))
sim_name = 'wide'
states = [ np.random.normal(3,1) for n in G.nodes()] # initiation state of all agenges
states[0] = np.random.normal(3,1) # infecting partcipiant 0
states = [ np.random.normal(5,1) for n in G.nodes()] # initiation state of all agenges
states[0] = np.random.normal(5,1) # infecting partcipiant 0
states[0] = sorted([1, states[0], 8])[1] # define an upper limit.
def main(): # we are defining a function that activates the sumulation.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment