library(rgl)
library(sphere)
n<-4
us<-sample(1:10,n)
us<-rep(1,n)
Nr<-n
ks<-runif(Nr)
ks<-rep(1,n)
In<-Player<-diag(n)
Out<-matrix(0,Nr,n)
for(i in 1:Nr){
for(j in 1:n){
if(j==i+1){
Player[i,j]<-1
Out[i,j]<-1
}
}
}
Player[Nr,1]<-Out[Nr,1]<-1
S<-1
P<-runif(1,min=0,max=(1/n)^n)
Nrep<-30
xssum<-NULL
col<-c()
for(rep in 1:Nrep){
Niter<-1000
dt<-0.01
m<-matrix(0,Niter,n)
p<-rep(0,Niter)
p[1]<-0
for(i in 1:n){
p[1]<-p[1]+us[i]*m[1,i]
}
m[1,]<-m[1,]/p[1]
p[1]<-0
for(i in 1:n){
p[1]<-p[1]+us[i]*m[1,i]
}
library(MCMCpack)
initloop<-TRUE
while(initloop){
m[1,1]<-runif(1)
m[1,2]<-runif(1)
tmp1<-1-(m[1,1]+m[1,2])
tmp2<-tmp1^2-4*P/(m[1,1]*m[1,2])
if(tmp2>=0){
m[1,3]<-1/2*(tmp1+sqrt(tmp2))
m[1,4]<-1/2*(tmp1-sqrt(tmp2))
if(m[1,4]>0){
initloop<-FALSE
}
}
}
m[1,]<-sample(m[1,])
for(i in 2:Niter){
m[i,]<-m[i-1,]
for(j in 1:Nr){
tmp<-ks[j]*dt
pamountIn<-0
pamountOut<-0
for(k in 1:n){
tmp<-tmp*m[i-1,k]^Player[j,k]
pamountIn<-pamountIn+us[k]*In[j,k]
pamountOut<-pamountOut+us[k]*Out[j,k]
}
for(k in 1:n){
m[i,k]<-m[i,k]-In[j,k]*tmp+tmp*pamountIn/pamountOut*us[k]*Out[j,k]/pamountOut*Out[j,k]
}
}
for(j in 1:n){
p[i]<-p[i]+us[j]*m[i,j]
}
}
plot(p,type="l",ylim=c(0,2),main="保存量")
plot(data.frame(m),cex=0.1)
xs<-matrix(0,Niter,n-1)
cv<-CategoryVector(n)
for(i in 1:Niter){
for(j in 1:n){
xs[i,]<-xs[i,]+m[i,j]*cv[j,]
}
}
xssum<-rbind(xssum,xs)
col<-c(col,rep(rep,Niter))
}
plot3d(xssum[,1],xssum[,2],xssum[,3],col=col)