Commit ed129b68 authored by Amit Goldenberg's avatar Amit Goldenberg

Merge branch 'script_ABM_collective_emotion.py' into 'master'

Script abm collective emotion.py



See merge request !3
parents fab6d5c7 2f34f21e
......@@ -5,18 +5,18 @@ from scipy.stats import truncnorm
import matplotlib.animation as animation
from ComplexNetworkSim import NetworkAgent, Sim
# all the packages
preference_list = []
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.
self.gamma = 1 #self.globalSharedParameters['gamma'] # the decay term.
#fixed variables (for now)
self.event = 0.5 #self.globalSharedParameters['event'] # rate of experience - low numbers mean
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)
self.event = self.globalSharedParameters['event'] # rate of experience - low numbers mean less chance
self.bump = 0#globalSharedParameters['bump']
#self.noise = np.random.normal(0.09, 0.15) # noise term
self.conform = truncnorm.rvs(0.28,0.6) #np.random.normal(0.28,0.2) #this is the degree of conformity each participant has.
self.thresh = -1# np.random.normal(3,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)
......@@ -26,15 +26,17 @@ 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
"""
# I made this cose for situations in which influence is = 0 (when there are no people that express their emotions)
#print "influence %s" %influence
emotion = (self.state*self.gamma) - influence + self.preference # the individual emotion
emotion = (self.state*self.gamma) - influence + self.preference +np.random.normal(0, 0.15) # the individual emotion
# this part forms the emotional bump that a participant recieves using the experience ratio.
self.event = self.event*0.95
self.event = self.event*1
if self.flip() == "bump": # if the flip condition fit the bump - than we need to bump.
self.state = emotion + self.bump # can be changed
elif self.flip() == "no_bump":
......@@ -71,6 +73,5 @@ class ColEmo(NetworkAgent):
self.local_avg = self.stateVector
"""
def flip(self):
return "no_bump" if random.random() > self.event else "bump"
import random
import numpy as np
from scipy.stats import truncnorm
import matplotlib.animation as animation
from ComplexNetworkSim import NetworkAgent, Sim
# all the packages
preference_list = []
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 = 0.83 #self.globalSharedParameters['gamma'] # the decay term.
#fixed variables (for now)
self.event = 0 #self.globalSharedParameters['event'] # rate of experience - low numbers mean less chance
self.bump = 0#globalSharedParameters['bump']
#self.noise = np.random.normal(0.09, 0.15) # noise term
self.conform = truncnorm.rvs(0.2,0.6) #np.random.normal(0.28,0.2) #this is the degree of conformity each participant has.
self.thresh = -1# np.random.normal(3,0.5)
self.confidence = def dist () #this is if I want to sweep it self.globalSharedParameters['confidence']
#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
def Run(self):
while True:
self.set_local_avg()
influence = (self.state-self.local_avg)*self.conform # certain conform ratio
if (self.state-self.local_avg) <self.confidence and (self.state-self.local_avg) >-self.confidence :
influence = influence
else:
influence = 0
# I made this cose for situations in which influence is = 0 (when there are no people that express their emotions)
#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.
self.event = self.event*1
if self.flip() == "bump": # if the flip condition fit the bump - than we need to bump.
self.state = emotion + self.bump # can be changed
elif self.flip() == "no_bump":
self.state = emotion
self.state = sorted([1, self.state, 8])[1] # define the max and min limit.
# this following part is designed to create the threshold that every person has.
# we are forming to parallel lists, self state and self-state vector/ Self state vercotr becomes None everytime something doesn't pass
# 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()
a = [nb.stateVector for nb in nbrs]
#print "neighbor %s" %a
self.local_avg = a[2] # this should be changed for a random number
#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]
self.local_avg = np.mean(filter(None, a)) # create a filter the removes nones from average.
print "average %s" %self.local_avg
print "neighbor %s" %a
except RuntimeWarning:
self.local_avg = self.stateVector
"""
def flip(self):
return "no_bump" if random.random() > self.event else "bump"
import math
import random
import numpy as np
from scipy.stats import truncnorm
import matplotlib.animation as animation
from ComplexNetworkSim import NetworkAgent, Sim
# all the packages
preference_list = []
class ColEmo(NetworkAgent):
def __init__(self, state, initialiser):
NetworkAgent.__init__(self, state, initialiser)
self.preference = 0 # np.random.normal(0,self.globalSharedParameters['preference']) #this is the defree of preference (regulation) each participants has.
self.gamma = 1 #self.globalSharedParameters['gamma'] # the decay term.
#fixed variables (for now)
#self.event = 0 #self.globalSharedParameters['event'] # rate of experience - low numbers mean less chance
#self.bump = 0#globalSharedParameters['bump']
self.noise = np.random.normal(0.09, 0.15) # noise term
self.conform = self.globalSharedParameters['conform'] #np.random.normal(0.28,0.2) #this is the degree of conformity each participant has.
self.polarize = self.globalSharedParameters['polarize']
#self.thresh = -1# np.random.normal(3,0.5) #threshold
#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
def Run(self):
while True:
self.set_local_avg()
influence = (self.local_avg-self.state)*self.conform+math.pow((self.local_avg-self.state),3)*self.polarize # certain conform ratio
# I made this cose for situations in which influence is = 0 (when there are no people that express their emotions)
#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.
"""self.event = self.event*1 #this part cad define the rate of efects for the bump
#if self.flip() == "bump": # if the flip condition fit the bump - than we need to bump.
self.state = emotion + self.bump # can be changed
elif self.flip() == "no_bump"
"""
self.state = emotion
self.state = sorted([1, self.state, 10])[1] # define the max and min limit.
# this following part is designed to create the threshold that every person has.
# we are forming to parallel lists, self state and self-state vector/ Self state vercotr becomes None everytime something doesn't pass
# a certain threshold - the average of nb is taken of all the numbers that does not include None
self.stateVector = self.state
"""
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()
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]
self.local_avg = np.mean(filter(None, a)) # create a filter the removes nones from average.
print "average %s" %self.local_avg
print "neighbor %s" %a
except RuntimeWarning:
self.local_avg = self.stateVector
"""
def flip(self):
return "no_bump" if random.random() > self.event else "bump"
......@@ -13,16 +13,16 @@ import matplotlib.animation as animation
from script_ABM_collective_emotion import ColEmo
from ComplexNetworkSim import NetworkSimulation, utils, PlotCreator
#get_ipython().magic(u'matplotlib inline')
get_ipython().magic(u'matplotlib inline')
"""network"""
nodes = 10 # the amount of nodes for the graph. which is also the amount of particiaptns
nodes = 100 # the amount of nodes for the graph. which is also the amount of particiaptns
#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*3) # the type of network we are building.
#=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.
......@@ -30,24 +30,29 @@ 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.01,0.2, 0.5]
gamma_set = [0.95]
event_set = [0] # the rate of emotion eliciting events (the change that an agent will experience)
preference_set = [0.00001]
#gamma_set = [0.95]
#bump_set = [2]
param_combos = [ {'preference':preference, 'gamma':gamma}
for preference in preference_set for gamma in gamma_set]
param_combos = [ {'preference':preference, 'event':event}
for preference in preference_set for event in event_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(2,1) for n in G.nodes()] # initiation state of all agenges
states[0] = np.random.normal(2,1) # infecting partcipiant 0
states = [ np.random.normal(4,1) for n in G.nodes()] # initiation state of all agenges
states[0] = np.random.normal(4,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.
......@@ -65,9 +70,9 @@ def main(): # we are defining a function that activates the sumulation.
t = time()
directory =(
'results/'
'{gamma}--{preference}'.format(
'{event}--{preference}'.format(
preference = global_params['preference'],
gamma = global_params['gamma'])
event = global_params['event'])
)
simulation = NetworkSimulation(G,states,ColEmo,directory,MAX_SIMULATION_TIME,TRIALS,**global_params)
......@@ -95,6 +100,9 @@ def main(): # we are defining a function that activates the sumulation.
plot_state.set_xlabel("time")
plot_state.set_ylabel("intensity")
# plot_state1 df.plot(kind='scatter', x='c', y='d',
# color='DarkGreen', label='Group 2', ax=ax);
# save the picture
fig = plot_state.get_figure()
fig.savefig('%s.png' %(directory))
......@@ -134,7 +142,7 @@ def main(): # we are defining a function that activates the sumulation.
"""
# run main
if __name__ == '__main__':
if __name__ == '__main__':
main()
""" in this part I print mean total which is the list of all the means"""
......@@ -144,7 +152,7 @@ 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')))
param_title.append( 'pre:%s-event:%s' % (i.get('preference'),i.get('event')))
mean_total.columns = param_title
......
""" 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
......@@ -10,18 +10,18 @@ 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 script_ABM_collective_emotion_cubic import ColEmo
from ComplexNetworkSim import NetworkSimulation, utils, PlotCreator
#get_ipython().magic(u'matplotlib inline')
get_ipython().magic(u'matplotlib inline')
"""network"""
nodes = 30 # the amount of nodes for the graph.
nodes = 10# the amount of nodes for the graph. which is also the amount of particiaptns
#typologt
#G = nx.gnm_random_graph (nodes,nodes*2.5) # the type of network we are building.
#G = nx.gnm_random_graph (nodes,nodes*3) # 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.
......@@ -30,25 +30,32 @@ 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]
#event_set = [0] # the rate of emotion eliciting events (the change that an agent will experience)
polarize_set = [-0.2,-0.1]# -0.01]
conform_set = [0.8,0.9]#,1.1]
#gamma_set = [0.95]
#bump_set = [2]
param_combos = [ {'preference':preference, 'gamma':gamma}
for preference in preference_set for gamma in gamma_set]
param_combos = [ {'conform': conform , 'polarize':polarize}
for conform in conform_set for polarize in polarize_set]
"""simulation routine"""
MAX_SIMULATION_TIME = 100 # the amounts of simulations
MAX_SIMULATION_TIME = 10 # 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.
states = [ np.random.normal(4,2) for n in G.nodes()] # initiation state of all agenges
states[0] = np.random.normal(4,2) # infecting partcipiant 0
states[0] = sorted([1, states[0], 10])[1] # define an upper limit.
def main(): # we are defining a function that activates the sumulation.
directory = 'test' #output directory
......@@ -65,9 +72,9 @@ def main(): # we are defining a function that activates the sumulation.
t = time()
directory =(
'results/'
'{gamma}--{preference}'.format(
preference = global_params['preference'],
gamma = global_params['gamma'])
'{conform}--{polarize}'.format(
polarize = global_params['polarize'],
conform = global_params['conform'])
)
simulation = NetworkSimulation(G,states,ColEmo,directory,MAX_SIMULATION_TIME,TRIALS,**global_params)
......@@ -91,10 +98,13 @@ def main(): # we are defining a function that activates the sumulation.
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 =data[0].plot (title="collective emotion- single trial %s" % (directory), legend = None, ylim = (1,10))
plot_state.set_xlabel("time")
plot_state.set_ylabel("intensity")
# plot_state1 df.plot(kind='scatter', x='c', y='d',
# color='DarkGreen', label='Group 2', ax=ax);
# save the picture
fig = plot_state.get_figure()
fig.savefig('%s.png' %(directory))
......@@ -120,7 +130,7 @@ def main(): # we are defining a function that activates the sumulation.
""""
# 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 =m.plot (title="mean collective emotion - average of trials %s" % (directory), legend = None, ylim = (1,10))
plot_m.set_xlabel("time")
plot_m.set_ylabel("collective emotion")
fig = plot_m.get_figure()
......@@ -144,12 +154,12 @@ 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')))
param_title.append( 'con:%s-pol:%s' % (i.get('conform'),i.get('polarize')))
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 =mean_total.plot (title="mean collective emotion - average of trials " , ylim = (1,10))
plot_m.set_xlabel("time")
plot_m.set_ylabel("collective emotion")
......@@ -174,7 +184,7 @@ for j in range(TRIALS): # for all j (wich are all the trials).
# In[38]:
plot_state =data[0].plot (title="collective emotion", legend = None, ylim = (1,8))
plot_state =data[0].plot (title="collective emotion", legend = None, ylim = (1,10))
plot_state.set_xlabel("time")
plot_state.set_ylabel("intensity")
......@@ -199,7 +209,7 @@ std = std.T
get_ipython().magic(u'matplotlib inline')
plot_m =m.plot (title="mean collective emotion", legend = None, ylim = (1,8))
plot_m =m.plot (title="mean collective emotion", legend = None, ylim = (1,10))
plot_m.set_xlabel("time")
plot_m.set_ylabel("collective emotion")
......
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