6 from itertools import *
7 from scipy import optimize as opt
8 from copy import deepcopy
20 distanceEmmissionMax = 30
26 fichier_init="config_initiale_default.txt"
30 # construction du graphe
32 lg = [(0, 1, 22.004323820359151), (0, 2, 28.750632705280324), (0, 3, 29.68069293796183), (0, 4, 8.547146256271331), (0, 5, 28.079672647730469), (0, 7, 23.017867703525138), (0, 8, 6.1268526078857208), (0, 9, 24.573433868296771), (1, 0, 22.004323820359151), (1, 2, 18.807277287689722), (1, 3, 18.982897767602783), (1, 4, 16.848855991756174), (1, 5, 17.042671653231526), (1, 6, 16.410544777532913), (1, 7, 25.598808236367063), (1, 8, 20.175759189503321), (1, 9, 12.843763853990932), (2, 0, 28.750632705280324), (2, 1, 18.807277287689722), (2, 3, 1.0957062702237066), (2, 4, 29.159997765424084), (2, 5, 1.8557839901886808), (2, 6, 23.122260476726876), (2, 9, 6.052562826627808), (3, 0, 29.68069293796183), (3, 1, 18.982897767602783), (3, 2, 1.0957062702237066), (3, 4, 29.884008054261855), (3, 5, 1.9922790489539697), (3, 6, 22.479228556182363), (3, 9, 6.4359869969688059), (4, 0, 8.547146256271331), (4, 1, 16.848855991756174), (4, 2, 29.159997765424084), (4, 3, 29.884008054261855), (4, 5, 28.006189408396626), (4, 7, 15.774839848636024), (4, 8, 3.6206480052249144), (4, 9, 23.804744370383144), (5, 0, 28.079672647730469), (5, 1, 17.042671653231526), (5, 2, 1.8557839901886808), (5, 3, 1.9922790489539697), (5, 4, 28.006189408396626), (5, 6, 21.492976178079076), (5, 8, 29.977996181215822), (5, 9, 4.4452006140146185), (6, 1, 16.410544777532913), (6, 2, 23.122260476726876), (6, 3, 22.479228556182363), (6, 5, 21.492976178079076), (6, 9, 20.04488615603487), (7, 0, 23.017867703525138), (7, 1, 25.598808236367063), (7, 4, 15.774839848636024), (7, 8, 16.915923579829141), (8, 0, 6.1268526078857208), (8, 1, 20.175759189503321), (8, 4, 3.6206480052249144), (8, 5, 29.977996181215822), (8, 7, 16.915923579829141), (8, 9, 25.962918470558208), (9, 0, 24.573433868296771), (9, 1, 12.843763853990932), (9, 2, 6.052562826627808), (9, 3, 6.4359869969688059), (9, 4, 23.804744370383144), (9, 5, 4.4452006140146185), (9, 6, 20.04488615603487), (9, 8, 25.962918470558208)]
35 #lg= [(0,1,23),(1,0,15),(1,2,45)]
39 return mt.sqrt(sum([(d1[t]-d2[t])**2 for t in d1]))
46 l = [(random()*coteCarre, random()*coteCarre) for _ in range(n)]
47 for io in range(len(l)) :
48 for ie in range(len(l)) :
50 dist = mt.sqrt((l[io][0]-l[ie][0])**2 + (l[io][1]-l[ie][1])**2)
51 if dist <= distanceEmmissionMax :
52 G.add_edge(io,ie,weight=dist)
53 G.add_edge(ie,io,weight=dist)
54 test = not(any([ not(nx.has_path(G,o,sink)) for o in G.nodes() if sink in G.nodes() and o != sink]))
58 def afficheGraph(G,l,tx,ty,sink):
60 img = cv.CreateImage ((tx, ty), 32, 3)
61 cv.Rectangle(img, (0,0),(tx,ty), cv.Scalar(255,255,255), thickness=-1)
63 u = float(tx)/(coteCarre + 2*distanceEmmissionMax)
64 return(int(distanceEmmissionMax*u + x * u),int(distanceEmmissionMax*u + y * u))
65 for i in set(range(len(l)))-set([sink]):
68 demx = distanceEmmissionMax*tx/(coteCarre+2*distanceEmmissionMax)
69 cv.Circle(img, (pix,piy),demx, cv.Scalar(125,125,125))
71 for i in set(range(len(l)))-set([sink]):
74 cv.Circle(img, (pix,piy),r, cv.Scalar(125,125,125),thickness=-1)
80 cv.Rectangle(img, (pix-r/2,piy-r/2),(pix+r/2,piy+r/2), cv.Scalar(125,125,125), thickness=-1)
82 for i in range(len(l)):
83 for j in range(len(l)):
85 if np.linalg.norm(np.array(l[i])-np.array(l[j])) < distanceEmmissionMax :
87 pixi,piyi = px((xi,yi))
89 pixj,piyj = px((xj,yj))
90 cv.Line(img, (pixi,piyi), (pixj,piyj), cv.Scalar(125,125,125))
94 for i in range(len(l)):
98 textColor = (0, 0, 255) # red
99 font = cv2.FONT_HERSHEY_SIMPLEX
101 cv2.putText(img, str(i), (pix-r/4,piy-r/2),font, 3.0, textColor)#,thickn """
102 cv.SaveImage("SensorNetwork.png",img)
105 G.add_weighted_edges_from(lg)
106 #print nx.is_strongly_connected(G)
112 #(G,l) = genereGraph()
114 #V = list(set(sample(N,int(len(N)*vrate)))-set([sink]))
115 V = list(set(N)-set([sink]))
117 print "source",source
120 #afficheGraph(G,l,500,500,sink)
130 #print G.edges(data=True)
131 #TODO afficher le graphe et etre sur qu'il est connexe
137 L = range(len(G.edges()))
138 d = [di['weight'] for (_,_,di) in G.edges(data=True)]
145 assert l in L, " pb de dimennsion de l: "+str(l)+ " "+ str(L)
157 a = [[ail(i,l) for l in L ] for i in xrange(n)]
158 aplus = [[1 if ail(i,l) > 0 else 0 for l in L ] for i in xrange(n)]
159 amoins = [[1 if ail(i,l) < 0 else 0 for l in L ] for i in xrange(n)]
176 cs = [alpha + beta*(di**path_loss_exp) for di in d]
199 return cmp(x1[1],x2[1])
209 def AfficheVariation (up,vp,lap,wp,thetap,etap,qp,Psp,Rhp,xp,valeurFonctionDualep):
210 global u, v, la, w, theta , q, Ps, Rh, eta, x,valeurFonctionDuale
212 print "du=",distance(u,up),
213 print "dv=",distance(v,vp),
214 print "dlambda=",distance(la,lap),
215 print "dw=",distance(w,wp),
216 print "dtheta=",abs(theta-thetap),
217 print "deta=",distance(eta,etap),
218 print "dq=",distance(q,qp),
219 print "dPs=",distance(Ps,Psp),
220 print "dRh=",distance(Rh,Rhp),
221 print "dx=",distance(x,xp),
222 print "dL=",abs(valeurFonctionDuale-valeurFonctionDualep),"\n"
225 valeurFonctionDuale = 0
228 r = x if (x >0 and x <= 1) else -1
229 #print "ds entre0et1 x et r", x,r
234 r = x if x >0 else -1
235 #print "ds xpos x et r", x,r
239 return x if x >= 0 else -1
242 def armin(f,xini,xr,args):
243 #xpos = lambda x : x if x > 0 else -1
246 r= opt.fmin_cobyla(f,xini,cons=[xpos],args=args,consargs=(),rhoend=errorD/100,iprint=0,maxfun=nbiter)
248 r = opt.fmin_cobyla(f,xini,[xposounul],args,consargs=(),rhoend=errorD/100,iprint=0,maxfun=nbiter)
250 r = opt.fmin_cobyla(f,xini,[entre0et1],args,consargs=(),rhoend=errorD/100,iprint=0,maxfun=nbiter)
261 return omega/(mt.pow(k,0.5))
266 return omega/mt.sqrt(k)
271 def maj(k,maj_theta,mxg,idxexp,comppsh=False):
272 # initialisation des operateurs lagrangiens
273 global u, v, la, w, theta , q, Ps, Rh, eta, x, valeurFonctionDuale
281 if not ASYNC or random() < taux_succes:
282 s = eta[(h,i)]-sum([a[i][l]*x[(h,l)] for l in L])
284 print "ds calcul u",abs(s),idxexp
286 smax = max(smax,abs(s))
287 up[(h,i)] = u[(h,i)]-theta*s
295 if not ASYNC or random() < taux_succes:
296 s = Rh[h]- mt.log(float(sigma2)/D)/(gamma*mt.pow(Ps[h],float(2)/3))
298 print "ds calcul v",abs(s),idxexp
300 smax = max(smax,abs(s))
301 vp[h] = max(0,v[h]-theta*s)
309 if not ASYNC or random() < taux_succes:
310 s = q[i]*Bi -sum([aplus[i][l]*cs[l]*sum([x[(h,l)] for h in V]) for l in L])-cr*sum([amoins[i][l]*sum([x[(h,l)] for h in V]) for l in L])-psi(Ps,i)
312 print "ds calcul la",abs(s),idxexp,i
314 smax = max(smax,abs(s))
315 resla = la[i]-theta*s
316 lap[i] = max(0,resla)
325 if not ASYNC or random() < taux_succes:
326 s = sum([a[i][l]*q[i] for i in N])
328 print "ds calcul w",abs(s),idxexp
330 smax = max(smax,abs(s))
331 wp[l] = w[l] + theta*s
337 thetap = maj_theta(k)
342 fa = sum([a[i][l]*w[l] for l in L]) - la[i]*Bi
347 if not ASYNC or random() < taux_succes:
348 n1 = dt.datetime.now()
349 c = -float(sum([a[i][l]*w[l] for l in L]) - la[i]*Bi)/(2*amplifieur)
350 n2 = dt.datetime.now()
351 #cp = armin(f_q,q[i],POS,tuple([i]))
352 n3 = dt.datetime.now()
353 tq += (n2-n1).microseconds
354 tqa += (n3-n2).microseconds
355 rep = epsilon if c <= 0 else c
366 #print psh,(gamma*mt.pow(psh,float(2)/3))
367 res= v[h]* mt.log(float(sigma2)/D)/(gamma*mt.pow(psh,float(2)/3)) +la[h]*psh + delta*mt.pow(psh,float(8)/3)
372 if not ASYNC or random() < taux_succes:
373 n1 = dt.datetime.now()
374 #calcul nouvelle solution
377 t= float(2*v[h]*mt.log(float(sigma2)/D))/(3*gamma*la[h])
378 rep = mt.pow(t,float(3)/5)
382 t= float(-3*la[h]+mt.sqrt(9*(la[h]**2)+64*delta*v[h]*mt.log(float(sigma2)/D)/gamma))/(16*delta)
383 rep = mt.pow(t,float(3)/5)
387 n2 = dt.datetime.now()
388 #cp = armin(f_Ps,Ps[h],POS,tuple([h]))
389 n3 = dt.datetime.now()
390 tp += (n2-n1).microseconds
391 tpa += (n3-n2).microseconds
402 etap[(h,i)] = etahi(h,i,Rh)
409 return delta*rh*rh-v[h]*rh-sum([u[(h,i)]*eta[(h,i)] for i in N])
411 if not ASYNC or random() < taux_succes:
412 rep = float(v[h])/(2*delta)
413 n1 = dt.datetime.now()
414 rep = float(v[h])/(2*delta)
415 n2 = dt.datetime.now()
416 #cp = armin(f_Rh,Rh[h],POS_NUL,tuple([h]))
417 n3 = dt.datetime.now()
418 tr += (n2-n1).microseconds
419 tra += (n3-n2).microseconds
420 Rhp[h] = 0 if rep < 0 else rep
430 r = delta*xhl*xhl + xhl*(cs[l]*sum([la[i]*aplus[i][l] for i in N]) +cr*sum([la[i]*amoins[i][l] for i in N])+sum([u[(h,i)]*a[i][l] for i in N]))
435 if not ASYNC or random() < taux_succes:
436 n1 = dt.datetime.now()
437 rep = -float(cs[l]*sum([la[i]*aplus[i][l] for i in N]) +cr*sum([la[i]*amoins[i][l] for i in N])+sum([u[(h,i)]*a[i][l] for i in N]))/(2*delta)
438 n2 = dt.datetime.now()
439 #cp = armin(f_x,x[(h,l)],POS_NUL,tuple([h,l]))
440 n3 = dt.datetime.now()
441 tx += (n2-n1).microseconds
442 txa += (n3-n2).microseconds
444 xp[(h,l)] = 0 if rep < 0 else rep
452 valeurFonctionDualep = 0
453 valeurFonctionDualep += sum([amplifieur*q[i]*q[i] for i in N])
454 valeurFonctionDualep += sum([sum([delta*(x[(h,l)]**2) for l in L]) for h in V])
455 valeurFonctionDualep += sum([delta*(Rh[h]**2) for h in V])
456 valeurFonctionDualep += sum([sum([u[(h,i)]*(sum([ a[i][l]*x[(h,l)] for l in L])- eta[(h,i)]) for i in N]) for h in V])
457 valeurFonctionDualep += sum([v[h]*(mt.log(float(sigma2)/D)/(gamma*mt.pow(Ps[h],float(2)/3)) - Rh[h]) for h in V])
458 valeurFonctionDualep += sum([la[i]*(psi(Ps,i) +sum([aplus[i][l]*cs[l]*sum([x[(h,l)] for h in V]) for l in L])+ cr*sum([ amoins[i][l]*sum([x[(h,l)] for h in V]) for l in L]) -q[i]*Bi) for i in N ])
459 valeurFonctionDualep += sum([w[l]*sum([a[i][l]*q[i] for i in N]) for l in L])
462 #AfficheVariation(up,vp,lap,wp,thetap,etap,qp,Psp,Rhp,xp,valeurFonctionDualep)
464 arret = abs(valeurFonctionDuale-valeurFonctionDualep)
466 return (up,vp,lap,wp,thetap,etap,qp,Psp,Rhp,xp,valeurFonctionDualep,arret,mxg,smax,tq+tp+tr+tx,tqa+tpa+tra+txa)
487 def initialisation():
488 global u, v, la, w, theta , q, Ps, Rh, eta, x,init
494 q[i] = 0.15 + random()*0.05
499 Ps[h] = 0.2+random()*0.3
503 Rh[vi] = 0.1 + random()*0.1
508 eta[(h,i)]= etahi(h,i,Rh)
518 # initialisation des operateurs lagrangiens
536 init = [deepcopy(q),deepcopy(Ps),deepcopy(Rh),deepcopy(eta),
537 deepcopy(x),deepcopy(u),deepcopy(v),deepcopy(la),deepcopy(w)]
541 def initialisation_():
542 global u, v, la, w, theta , q, Ps, Rh, eta, x,init
543 fd = open(fichier_init,"r")
548 (q,Ps,Rh,eta,x,u,v,la,w) = tuple([deepcopy(x) for x in init_p])
549 init = [deepcopy(q),deepcopy(Ps),deepcopy(Rh),deepcopy(eta),
550 deepcopy(x),deepcopy(u),deepcopy(v),deepcopy(la),deepcopy(w)]
554 def __evalue_maj_theta__(nbexp,out=False):
555 global u, v, la, w, theta , q, Ps, Rh, eta, x, valeurFonctionDuale
562 om = omega/(mt.pow(k,0.75))
565 for idxexp in range(nbexp):
577 while k < itermax and not arret :
579 (u,v,la,w,theta,eta,q,Ps,Rh,x,valeurFonctionDuale,ar,mxg,smax,ct,cta)=maj(k,__maj_theta,mxg,idxexp)
580 err = (max(q.values()) - min(q.values()))/min(q.values())
583 arret = err < errorq or ar < errorD
585 variation = "+" if smax > sm else "-"
586 if out : print variation,
590 errorq, "erreur sur F", ar, "et q:", q
592 if out : print "maxg=", mxg
593 mem = [deepcopy(q),deepcopy(Ps),deepcopy(Rh),deepcopy(eta),
594 deepcopy(x),deepcopy(u),deepcopy(v),deepcopy(la),deepcopy(w)]
598 #print "#########\n",mem,"\#########\n"
600 #print "#########m\n",mem,"\#########\n"
605 print "variation trop grande"
612 print "nbre d'iteration trop grand"
617 liste_arret += [(err, ar,k,errorD)]
619 print "###############"
621 print "###############"
625 #print (min(m),max(m),float(sum(m))/nbexp,m),m
626 #return (liste_arret,dur,dura)
627 return (liste_arret,dur)
630 def __une_seule_exp__(fichier_donees):
631 global u, v, la, w, theta , q, Ps, Rh, eta, x, valeurFonctionDuale
635 fichier = open(fichier_donees, "r")
639 instructions[l[0]] = eval(l[1])
640 u, v, la, w, q, Ps, Rh, eta, x, = instructions['u'], instructions['v'], instructions['la'], instructions['w'], instructions['q'], instructions['Ps'], instructions['Rh'], instructions['eta'], instructions['x']
647 om = omega/(mt.pow(k,0.75))
649 for idxexp in range(nbexp):
654 while k < itermax and not arret :
655 (u,v,la,w,theta,eta,q,Ps,Rh,x,valeurFonctionDuale,ar,mxg,smax)=maj(k,__maj_theta,mxg,idxexp)
656 errorq = (max(q.values()) - min(q.values()))/min(q.values())
657 arret = errorq < error
659 variation = "+" if smax > sm else "-"
662 print "k:",k,"erreur sur q", errorq, "et q:",q
665 print "variation trop grande"
672 print "nbre d'iteration trop grand"
677 print "###############"
679 print "###############"
682 print (min(m),max(m),float(sum(m))/nbexp,m),m
688 #__une_seule_exp__("config_initiale.py")
689 #pour evaluerle test d'arret
692 for k in list(np.logspace(-6, -3, num=15)):
694 listederes += __evalue_maj_theta__(5)
702 def __comparePsh_et_Psh_avec8_3__(nbexp,out=False):
704 global u, v, la, w, theta , q, Ps, Rh, eta, x, valeurFonctionDuale
711 om = omega/(mt.pow(k,0.75))
714 for idxexp in range(nbexp):
728 while k < itermax and not arret :
729 (u,v,la,w,theta,eta,q,Ps,Rh,x,valeurFonctionDuale,ar,mxg,smax,ct,cta)=maj(k,__maj_theta,mxg,idxexp)
730 err = (max(q.values()) - min(q.values()))/min(q.values())
733 arret = err < errorq or ar < errorD
735 variation = "+" if smax > sm else "-"
736 if out : print variation,
740 errorq, "erreur sur F", ar, "et q:", q
742 if out : print "maxg=", mxg
743 mem = [deepcopy(q),deepcopy(Ps),deepcopy(Rh),deepcopy(eta),
744 deepcopy(x),deepcopy(u),deepcopy(v),deepcopy(la),deepcopy(w)]
748 #print "#########\n",mem,"\#########\n"
750 #print "#########m\n",mem,"\#########\n"
755 print "variation trop grande"
762 print "nbre d'iteration trop grand"
767 liste_arret += [(err, ar,k,errorD)]
769 print "###############"
770 print k," avec optym"
771 print "###############"
778 q,Ps,Rh,eta,x,u,v,la,w=init[0],init[1],init[2],init[3],init[4],init[5],init[6],init[7],init[8]
785 while k < itermax and not arret :
786 (u,v,la,w,theta,eta,q,Ps,Rh,x,valeurFonctionDuale,ar,mxg,smax,ct,cta)=maj(k,__maj_theta,mxg,idxexp,True)
787 err = (max(q.values()) - min(q.values()))/min(q.values())
790 arret = err < errorq or ar < errorD
792 variation = "+" if smax > sm else "-"
793 if out : print variation,
797 errorq, "erreur sur F", ar, "et q:", q
799 if out : print "maxg=", mxg
800 mem = [deepcopy(q),deepcopy(Ps),deepcopy(Rh),deepcopy(eta),
801 deepcopy(x),deepcopy(u),deepcopy(v),deepcopy(la),deepcopy(w)]
805 #print "#########\n",mem,"\#########\n"
807 #print "#########m\n",mem,"\#########\n"
812 print "variation trop grande"
819 print "nbre d'iteration trop grand"
824 liste_arret += [(err, ar,k,errorD)]
826 print "###############"
828 print "###############"
833 #print (min(m),max(m),float(sum(m))/nbexp,m),m
834 #return (liste_arret,dur,dura)
839 # pour evaluer argmin
843 for k in list(np.logspace(-5, -3, num=10)):
846 listederes += [(k,__evalue_maj_theta__(3))]
853 for k in list(np.logspace(-5, -3, num=10)):
856 listederes += [(k,__comparePsh_et_Psh_avec8_3__(10))]
865 print"#######################"
870 #__evalue_maj_theta__()
886 print "L",valeurFonctionDuale
890 # relation ente les variables primaires et secondaires ?