Opinion Game - One Topic in the network

These codes were developed as a part of the our opinion game model.

Import Python built-in functions we need to run and plot the game


In [24]:
import numpy as np
from numpy.random import randn
import pandas as pd
from pandas import Series, DataFrame

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.image as mpimg
from matplotlib import rcParams
import seaborn as sb

Set up inline matplotlib

This tells Python to plot the figure right in here, in the notebook.


In [25]:
%matplotlib inline
#rcParams['figure.figsize'] = 5, 4
sb.set_style('whitegrid')

Import Game Modules From a Given Path

User have to edit the path and put the correct one on his/her machine.


In [26]:
import sys
# search path for modules
sys.path.append('/Users/hn/Documents/GitHub/PyOpinionGame/')

import opiniongame.config as og_cfg
import opiniongame.IO as og_io
import opiniongame.coupling as og_coupling
import opiniongame.state as og_state
import opiniongame.adjacency as og_adj
import opiniongame.selection as og_select
import opiniongame.potentials as og_pot
import opiniongame.core as og_core
import opiniongame.stopping as og_stop
import opiniongame.opinions as og_opinions

Setting Up Game Parameters


In [27]:
config = og_cfg.staticParameters()

path = '/Users/hn/Documents/GitHub/PyOpinionGame/'  # path to the 'staticParameters.cfg'
staticParameters = path + 'staticParameters.cfg'

config.readFromFile(staticParameters)
config.threshold = 0.0001
config.Kthreshold = 0.00001
config.startingseed = 20
config.learning_rate = 0.1
tau = 0.62 #tip of the tent potential function
config.printOut()


=================
StaticParameters:
=================
Learning rate     = 0.1
Unique. strength  = 0.0
Skew. strength  = 0.0
NumExperiments    = 100
PopSize           = 20
Threshold         = 0.0001
Hthreshold        = 1e-06
Kthreshold        = 1e-05
ntopics           = 1
startingSeed      = 20
iterationMax      = 100

seed PRNG: must do this before any random numbers are ever sampled during default generation


In [28]:
print("SEEDING PRNG: "+str(config.startingseed))
np.random.seed(config.startingseed)


SEEDING PRNG: 20

Set up the state of the system

State of the system includes:

  • Weight Matrix (Matrix of the coupling wieghts between topic)
  • Initial Opinions of agents
  • Adjacency matrix of the network

In [29]:
# These are the default matrices for the state of the system:
# If you want to change them, you can generate a new one in the following cell
default_weights = og_coupling.weights_no_coupling(config.popSize, config.ntopics)
default_initialOpinions = og_opinions.initialize_opinions(config.popSize, config.ntopics)
default_adj = og_adj.make_adj(config.popSize, 'full')

User Defined States Can go in the following cell:


In [30]:
# user_weights = 
# user_initialOpinions = 
# user_adj =

In [48]:
state = og_state.WorldState(adj=default_adj, 
                            couplingWeights=default_weights, 
                            initialOpinions=default_initialOpinions, 
                            initialHistorySize=100, 
                            historyGrowthScale=2)
state.validate()
ufuncs = og_cfg.UserFunctions(og_select.FastPairSelection,
                              og_stop.iterationStop,
                              og_pot.createTent(tau))


WEIGHT SHAPE   : (20, 1, 1)
OPINION SHAPE  : (20, 1)
ADJACENCY SHAPE: (20, 20)
==> World state validation passed.

Run The Game


In [49]:
#
# run the game
#
state = og_core.run_until_convergence(config, state, ufuncs)

# Extract and save the history of the game
rdict = {}
rdict['history'] = state.history
og_io.saveMatrix('output.mat', rdict)



Reshape the history

Since here we have just one topic, the matrix can be converted to a 2D array, rather than 3. This makes the plotting job easier:


In [50]:
time, population_size, no_of_topics = rdict['history'].shape
evolution = rdict['history'].reshape(time, population_size)

Convert to Panda DataFrame and then plot.


In [51]:
df = pd.DataFrame(data=evolution, index=None, columns=None)

In [99]:
fig = plt.figure()
ax = df.plot(legend=False)
ax.set_xlabel("Time")
ax.set_ylabel("Opinions")
ax.set_title('Evolution of Opinions')
plt.show()


<matplotlib.figure.Figure at 0x1a116fe2d0>

Plot the numpy array


In [98]:
fig1 = plt.figure()
plt.plot(evolution)
plt.xlabel('Time')
plt.ylabel('Opinionds')
plt.title('Evolution of Opinions')
plt.show()