From b76dffdc63a50ea3955068b3d28194bd12c26719 Mon Sep 17 00:00:00 2001 From: zthdsb <1278405208@qq.com> Date: Sun, 26 Nov 2017 14:00:22 +0800 Subject: [PATCH] =?UTF-8?q?python=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 张铁海 学号:201730310112 邮箱:1278405208@qq.com 初学python,代码修改还有欠缺,望老师指正~ --- .../.gitignore" | 8 ++ .../p1.py" | 5 + .../p10.py" | 84 +++++++++++ .../p11.py" | 136 ++++++++++++++++++ .../p12.py" | 16 +++ .../p13.py" | 31 ++++ .../p13/compMean.py" | 6 + .../p13/compVariance.py" | 13 ++ .../p13/p13.py" | 13 ++ .../p14.py" | 13 ++ .../p15.py" | 13 ++ .../p16.py" | 48 +++++++ .../p2.py" | 60 ++++++++ .../p3.py" | 65 +++++++++ .../p4.py" | 11 ++ .../p5.py" | 26 ++++ .../p6.py" | 38 +++++ .../p7.py" | 41 ++++++ .../p8.py" | 97 +++++++++++++ .../p9.py" | 101 +++++++++++++ 20 files changed, 825 insertions(+) create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/.gitignore" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p1.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p10.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p11.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p12.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/compMean.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/compVariance.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/p13.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p14.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p15.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p16.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p2.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p3.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p4.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p5.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p6.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p7.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p8.py" create mode 100644 "python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p9.py" diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/.gitignore" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/.gitignore" new file mode 100644 index 0000000..2945e14 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/.gitignore" @@ -0,0 +1,8 @@ + +p13/__pycache__/__init__.cpython-35.pyc +p13/__init__.py +p13/__pycache__/p13.cpython-35.pyc +p13/__pycache__/compVariance.cpython-35.pyc +p13/__pycache__/compMean.cpython-35.pyc +text.py +泡泡.py diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p1.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p1.py" new file mode 100644 index 0000000..1d4c553 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p1.py" @@ -0,0 +1,5 @@ +n=10 +p=[] +for i in range(n): + p.append(1/n) +print(p) \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p10.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p10.py" new file mode 100644 index 0000000..22b36e9 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p10.py" @@ -0,0 +1,84 @@ +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +def getPositon(a): + raw, column = a.shape # get the matrix of a raw and column + positon = np.argmax(a) # get the index of max in the a + # print(positon) + r, c = divmod(positon , column) + return r,c + +def sence(p,z,world,pSenseCorrect): + # nRow=len(p[0]) + # nCol=len(p[:0]) + nRow,nCol=np.shape(p) + q_size=(nRow,nCol) + q=np.zeros(q_size) + for r in range(0,nRow): + for c in range(0,nCol): + if z== world[r][c]: + hit=1 + else: + hit=0 + q[r,c]=p[r,c]*(hit * pSenseCorrect + (1-hit) * (1-pSenseCorrect)) + S=sum(q) + for i in range(len(q)): + q[i]=q[i]/sum(S) + return q + +world = (('red', 'green', 'green', 'red', 'red'), +('red', 'red', 'green', 'red', 'red'), +('red', 'red', 'green', 'green', 'red'), +('red', 'red', 'red', 'red', 'red')) +nRow = len(world) +nCol = len(world[1]) +print(world[1][1]) +pStart = 0.7 +ones_size=(nRow,nCol) +ones=np.ones(ones_size) +p = (1 - pStart) / (nRow * nCol - 1) * ones +pSenseCorrect=0.7 +p[2,1]=pStart +measurements=['green'] +# print(measurements[0]) +q=sence(p,measurements[0],world,pSenseCorrect) +print("The Prior:\n",p) +print("The probability after sensing:\n",q) +r,c=getPositon(q) +print('The largest probability %s occurs at cell(%s,%s)\n'%(q[r,c],r,c)) + +plt.ion() +h=plt.figure(1) +ax=Axes3D(h) +ly= len(p[0]) #5 # Work out matrix dimensions +lx= len(p[:,0]) #4 +xpos = np.arange(0,lx,1) # Set up a mesh of positions +ypos = np.arange(0,ly,1) +xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25) +xpos = xpos.flatten() # Convert positions to 1D array +ypos = ypos.flatten() +zpos = np.zeros(lx*ly) + +dx = np.ones_like(zpos) +dy = dx.copy() +dz = p.T.flatten() +ax.bar3d(xpos,ypos,zpos, dx, dy, dz) + +h1=plt.figure(2) +ax=Axes3D(h1) +ly= len(q[0]) #5 # Work out matrix dimensions +lx= len(q[:,0]) #4 +xpos = np.arange(0,lx,1) # Set up a mesh of positions +ypos = np.arange(0,ly,1) +xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25) +xpos = xpos.flatten() # Convert positions to 1D array +ypos = ypos.flatten() +zpos = np.zeros(lx*ly) + +dx = np.ones_like(zpos) +dy = dx.copy() +dz = q.T.flatten() +ax.bar3d(xpos,ypos,zpos, dx, dy, dz) +plt.ioff() +plt.show() \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p11.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p11.py" new file mode 100644 index 0000000..049ac6e --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p11.py" @@ -0,0 +1,136 @@ +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +def getPositon(a): + raw, column = a.shape # get the matrix of a raw and column + positon = np.argmax(a) # get the index of max in the a + # print(positon) + r, c = divmod(positon , column) + return r,c + +def move(p,u,pMoveCorrect): + nRow=int(len(p)) + nCol=int(len(p[0])) + q=np.zeros(ones_size) + for r in range(1,nRow+1): + for c in range(1,nCol+1): + q[r-1,c-1]=pMoveCorrect * p[np.mod(r-1-u[0],nRow),np.mod(c-1-u[1],nCol)]+ (1-pMoveCorrect)* p[r-1,c-1] + # return q + return q + +def sence(p,z,world,pSenseCorrect): + # nRow=len(p[0]) + # nCol=len(p[:0]) + nRow,nCol=np.shape(p) + q_size=(nRow,nCol) + q=np.zeros(q_size) + for r in range(0,nRow): + for c in range(0,nCol): + if z== world[r][c]: + hit=1 + else: + hit=0 + q[r,c]=p[r,c]*(hit * pSenseCorrect + (1-hit) * (1-pSenseCorrect)) + S=sum(q) + for i in range(len(q)): + q[i]=q[i]/sum(S) + return q + +def compEntropy(p): + compEntropy = -sum(sum(p * np.log2(p))) + return compEntropy + + +world = (('red', 'green', 'green', 'red', 'red'), +('red', 'red', 'green', 'red', 'red'), +('red', 'red', 'green', 'green', 'red'), +('red', 'red', 'red', 'red', 'red')) +nRow = len(world) +nCol = len(world[1]) +print(nRow,nCol) +step={ + 'stop':[0,0], + 'right':[0,1], + 'left':[0,-1], + 'down':[1,0], + 'up':[-1,0] +} +pMoveCorrect = 0.8 +pSenseCorrect=0.7 +ones_size=(nRow,nCol) +ones=np.ones(ones_size) +p = 1/ (nRow * nCol) * ones +# compEntropy=-sum(sum(p * np.log2(p))) + +#First configuration +motions=[step['stop'],step['right'],step['down'],step['down'],step['right']] +measurements=['green','green','green','green','green'] +#Check the size +if len(motions)!= len(measurements): + print("The variable 'motions' should be of the same size as 'measurements' ! ") +entropy_size=(2,len(motions)) +entropy=np.zeros(entropy_size) +#The main loop +plt.ion() +for i in range(0,len(motions)): + # plt.ion() + p=move(p,motions[i],pMoveCorrect) + p0=p + p=sence(p,measurements[i],world,pSenseCorrect) + #Compute entropy + entropy[:,i]=[compEntropy(p0),compEntropy(p)] + # Make figures + h=plt.figure(1) + ax1=h.add_subplot(2,1,1,projection='3d') + # ax = Axes3D(h) + plt.cla() + plt.title('Step %s\n The probability before sensing'%i) + ly = len(p0[0]) # 5 # Work out matrix dimensions + lx = len(p0[:, 0]) # 4 + xpos = np.arange(0, lx, 1) # Set up a mesh of positions + ypos=(1,2,3,4,5) + xpos, ypos = np.meshgrid(xpos, ypos) + xpos = xpos.flatten() # Convert positions to 1D array + ypos = ypos.flatten() + zpos = np.zeros(lx * ly) + + dx = np.ones_like(zpos) + dy = dx.copy() + dz = p0.T.flatten() + # ax1.set(color='r,b,g') + ax1.bar3d(xpos, ypos, zpos, dx, dy, dz,color='b',alpha=0.6) + + ax2=h.add_subplot(2,1,2,projection='3d') + ly = len(p[0]) # 5 # Work out matrix dimensions + lx = len(p[:, 0]) # 4 + xpos = np.arange(0, lx, 1) # Set up a mesh of positions + ypos = np.arange(0, ly, 1) + xpos, ypos = np.meshgrid(xpos, ypos) + xpos = xpos.flatten() # Convert positions to 1D array + ypos = ypos.flatten() + zpos = np.zeros(lx * ly) + dx = np.ones_like(zpos) + dy = dx.copy() + dz = p.T.flatten() + # plt.cla() + col=np.arange(30) + # plt.scatter(xpos,ypos,zpos,c=col) + ax2.bar3d(xpos, ypos, zpos, dx, dy, dz,color='g',alpha=0.6) + plt.pause(0.5) + +print('The Posterior:\n',p) +r,c=getPositon(p) +print('The largest probability %.4f occurs at cell (%d, %d)\n '%(p[r,c],r,c)) + +h2=plt.figure(2) +motions_size=len(motions) +plt.plot(range(1,motions_size+1),entropy[0,:],'bh',linewidth=3,markersize=10) +plt.plot(range(1,motions_size+1),entropy[1,:],'rx',linewidth=3,markersize=10) + +plt.xlim(0,(len(motions)+1)) +plt.xlabel('Step') +plt.ylabel('Entropy') +plt.legend(('After sensing', 'Before sensing'),loc='upper right') +plt.ioff() +plt.show() \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p12.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p12.py" new file mode 100644 index 0000000..f2ae960 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p12.py" @@ -0,0 +1,16 @@ + +pCan=0.001 +pNon=0.999 +z='positive' +# z='negative' +pPosCan=0.8 +pPosNon=0.1 +if z=='positive': + p=[pPosCan*pCan, pPosNon*pNon] +else: + p=[(1-pPosCan)*pCan,(1-pPosNon)*pNon] +S=sum(p) +for i in range(len(p)): + p[i]=p[i]/sum(p) +print(p[0]) +print(p[1]) diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13.py" new file mode 100644 index 0000000..b32ade9 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13.py" @@ -0,0 +1,31 @@ +from compMean import compMean +from compVariance import compVariance +import numpy as np + +def mean(x): #计算均值的 + S = np.sum(x) #矩阵中每个元素求和必须用np.sum + shape = x.shape[:] + mean=S/(shape[0]*shape[1]) + return mean + +def compVariance(x): #计算方差的 + mu=mean(x) + mu=np.mat(mu) + x2=np.square(x-mu) + sigma2=mean(x2) + return sigma2 +def compMean(x): #计算均值的 + S=np.sum(x) + shape=x.shape[:] + mu=S/(shape[0]*shape[1]) + return mu + +x=[7,38,4,23,18] +# x=[17,19,18,17,19] +# x=[18,18,18,18,18] +x=np.mat(x) +mu=compMean(x) +sigma2=compVariance(x) +print('The Expectation / Mean:\t %s \n'%mu) +print('The Variance is:\t\t %s \n'%sigma2) +print('The Standard Deviation is:\t %s \n'%np.sqrt(sigma2)) \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/compMean.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/compMean.py" new file mode 100644 index 0000000..c63a2bf --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/compMean.py" @@ -0,0 +1,6 @@ +import numpy as np +def compMean(x): #计算均值的 + S=np.sum(x) + shape=x.shape[:] + mu=S/(shape[0]*shape[1]) + return mu \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/compVariance.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/compVariance.py" new file mode 100644 index 0000000..e36fa8e --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/compVariance.py" @@ -0,0 +1,13 @@ +import numpy as np +def mean(x): #计算均值的 + S = np.sum(x) #矩阵中每个元素求和必须用np.sum + shape = x.shape[:] + mean=S/(shape[0]*shape[1]) + return mean + +def compVariance(x): #计算方差的 + mu=mean(x) + mu=np.mat(mu) + x2=np.square(x-mu) + sigma2=mean(x2) + return sigma2 \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/p13.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/p13.py" new file mode 100644 index 0000000..203cdb6 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p13/p13.py" @@ -0,0 +1,13 @@ +from compMean import compMean +from compVariance import compVariance +import numpy as np + +x=[7,38,4,23,18] +# x=[17,19,18,17,19] +# x=[18,18,18,18,18] +x=np.mat(x) +mu=compMean(x) +sigma2=compVariance(x) +print('The Expectation / Mean:\t %.2f \n'%mu) +print('The Variance is:\t\t %.2f \n'%sigma2) +print('The Standard Deviation is:\t %.2f \n'%np.sqrt(sigma2)) \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p14.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p14.py" new file mode 100644 index 0000000..e1d55ab --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p14.py" @@ -0,0 +1,13 @@ +import numpy as np + +from p13 import compMean #这种方式引用在使用函数时,前面必须加文件名 compMean.compMean(x) +# import compMean 这种方式引用,使用函数时,前面不用加文件名 +a=2 +b=4 +x=[7,38,4,23,18] +x=np.mat(x) +y=a*x + b +xmu=compMean.compMean(x) +ymu=compMean.compMean(y) +print('a * Xmu + b \t= %s \n'%(a * xmu + b)) +print('Ymu \t\t= %.2f \n'%ymu) diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p15.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p15.py" new file mode 100644 index 0000000..7518a45 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p15.py" @@ -0,0 +1,13 @@ +import numpy as np +from p13 import compMean +from p13 import compVariance + +x= [7, 38, 4, 23, 18] +x=np.mat(x) +x2= np.square(x) +# print(x2) +x2mu= compMean.compMean(x2) +xmu = compMean.compMean(x) +xvar= compVariance.compVariance(x) +print('The Variance of X \t= %.2f \n'%xvar) +print('E[X^2]-E[X]^2 \t\t= %.2f \n'%(x2mu - np.square(xmu))) \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p16.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p16.py" new file mode 100644 index 0000000..0e99490 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p16.py" @@ -0,0 +1,48 @@ +import numpy as np +import matplotlib.pyplot as plt +import numpy.linalg +from scipy.linalg import sqrtm + +# +def getSigmaEllipse(x,c,nsig,n): + # if nargin==4: #nargin 在matlab中表示函数输入参数的个数 + inc=2 * np.pi/n + # else: + # inc=np.pi/30 + # return inc + r=sqrtm(c) + phi=np.arange(0,(2*np.pi),inc) #生成起始为0,终止为(2*np.pi),步长为inc的矩阵,不包括终值 + b=[2*np.pi,0] + phi = np.hstack((phi, b)) #按行合并 + phi=np.mat(phi) + z = np.vstack((np.cos(phi), np.sin(phi))) + z=np.mat(z) + a=nsig * r * z + e=np.zeros_like(a) + e[0,:]=a[0,:] +x[0] + e[1,:]=a[1,:] +x[1] + return e + +mu=[0,0] +sigmax=5 +sigmay=7 +rho=0.2 +sigmaxy=sigmax * sigmay * rho +Sigma=[[np.square(sigmax),sigmaxy],[sigmaxy,np.square(sigmay)]] +# print(Sigma) +# Sigma=np.mat(Sigma) +ellipsis=getSigmaEllipse(mu,Sigma,1,100) + +plt.figure('The 1-sigma ellipse') +# plt.hold() +plt.plot(ellipsis[0,:],ellipsis[1,:],'ro',linewidth=3,markersize=15) +# plt.show() +plt.plot(mu[0], mu[1], 'gx',linewidth=10,markersize=10) +plt.xlabel('x') +plt.ylabel('y') +plt.grid(which='both') +plt.minorticks_on() +plt.title('σx = %.1f, σy = %.1f, ρ = %.1f'%(sigmax, sigmay, rho)) +plt.xlim(-5.5,5.5,0.5) +plt.ylim(-5.5,5.5) +plt.show() \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p2.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p2.py" new file mode 100644 index 0000000..8df2cb0 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p2.py" @@ -0,0 +1,60 @@ +import matplotlib.pyplot as plt +import numpy as np +# q=[0,0,0,0,0] +def sense(p,world,pHit,pMiss): + q=np.zeros(len(p)) + size=int(len(p)) + obs = np.zeros(size) + for i in range(size): + if "red"==world[i]: + hit=1 + else: + hit=0 + obs[i]=hit*pHit+(1-hit)*pMiss + q[i]=p[i]*(hit*pHit+(1-hit)*pMiss) + # q.index(q[i]) + S=sum(q) + for i in range(size): + q[i]=q[i]/S + print(q) + + plt.figure('The Prior distribution') + plt.bar(x=(0,1,2,3,4),height=p,color='g') + plt.ylabel("Probability of being at the positon") + plt.xlabel("Position") + plt.ylim(0,0.5) + + plt.figure('Observation model') + plt.bar(x=(0, 1, 2, 3, 4), height=obs, color='b') + plt.ylabel("Probability of being at the positon") + plt.xlabel("Position") + plt.ylim(0, 0.9) + + plt.figure('The Posterior distribution') + plt.bar(x=(0, 1, 2, 3, 4), height=q, color='red') + plt.ylabel("Probability of being at the positon") + plt.xlabel("Position") + plt.ylim(0, 0.5) + + plt.figure('Plot all') + plt.subplot(311) + plt.bar(x=(0,1,2,3,4),height=p,color='red') + plt.ylabel('Probability') + plt.ylim(0,0.5) + plt.subplot(312) + plt.bar(x=(0,1,2,3,4),height=obs) + plt.ylabel('Likelihood') + plt.ylim(0, 0.9) + plt.subplot(313) + plt.bar(x=(0,1,2,3,4),height=q) + plt.xlabel('Position') + plt.ylabel('Probability') + plt.ylim(0,0.5) + plt.show() + +world=["green","red","red","green","green"] +p=[0.2,0.2,0.2,0.2,0.2] +pHit=0.6 +pMiss=0.2 +sense(p,world,pHit,pMiss) + diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p3.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p3.py" new file mode 100644 index 0000000..b468d57 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p3.py" @@ -0,0 +1,65 @@ +import numpy as np +import matplotlib.pyplot as plt + +def sence(p,z,world,pHit,pMiss): + q=np.zeros(len(p)) + for i in range(0,len(p)): + if z==world[i]: + hit=1 + else: + hit=0 + q[i]=p[i]* (hit * pHit+ (1-hit) * pMiss) + S=sum(q) + for i in range(len(q)): + q[i]=q[i]/S + return q + +def p3plot(): + plt.ion() + plt.figure('Plot all') + plt.subplot(3, 1, 1) + plt.cla() + plt.bar(x=(1, 2, 3, 4, 5), height=p) + plt.ylabel('Prior') + plt.ylim(0, 0.5) + plt.title('Measurement=%s' % measurements[i]) + + plt.subplot(3, 1, 2) + obs = np.zeros(len(world)) + for j in range(0, len(world)): + if measurements[i] == world[j]: + hit = 1 + else: + hit = 0 + obs[j] = hit * pHit + (1 - hit) * pMiss + plt.cla() + plt.bar(x=(1, 2, 3, 4, 5), height=obs) + plt.ylabel('Observation') + plt.ylim(0, 0.9) + + plt.subplot(3, 1, 3) + plt.cla() + plt.bar(x=(1, 2, 3, 4, 5), height=q) + plt.xlabel('Posterior') + plt.ylabel('Posterior') + plt.ylim(0, 0.5) + # plt.pause(0.5) + plt.ioff() + plt.show() + +world=['green', 'red', 'red', 'green', 'green'] +p=[0.2,0.2,0.2,0.2,0.2] +measurements=['red','red','green'] +pHit=0.6 +pMiss=0.2 +plt.ion() +for i in range(0,len(measurements)): + q=sence(p,measurements[i],world,pHit,pMiss) + p3plot() + # plt.pause(0.5) + p=q +print(p) +p3plot() +# plt.pause(0.5) +# plt.ioff() +# plt.show() \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p4.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p4.py" new file mode 100644 index 0000000..9a81f38 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p4.py" @@ -0,0 +1,11 @@ +p=[1/9, 1/3, 1/3, 1/9, 1/9] +u=6 +def move(p,u): + n=len(p)# n=int(len(p)) + q=[] #numpy.zeros(n) + for i in range(1,n+1): + x,y=divmod(i-1-u,n) + q.append(p[y]) + print("Before movtion:\n",p) + print("After movtion:\n",q) +move(p,u) diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p5.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p5.py" new file mode 100644 index 0000000..70b4735 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p5.py" @@ -0,0 +1,26 @@ +import numpy as np +p=[0, 0.5, 0, 0.5, 0] +u=2 #表示小车前进的格数 +pExact=0.8 +pOvershoot=0.1 +pUndershoot=0.1 +def move(p,u,pExact,pOvershoot,pUndershoot): + n=len(p) + q=np.zeros(n) + for i in range(1,n+1): + l=i-1 + x,y=divmod(i-1-u,n) + # print(y) + q[l]=pExact*p[y] + # q.append(pExact*p[y]) #在正确的情况下,所在格子的概率 + # print(q) + x,y=divmod(i-2-u,n) + q[l]=q[l]+pOvershoot*p[y] + # q.index(q[l]+pOvershoot*p[y]) #加上超过格子的误差 + x, y = divmod(i - u, n) + q[l] = q[l] + pUndershoot * p[y] + # q.index(q[l]+pUndershoot*p[y])#加上不足格子的误差 + print(p) + print(q) + # q.append(q) +move(p,u,pExact,pOvershoot,pUndershoot) \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p6.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p6.py" new file mode 100644 index 0000000..6c37d93 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p6.py" @@ -0,0 +1,38 @@ +import numpy as np +import matplotlib.pyplot as plt +p=[1, 0, 0, 0, 0] +u=1 +step=20 +pExact=0.8 +pOvershoot=0.1 +pUndershoot=0.1 +# n=len(p) +# q = np.zeros(n) +def move(p,u,pExact,pOvershoot,pUndershoot): + n=len(p) + q = np.zeros(n) + for i in range(1, n + 1): + l = i - 1 + x, y = divmod(i - 1 - u, n) + q[l] = pExact * p[y] + x, y = divmod(i - 2 - u, n) + q[l] = q[l] + pOvershoot * p[y] + x, y = divmod(i - u, n) + q[l] = q[l] + pUndershoot * p[y] + return q +fig1=plt.figure(figsize=(10,10),dpi=80) +plt.ion() #开启交互模式 +# q=move(p,u,pExact,pOvershoot,pUndershoot) +for i in range(1,step+1): + print(i) + p=move(p,u,pExact,pOvershoot,pUndershoot) + print(p) + plt.cla() + plt.bar(x=(1,2,3,4,5),height=p) + plt.title('step=%s'%i) + plt.ylim(0,1) + plt.ylabel('Probability') + plt.pause(0.5) +plt.ioff()#关闭交互模式,如果不关闭图像就会一闪而过,不会长留 +plt.show() + diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p7.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p7.py" new file mode 100644 index 0000000..3ee271e --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p7.py" @@ -0,0 +1,41 @@ +import numpy as np +import matplotlib.pyplot as plt +p=[1, 0, 0, 0, 0] +u=1 +step=100 +pExact=0.8 +pOvershoot=0.1 +pUndershoot=0.1 +entropy=np.zeros(step) +def move(p,u,pExact,pOvershoot,pUndershoot): + n=len(p) + q = np.zeros(n) + for i in range(1, n + 1): + l = i - 1 + x, y = divmod(i - 1 - u, n) + q[l] = pExact * p[y] + x, y = divmod(i - 2 - u, n) + q[l] = q[l] + pOvershoot * p[y] + x, y = divmod(i - u, n) + q[l] = q[l] + pUndershoot * p[y] + return q +# q=move(p,u,pExact,pOvershoot,pUndershoot) +plt.ion() +for i in range(1,step+1): + p=move(p,u,pExact,pOvershoot,pUndershoot) + entropy[i-1]=-sum(p * np.log2(p)) + print(i) + print(p) + # print(entropy) + # print(p) + # plt.cla() + # x=plt.xlim(1,step) +y = entropy +plt.plot(y,'r^',linewidth=0.5,markersize=6)#,shap='-',linewidth=2,color='g' +plt.plot(y,'g',linewidth=2,markersize=2)#,shap=':',linewidth=1.5,color='r' + # plt.xlim(1,step,10) +plt.xlabel('Motion step') +plt.ylabel('Entropy') + # plt.pause(0.5) #每次图表显示间隔的时间 +plt.ioff() +plt.show() \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p8.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p8.py" new file mode 100644 index 0000000..4821ce2 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p8.py" @@ -0,0 +1,97 @@ +import numpy as np +import matplotlib.pyplot as plt +def sense(p,z,world,pHit,pMiss): + size=int(len(p)) + # obs = np.zeros(size) + q=np.zeros(len(p)) + for i in range(size): + if z==world[i]: + hit=1 + else: + hit=0 + # obs[i]=hit*pHit+(1-hit)*pMiss + q[i]=p[i]*(hit*pHit+(1-hit)*pMiss) + # q.index(q[i]) + S=sum(q) + for i in range(size): + q[i]=q[i]/S + # print(q) + return q +def move(p,u,pExact,pOvershoot,pUndershoot): + n=len(p) + q = np.zeros(n) + for i in range(1, n + 1): + l = i - 1 + x, y = divmod(i - 1 - u, n) + q[l] = pExact * p[y] + x, y = divmod(i - 2 - u, n) + q[l] = q[l] + pOvershoot * p[y] + x, y = divmod(i - u, n) + q[l] = q[l] + pUndershoot * p[y] + return q +p=[0.2, 0.2, 0.2, 0.2, 0.2] +world=['green','red','red','green','green'] +#First configuration of meas. +# measurements=['red','green'] +# motions=[1,1] +#Sencond configuration +measurements=['red','green','green'] +motions=[1,1,1] +#Third configuration +# measurements=['green','red'] +# motions=[1,1] +#Fourth configuration +# measurements=['green''green'] +# motions=[3,1] +#Fifth configuration,It is impossible case +# measurements=['red','red'] +# motions=[3,1] +#Sixth configuration,It is impossible case +# measurements=['red','red'] +# motions=[2,1] +pHit=0.6 +pMiss=0.2 +pExact=0.8 +pOvershoot=0.1 +pUndershoot=0.1 +entropy=np.zeros((2,len(motions))) +motions_size=len(motions) +for i in range(len(measurements)): + #Updara by sensing + p=sense(p,measurements[i],world,pHit,pMiss) + entropy[0,i]=-sum(p*np.log2(p)) + p=move(p,motions[i],pExact,pOvershoot,pUndershoot) + entropy[1,i]=-sum(p*np.log2(p)) +print('The final posterior:') +print(p) +print('The final entropy:') +print(entropy[-1,-1]) + +print(len(motions)) + +plt.ion() +h1=plt.figure(1) +plt.cla() +hAllBar=plt.bar(x=(1,2,3,4,5),height=p,width=1,facecolor='g',edgecolor='black') +p=p.tolist() +pMaxCell=max(p) +iMaxCell=p.index(pMaxCell) #提取不到最大值的位置 +pMax=np.zeros(len(p)) +pMax[iMaxCell]=pMaxCell +hMaxBar=plt.bar(x=(1,2,3,4,5),height=pMax,width=1,facecolor='r',edgecolor='black') +plt.xlabel('Index of cell') +plt.ylabel('Posterior') +plt.xlim(0,5.5,1) +# plt.show(h1) + +h2=plt.figure(2) +plt.plot(range(1,motions_size+1),entropy[0,:],'bh',linewidth=3,markersize=10) +plt.plot(range(1,motions_size+1),entropy[1,:],'rx',linewidth=3,markersize=10) +print(entropy[0,:]) +print(entropy[1,:]) +plt.xlim(-1,(len(motions)+1)) +plt.xlabel('Step') +plt.ylabel('Entropy') +plt.legend(('After sensing', 'Before sensing'),loc='upper right') +plt.ioff() +plt.show() \ No newline at end of file diff --git "a/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p9.py" "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p9.py" new file mode 100644 index 0000000..1e46d50 --- /dev/null +++ "b/python\344\277\256\346\224\271\345\274\240\351\223\201\346\265\267/p9.py" @@ -0,0 +1,101 @@ +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D +def getPositon(a): + raw, column = a.shape # get the matrix of a raw and column + positon = np.argmax(a) # get the index of max in the a + # print(positon) + r, c = divmod(positon , column) + return r,c + +def move(p,u,pMoveCorrect): + nRow=int(len(p)) + nCol=int(len(p[0])) + q=np.zeros(ones_size) + for r in range(1,nRow+1): + for c in range(1,nCol+1): + q[r-1,c-1]=pMoveCorrect * p[np.mod(r-1-u[0],nRow),np.mod(c-1-u[1],nCol)]+ (1-pMoveCorrect)* p[r-1,c-1] + # return q + return q + +world = (('red', 'green', 'green', 'red', 'red'), +('red', 'red', 'green', 'red', 'red'), +('red', 'red', 'green', 'green', 'red'), +('red', 'red', 'red', 'red', 'red')) +# print(world) +# print(len(world)) +# print(len(world[1])) +nRow = len(world) +nCol = len(world[1]) +ones_size=(nRow,nCol) +ones=np.ones(ones_size) +step={ + 'stop':[0,0], + 'right':[0,1], + 'left':[0,-1], + 'down':[1,0], + 'up':[-1,0] +} +pMoveCorrect = 0.8 +pStart = 0.7 +p = (1 - pStart) / (nRow * nCol - 1) * ones +# Fisrt configuration +# p[2,1]=pStart +# motions=step['right'] +# Second configuration +p[0,2]=pStart +motions=step['up'] + +q=move(p,motions,pMoveCorrect) +print('The Prior:\n',p) +print('The probability after moving:\n',q) +r,c=getPositon(q) +print('The largest probability %s occurs at cell(%s,%s)\n'%(q[r,c],r,c)) + +plt.ion() +h=plt.figure(1) +ax=Axes3D(h) +# x=np.arange(1,nRow+1,1) +# y=np.arange(1,nCol+1,1) +# z=p.flatten() +# x=x.flatten() +# y=y.flatten() +# dx_size=(nRow,nCol) +# dx=np.ones(dx_size) +# dy=dx.copy() +# dz=p.flatten() +# ax.bar3d(x,y,z,dx,dy,dz) +# plt.show() + +ly= len(p[0]) #5 # Work out matrix dimensions +lx= len(p[:,0]) #4 +xpos = np.arange(0,lx,1) # Set up a mesh of positions +ypos = np.arange(0,ly,1) +xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25) +xpos = xpos.flatten() # Convert positions to 1D array +ypos = ypos.flatten() +zpos = np.zeros(lx*ly) + +dx = np.ones_like(zpos) +dy = dx.copy() +dz = p.T.flatten() +ax.bar3d(xpos,ypos,zpos, dx, dy, dz) + +h1=plt.figure(2) +ax=Axes3D(h1) +ly= len(q[0]) #5 # Work out matrix dimensions +lx= len(q[:,0]) #4 +xpos = np.arange(0,lx,1) # Set up a mesh of positions +ypos = np.arange(0,ly,1) +xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25) +xpos = xpos.flatten() # Convert positions to 1D array +ypos = ypos.flatten() +zpos = np.zeros(lx*ly) + +dx = np.ones_like(zpos) +dy = dx.copy() +dz = q.T.flatten() +# color=plt.cm. +ax.bar3d(xpos,ypos,zpos, dx, dy, dz) +plt.ioff() +plt.show()