import time
import networkx as nx #导入复杂网络分析库
import matplotlib.pyplot as plt #导入科学绘图库
import random
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号
获取多次结果平均值函数,以机事件按概率发生函数:
[Python] 纯文本查看复制代码
def getAv(li):
new = []
for i in range(len(li[0])):
n = 0
for j in range(len(li)):
n += li[j][i]
new.append(round(n/len(li),3))
return(new)
#概率事件
def ran_happen(p):
n = random.random()
if n < p:
return(1)
else:
return(0)
异质元胞自动机 (HCA) 的负面口碑扩散模型类:
[Python] 纯文本查看复制代码
class HCA(object):
def __init__(self,h,l,Vc,Va,Vb,Vy,Vo):
super(HCA, self).__init__()
self.h = h #行
self.l = l #列
self.Vc = Vc #初期抱怨比例
self.Va = Va #易感转化抱怨概率
self.Vb = Vb #负面口碑传播概率
self.Vy = Vy #二次负面概率
self.Vo = Vo #负面口碑解除概率
self.cell = np.random.randint(0,1,size=(self.h,self.l))
for i in range(self.h):
for j in range(self.l):
if ran_happen(self.Vc):
self.cell[i][j] = 1 #0易感 1抱怨 2康复
def lin(self,i,j): #元胞邻域历遍
ii = [i-1,i-1,i-1, i, i,i+1,i+1,i+1]
jj = [j-1, j,j+1,j-1,j+1,j-1, j,j+1]
for x in range(len(ii)):
if ii[x] < self.h and ii[x] >= 0:
if jj[x] < self.l and jj[x] >= 0:
if self.cell[ii[x]][jj[x]] == 0:
if ran_happen(self.Vb):
self.cell[ii[x]][jj[x]] = 1
if self.cell[ii[x]][jj[x]] == 2:
if ran_happen(self.Vy):
self.cell[ii[x]][jj[x]] = 1
def process(self): #每一步
num = 0
for i in range(self.h):
for j in range(self.l):
if self.cell[i][j] == 0:
if ran_happen(self.Va):
self.cell[i][j] = 1
elif self.cell[i][j] == 1:
num += 1
self.lin(i,j)
if ran_happen(self.Vo):
self.cell[i][j] = 2
else:
if ran_happen(self.Vy):
self.cell[i][j] = 1
return(num)
主函数:
[Python] 纯文本查看复制代码
def main(Vc):
ZN = []
ZNN = []
for j in range(2):
hh = HCA(128,128,Vc,0.05,0.1,0.1,0.5)
N = []
NN = []
old = 0
for i in range(20):
n = hh.process()
N.append(round(n/(128*128),3))
NN.append(round((n-old)/(128*128),3))
old = n
ZN.append(N)
ZNN.append(NN)
return(getAv(ZN),getAv(ZNN))