Projet_Boites/Probas.py
2023-06-03 22:57:02 +02:00

266 lines
9.3 KiB
Python
Executable file

#!/usr/bin/python3
from random import random
from math import floor, sqrt
from statistics import mean, variance
from matplotlib import pyplot as plt
from pylab import *
import numpy as np
import matplotlib.pyplot as pt
def simulate_NFBP(N):
"""
Tries to simulate T_i, V_i and H_n for N packages of random size.
"""
i = 0 # Nombre de boites
R = [0] # Remplissage de la i-eme boite
T = [0] # Nombre de paquets de la i-eme boite
V = [0] # Taille du premier paquet de la i-eme boite
H = [] # Rang de la boite contenant le n-ieme paquet
for n in range(N):
size = random()
if R[i] + size >= 1:
# Il y n'y a plus de la place dans la boite pour le paquet.
# On passe à la boite suivante (qu'on initialise)
i += 1
R.append(0)
T.append(0)
V.append(0)
R[i] += size
T[i] += 1
if V[i] == 0:
# C'est le premier paquet de la boite
V[i] = size
H.append(i)
return {
"i": i,
"R": R,
"T": T,
"V": V,
"H": H
}
def stats_NFBP(R, N):
"""
Runs R runs of NFBP (for N packages) and studies distribution, variance, mean...
"""
print("Running {} NFBP simulations with {} packages".format(R, N))
I = []
H = [[] for _ in range(N)] # List of empty lists
for i in range(R):
sim = simulate_NFBP(N)
I.append(sim["i"])
for n in range(N):
H[n].append(sim["H"][n])
print("Mean number of boxes : {} (variance {})".format(mean(I), variance(I)))
for n in range(N):
print("Mean H_{} : {} (variance {})".format(n, mean(H[n]), variance(H[n])))
def stats_NFBP_iter(R, N):
"""
Runs R runs of NFBP (for N packages) and studies distribution, variance, mean...
Calculates stats during runtime instead of after to avoid excessive memory usage.
"""
P=R*N
print("Running {} NFBP simulations with {} packages".format(R, N))
ISum = 0
IVarianceSum = 0
HSum = [0 for _ in range(N)]
HSumVariance = [0 for _ in range(N)]
Sum_T=[0 for _ in range(N)]
Sum_V=[0 for _ in range(N)]
for i in range(R):
sim = simulate_NFBP(N)
ISum += sim["i"]
IVarianceSum += sim["i"]**2
for n in range(N):
HSum[n] += sim["H"][n]
HSumVariance[n] += sim["H"][n]**2
T=sim['T']
V=sim['V']
for i in range(N):
T.append(0)
V.append(0)
Sum_T=[x+y for x,y in zip(Sum_T,T)]
Sum_V=[x+y for x,y in zip(Sum_V,V)]
#we use round to approximate variations of continuous variable V
# Sum_V= round(sim['V'],2))
Sum_T=[x/R for x in Sum_T]
Sum_V=[round(x/R,2) for x in Sum_V]
print(Sum_V)
I = ISum/R
IVariance = sqrt(IVarianceSum/(R-1) - I**2)
print("Mean number of boxes : {} (variance {})".format(I, IVariance),'\n')
print(" {} * {} iterations of T".format(R,N),'\n')
for n in range(N):
Hn = HSum[n]/R # moyenne
HVariance = sqrt(HSumVariance[n]/(R-1) - Hn**2) # Variance
print("Index of box containing the {}th package (H_{}) : {} (variance {})".format(n, n, Hn, HVariance))
HSum=[x/R for x in HSum]
print(HSum)
#Plotting
fig = plt.figure()
#T plot
x = np.arange(N)
print(x)
ax = fig.add_subplot(221)
ax.bar(x,Sum_T, width=1,label='Empirical values', edgecolor="blue", linewidth=0.7,color='red')
ax.set(xlim=(0, N), xticks=np.arange(0, N),ylim=(0,3), yticks=np.linspace(0, 3, 5))
ax.set_ylabel('Items')
ax.set_xlabel('Boxes (1-{})'.format(N))
ax.set_title('T histogram for {} packages (Number of packages in each box)'.format(P))
ax.legend(loc='upper left',title='Legend')
#V plot
bx = fig.add_subplot(222)
bx.bar(x,Sum_V, width=1,label='Empirical values', edgecolor="blue", linewidth=0.7,color='orange')
bx.set(xlim=(0, N), xticks=np.arange(0, N),ylim=(0, 1), yticks=np.linspace(0, 1, 10))
bx.set_ylabel('First item size')
bx.set_xlabel('Boxes (1-{})'.format(N))
bx.set_title('V histogram for {} packages (first package size of each box)'.format(P))
bx.legend(loc='upper left',title='Legend')
#H plot
#We will simulate this part for a asymptotic study
cx = fig.add_subplot(223)
cx.bar(x,HSum, width=1,label='Empirical values', edgecolor="blue", linewidth=0.7,color='green')
cx.set(xlim=(0, N), xticks=np.arange(0, N),ylim=(0, 10), yticks=np.linspace(0, N, 5))
cx.set_ylabel('Box ranking of n-item')
cx.set_xlabel('n-item (1-{})'.format(N))
cx.set_title('H histogram for {} packages'.format(P))
xb=linspace(0,N,10)
yb=Hn*xb/10
wb=HVariance*xb/10
cx.plot(xb,yb,label='Theoretical E(Hn)',color='brown')
cx.plot(xb,wb,label='Theoretical V(Hn)',color='purple')
cx.legend(loc='upper left',title='Legend')
plt.show()
def simulate_NFDBP(N):
"""
Tries to simulate T_i, V_i and H_n for N packages of random size.
"""
i = 0 # Nombre de boites
R = [0] # Remplissage de la i-eme boite
T = [0] # Nombre de paquets de la i-eme boite
V = [0] # Taille du premier paquet de la i-eme boite
H = [] # Rang de la boite contenant le n-ieme paquet
for n in range(N):
size = random()
R[i] += size
T[i] += 1
if R[i] + size >= 1:
# Il y n'y a plus de la place dans la boite pour le paquet.
# On passe à la boite suivante (qu'on initialise)
i += 1
R.append(0)
T.append(0)
V.append(0)
if V[i] == 0:
# C'est le premier paquet de la boite
V[i] = size
H.append(i)
return {
"i": i,
"R": R,
"T": T,
"V": V,
"H": H
}
def stats_NFDBP(R, N,t_i):
"""
Runs R runs of NFDBP (for N packages) and studies distribution, variance, mean...
"""
print("Running {} NFDBP simulations with {} packages".format(R, N))
P=N*R
I = []
H = [[] for _ in range(N)] # List of empty lists
T=[]
Tk=[[] for _ in range(N)]
Ti=[]
#First iteration to use zip after
sim=simulate_NFDBP(N)
Sum_T=sim["T"]
for i in range(R):
sim = simulate_NFDBP(N)
I.append(sim["i"])
for n in range(N):
H[n].append(sim["H"][n])
Tk[n].append(sim["T"][n])
T=sim["T"]
Ti.append(sim["T"])
for k in range(N):
Sum_T.append(0)
T.append(0)
Sum_T=[x+y for x,y in zip(Sum_T,T)]
Sum_T=[x/R for x in Sum_T] #Experimental [Ti=k]
Sum_T=[x*100/(sum(Sum_T)) for x in Sum_T] #Pourcentage de la repartition des items
print(Tk)
print("Mean number of boxes : {} (variance {})".format(mean(I), variance(I)))
for n in range(N):
print("Mean H_{} : {} (variance {})".format(n, mean(H[n]), variance(H[n])))
print("Mean T_{} : {} (variance {})".format(k, mean(Sum_T), variance(Sum_T)))
#Plotting
fig = plt.figure()
#T plot
x = np.arange(N)
print(x)
ax = fig.add_subplot(121)
ax.bar(x,Sum_T, width=1,label='Empirical values', edgecolor="blue", linewidth=0.7,color='red')
ax.set(xlim=(0, N), xticks=np.arange(0, N),ylim=(0,3), yticks=np.linspace(0, 3, 5))
ax.set_ylabel('Items')
ax.set_xlabel('Boxes (1-{})'.format(N))
ax.set_title('T histogram for {} packages (Number of packages in each box)'.format(P))
ax.legend(loc='upper left',title='Legend')
plt.show()
#Mathematical P(Ti=k) plot
x = np.arange(N)
print(x)
ax = fig.add_subplot(122)
ax.hist(x,Sum_T, width=1,label='Empirical values', edgecolor="blue", linewidth=0.7,color='red')
ax.set(xlim=(0, N), xticks=np.arange(0, N),ylim=(0,3), yticks=np.linspace(0, 3, 5))
ax.set_ylabel('Items')
ax.set_xlabel('Boxes (1-{})'.format(N))
ax.set_title('T histogram for {} packages (Number of packages in each box)'.format(P))
ax.legend(loc='upper left',title='Legend')
plt.show()
N = 10 ** 1
sim = simulate_NFBP(N)
print("Simulation NFBP pour {} packaets. Contenu des boites :".format(N))
for j in range(sim["i"] + 1):
remplissage = floor(sim["R"][j] * 100)
print("Boite {} : Rempli à {} % avec {} paquets. Taille du premier paquet : {}".format(j, remplissage, sim["T"][j],
sim["V"][j]))
print()
stats_NFBP(10 ** 3, 10)
N = 10 ** 1
sim = simulate_NFDBP(N)
print("Simulation NFDBP pour {} packaets. Contenu des boites :".format(N))
for j in range(sim["i"] + 1):
remplissage = floor(sim["R"][j] * 100)
print("Boite {} : Rempli à {} % avec {} paquets. Taille du premier paquet : {}".format(j, remplissage,
sim["T"][j],
sim["V"][j]))
print()
stats_NFBP_iter(10**3, 10)
#stats_NFDBP(10 ** 3, 10)
#
#pyplot.plot([1, 2, 4, 4, 2, 1], color = 'red', linestyle = 'dashed', linewidth = 2,
#markerfacecolor = 'blue', markersize = 5)
#pyplot.ylim(0, 5)
#pyplot.title('Un exemple')
#show()