code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
def agPalindr(s): n=len(s) m=[[0 for x in range(n+1)] for y in range(n+1)] for ini in range(2,n+1): j,i=ini,0 while j<=n: if s[i]==s[j-1]: m[i][j]=m[i+1][j-1] else: m[i][j]=min(m[i][j-1],m[i+1][j])+1 j+=1 i+=1 print '\n'.join(map(lambda x:' '.join(map(str,x)),m)) return m[0][n] f=open('palindromo.in') while f.readline().rstrip()!="0": print agPalindr(f.readline().rstrip())
[ [ 2, 0, 0.4062, 0.75, 0, 0.66, 0, 553, 0, 1, 1, 0, 0, 0, 10 ], [ 14, 1, 0.125, 0.0625, 1, 0.31, 0, 773, 3, 1, 0, 0, 890, 10, 1 ], [ 14, 1, 0.1875, 0.0625, 1, 0.31, ...
[ "def agPalindr(s):\n\tn=len(s)\n\tm=[[0 for x in range(n+1)] for y in range(n+1)]\n\tfor ini in range(2,n+1):\n\t\tj,i=ini,0\n\t\twhile j<=n:\n\t\t\tif s[i]==s[j-1]: m[i][j]=m[i+1][j-1]\n\t\t\telse: m[i][j]=min(m[i][j-1],m[i+1][j])+1", "\tn=len(s)", "\tm=[[0 for x in range(n+1)] for y in range(n+1)]", "\tfor ...
def pr(h): print "-",' '.join(map(str,h[0])) print "-",' '.join(map(str,h[1])) print "-",' '.join(map(str,h[2])) print def solve(h,s,d,n): if n==1: h[d].append(h[s].pop()) #print "move el ",h[d][len(h[d])-1]," de ",s+1," a ",d+1 pr(h) else: solve(h,s,3-s-d,n-1) h[d].append(h[s].pop()) #print "move el ",h[d][len(h[d])-1]," de ",s+1," a ",d+1 pr(h) solve(h,3-s-d,d,n-1) h=[[3,2,1],[],[]] pr(h) solve(h,0,2,len(h))
[ [ 2, 0, 0.3947, 0.7368, 0, 0.66, 0, 37, 0, 1, 0, 0, 0, 0, 17 ], [ 8, 1, 0.1053, 0.0526, 1, 0.7, 0, 535, 3, 2, 0, 0, 0, 0, 3 ], [ 8, 1, 0.1579, 0.0526, 1, 0.7, 0...
[ "def pr(h):\n\tprint(\"-\",' '.join(map(str,h[0])))\n\tprint(\"-\",' '.join(map(str,h[1])))\n\tprint(\"-\",' '.join(map(str,h[2])))\n\tif n==1:\n\t\th[d].append(h[s].pop())\n\t\t#print \"move el \",h[d][len(h[d])-1],\" de \",s+1,\" a \",d+1\n\t\tpr(h)", "\tprint(\"-\",' '.join(map(str,h[0])))", "\tprint(\"-\",'...
def mochila(C,k): M=[True]+[False]*k for i in range(len(C)): for j in reversed(range(k+1)): M[j]=M[j] or M[j-C[i]] print ''.join([x and '#' or '_' for x in M]) if M[k]: return True return M[k] print mochila([1,2,3,4,5,6],7)
[ [ 2, 0, 0.45, 0.8, 0, 0.66, 0, 797, 0, 2, 1, 0, 0, 0, 6 ], [ 14, 1, 0.2, 0.1, 1, 0.56, 0, 727, 4, 0, 0, 0, 0, 0, 0 ], [ 6, 1, 0.5, 0.5, 1, 0.56, 0.5, 826, ...
[ "def mochila(C,k):\n\tM=[True]+[False]*k\n\tfor i in range(len(C)):\n\t\tfor j in reversed(range(k+1)):\n\t\t\tM[j]=M[j] or M[j-C[i]]\n\t\tprint(''.join([x and '#' or '_' for x in M]))\n\t\tif M[k]: return True\n\treturn M[k]", "\tM=[True]+[False]*k", "\tfor i in range(len(C)):\n\t\tfor j in reversed(range(k+1)...
def pasos(u,v): n,m=len(u),len(v) M1=range(m+1) M2=[1]*(m+1) for i in range(1,n+1): M2[0]=i for j in range(1,m+1): M2[j]=min(M2[j-1]+1, M1[j]+1, M1[j-1]+(u[i-1]!=v[j-1] and 1 or 0)) M1=M2[:] print ''.join([str(x) for x in M1]) return M1[m] print pasos('abc','abx')
[ [ 2, 0, 0.4615, 0.8462, 0, 0.66, 0, 617, 0, 2, 1, 0, 0, 0, 9 ], [ 14, 1, 0.1538, 0.0769, 1, 0.98, 0, 51, 0, 0, 0, 0, 0, 8, 2 ], [ 14, 1, 0.2308, 0.0769, 1, 0.98, ...
[ "def pasos(u,v):\n\tn,m=len(u),len(v)\n\tM1=range(m+1)\n\tM2=[1]*(m+1)\n\tfor i in range(1,n+1):\n\t\tM2[0]=i\n\t\tfor j in range(1,m+1):\n\t\t\tM2[j]=min(M2[j-1]+1, M1[j]+1, M1[j-1]+(u[i-1]!=v[j-1] and 1 or 0))", "\tn,m=len(u),len(v)", "\tM1=range(m+1)", "\tM2=[1]*(m+1)", "\tfor i in range(1,n+1):\n\t\tM2[...
from random import random,randint from math import sqrt def dist(a,b): return sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) def sumx(C): return reduce(lambda x,y:x+y,C,0) def mind(C): if len(C)==2: return dist(C[0],C[1]) elif len(C)<2: return float("Inf") C.sort(key=lambda x:x[0]) r=C[len(C)/2][0] d1=mind(C[:len(C)/2]) d2=mind(C[len(C)/2:]) d=min(d1,d2) C2=[x for x in C if r-d<=x[0]<=r+d] if len(C2)<2: return d else: return min([dist(a,b) for a in C2 for b in C2 if a!=b]) C=list(set([(randint(0,10),randint(0,10)) for x in range(5)])) print C print mind(C)
[ [ 1, 0, 0.0417, 0.0417, 0, 0.66, 0, 715, 0, 2, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0833, 0.0417, 0, 0.66, 0.1429, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 2, 0, 0.1875, 0.0833, 0, ...
[ "from random import random,randint", "from math import sqrt", "def dist(a,b):\n\treturn sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)", "\treturn sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)", "def sumx(C):\n\treturn reduce(lambda x,y:x+y,C,0)", "\treturn reduce(lambda x,y:x+y,C,0)", "def mind(C):\n\tif len(C)==2: ret...
#!/usr/bin/env python from matplotlib.pyplot import * fin=open('instance80_24/data.dat') todo=fin.read().strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] exacto=[int(x.split()[0]) for x in todo if x] constru=[int(x.split()[1]) for x in todo if x] local=[int(x.split()[2]) for x in todo if x] tabu=[int(x.split()[3]) for x in todo if x] #title("Cantidad de operaciones de $matching$") xlabel("exacto") ylabel("cs") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.1) #savefig('ej1_counts.png',dpi=640./8) show()
[ [ 1, 0, 0.0909, 0.0455, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1818, 0.0455, 0, 0.66, 0.0667, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2273, 0.0455, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('instance80_24/data.dat')", "todo=fin.read().strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "exacto=[int(x.split()[0]) for x in todo if x]", "constru=[int(x.split()[1]) for x in todo if x]", "local=[int(x.split()[2]) for x in todo if x]",...
#!/usr/bin/env python from matplotlib.pyplot import * files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] data = "\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]) todo=data.strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] exacto=[int(x.split()[0]) for x in todo if x] constru=[int(x.split()[1]) for x in todo if x] local=[int(x.split()[2]) for x in todo if x] tabu=[int(x.split()[3]) for x in todo if x] title("Comparacion de algoritmos de max-sat") xlabel("# Clausulas satisfacibles") ylabel("# Clausulas satisfechas") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.02) savefig('plot_todos_vs_exacto.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1739, 0.0435, 0, 0.66, 0.0556, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.2174, 0.0435, 0, 0...
[ "from matplotlib.pyplot import *", "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "data = \"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])])", "todo=data.strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]",...
#! /usr/bin/python files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#!/usr/bin/env python from matplotlib.pyplot import * files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] data = "\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]) todo=data.strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] exacto=[int(x.split()[0]) for x in todo if x] constru=[int(x.split()[1]) for x in todo if x] local=[int(x.split()[2]) for x in todo if x] tabu=[int(x.split()[3]) for x in todo if x] title("Comparacion de algoritmos de max-sat") xlabel("# Clausulas satisfacibles") ylabel("# Clausulas satisfechas") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.02) savefig('plot_todos_vs_exacto.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1739, 0.0435, 0, 0.66, 0.0556, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.2174, 0.0435, 0, 0...
[ "from matplotlib.pyplot import *", "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "data = \"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])])", "todo=data.strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]",...
#! /usr/bin/python files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#! /usr/bin/python files=["constructiva.out","busq_local.out","tabu.out"] f=open("data_big.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "f=open(\"data_big.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#!/usr/bin/env python from matplotlib.pyplot import * fin=open('data_big.dat') tam=open('hard_big_tamanios') todo=fin.read().strip().split('\n') #xs=tam.read().split() constru=[int(x.split()[0]) for x in todo if x] local=[int(x.split()[1]) for x in todo if x] xs=tabu=[int(x.split()[2]) for x in todo if x] title("Comparacion de los algoritmos vs Tabu Search") xlabel("# Clausulas satisfechas por tabu") ylabel("fraccion de # Clausulas satisfechas por tabu") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.01) savefig('plot_todos_vs_tabu.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1739, 0.0435, 0, 0.66, 0.0625, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2174, 0.0435, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('data_big.dat')", "tam=open('hard_big_tamanios')", "todo=fin.read().strip().split('\\n')", "constru=[int(x.split()[0]) for x in todo if x]", "local=[int(x.split()[1]) for x in todo if x]", "xs=tabu=[int(x.split()[2]) for x in todo if x]", "title(\"Comparaci...
#! /usr/bin/python files=["constructiva.out","busq_local.out","tabu.out"] f=open("data_big.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "f=open(\"data_big.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#!/usr/bin/env python from matplotlib.pyplot import * fin=open('data_big.dat') tam=open('hard_big_tamanios') todo=fin.read().strip().split('\n') #xs=tam.read().split() constru=[int(x.split()[0]) for x in todo if x] local=[int(x.split()[1]) for x in todo if x] xs=tabu=[int(x.split()[2]) for x in todo if x] title("Comparacion de los algoritmos vs Tabu Search") xlabel("# Clausulas satisfechas por tabu") ylabel("fraccion de # Clausulas satisfechas por tabu") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.01) savefig('plot_todos_vs_tabu.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1739, 0.0435, 0, 0.66, 0.0625, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2174, 0.0435, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('data_big.dat')", "tam=open('hard_big_tamanios')", "todo=fin.read().strip().split('\\n')", "constru=[int(x.split()[0]) for x in todo if x]", "local=[int(x.split()[1]) for x in todo if x]", "xs=tabu=[int(x.split()[2]) for x in todo if x]", "title(\"Comparaci...
#! /usr/bin/python from random import randint from random import choice INSTANCIAS = 70 MAX_CLAUS = 300 MAX_VARS = 40 MAX_VARS_POR_CLAUS = 10 f = open("hard_big.in",'w') clausulas=open("hard_big_tamanios",'w') for i in xrange(INSTANCIAS): c = randint(1,MAX_CLAUS) clausulas.write(str(c)+"\n") v = randint(1,MAX_VARS) f.write("%d %d\r\n"%(c,v)) mvpc=randint(3,MAX_VARS_POR_CLAUS) for j in xrange(c): l = randint(1,mvpc) f.write(" %d\t\t"%l) for k in xrange(l): s = choice([-1,1]) f.write((s>0 and " " or "")+"%d\t"%(s*randint(1,v))) f.write('\r\n') f.write('-1 -1\r\n') f.close()
[ [ 1, 0, 0.0667, 0.0333, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1, 0.0333, 0, 0.66, 0.1, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 14, 0, 0.1667, 0.0333, 0, 0.66,...
[ "from random import randint", "from random import choice", "INSTANCIAS = 70", "MAX_CLAUS = 300", "MAX_VARS = 40", "MAX_VARS_POR_CLAUS = 10", "f = open(\"hard_big.in\",'w')", "clausulas=open(\"hard_big_tamanios\",'w')", "for i in xrange(INSTANCIAS):\n\tc = randint(1,MAX_CLAUS)\n\tclausulas.write(str(...
#! /usr/bin/python from random import randint from random import choice INSTANCIAS = 70 MAX_CLAUS = 300 MAX_VARS = 40 MAX_VARS_POR_CLAUS = 10 f = open("hard_big.in",'w') clausulas=open("hard_big_tamanios",'w') for i in xrange(INSTANCIAS): c = randint(1,MAX_CLAUS) clausulas.write(str(c)+"\n") v = randint(1,MAX_VARS) f.write("%d %d\r\n"%(c,v)) mvpc=randint(3,MAX_VARS_POR_CLAUS) for j in xrange(c): l = randint(1,mvpc) f.write(" %d\t\t"%l) for k in xrange(l): s = choice([-1,1]) f.write((s>0 and " " or "")+"%d\t"%(s*randint(1,v))) f.write('\r\n') f.write('-1 -1\r\n') f.close()
[ [ 1, 0, 0.0667, 0.0333, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1, 0.0333, 0, 0.66, 0.1, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 14, 0, 0.1667, 0.0333, 0, 0.66,...
[ "from random import randint", "from random import choice", "INSTANCIAS = 70", "MAX_CLAUS = 300", "MAX_VARS = 40", "MAX_VARS_POR_CLAUS = 10", "f = open(\"hard_big.in\",'w')", "clausulas=open(\"hard_big_tamanios\",'w')", "for i in xrange(INSTANCIAS):\n\tc = randint(1,MAX_CLAUS)\n\tclausulas.write(str(...
#! /usr/bin/python files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#! /usr/bin/python from random import randint from random import choice INSTANCIAS = 1 MAX_CLAUS = 300 MAX_VARS = 300 MAX_VARS_POR_CLAUS = 3 f = open("hard.in",'w') for i in xrange(INSTANCIAS): c = randint(1,MAX_CLAUS) v = randint(1,MAX_VARS) f.write("%d %d\r\n"%(c,v)) for j in xrange(c): l = randint(1,randint(2,MAX_VARS_POR_CLAUS)) f.write(" %d\t\t"%l) for k in xrange(l): s = choice([-1,1]) f.write((s>0 and " " or "")+"%d\t"%(s*randint(1,v))) f.write('\r\n') f.write('-1 -1\r\n') f.close()
[ [ 1, 0, 0.0741, 0.037, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1111, 0.037, 0, 0.66, 0.1111, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 14, 0, 0.1852, 0.037, 0, 0....
[ "from random import randint", "from random import choice", "INSTANCIAS = 1", "MAX_CLAUS = 300", "MAX_VARS = 300", "MAX_VARS_POR_CLAUS = 3", "f = open(\"hard.in\",'w')", "for i in xrange(INSTANCIAS):\n\tc = randint(1,MAX_CLAUS)\n\tv = randint(1,MAX_VARS)\n\tf.write(\"%d %d\\r\\n\"%(c,v))\n\tfor j in xr...
#!/usr/bin/env python from matplotlib.pyplot import * fin=open('instance80_24/data.dat') todo=fin.read().strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] exacto=[int(x.split()[0]) for x in todo if x] constru=[int(x.split()[1]) for x in todo if x] local=[int(x.split()[2]) for x in todo if x] tabu=[int(x.split()[3]) for x in todo if x] #title("Cantidad de operaciones de $matching$") xlabel("exacto") ylabel("cs") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.1) #savefig('ej1_counts.png',dpi=640./8) show()
[ [ 1, 0, 0.0909, 0.0455, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1818, 0.0455, 0, 0.66, 0.0667, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2273, 0.0455, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('instance80_24/data.dat')", "todo=fin.read().strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "exacto=[int(x.split()[0]) for x in todo if x]", "constru=[int(x.split()[1]) for x in todo if x]", "local=[int(x.split()[2]) for x in todo if x]",...
#! /usr/bin/python files=["constructiva_big.out","busq_local_big.out","tabu_big.out"] f=open("data_big.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"constructiva_big.out\",\"busq_local_big.out\",\"tabu_big.out\"]", "f=open(\"data_big.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#!/usr/bin/env python from matplotlib.pyplot import * fin=open('data_big.dat') tam=open('hard_big_tamanios') todo=fin.read().strip().split('\n') #xs=tam.read().split() constru=[int(x.split()[0]) for x in todo if x] local=[int(x.split()[1]) for x in todo if x] xs=tabu=[int(x.split()[2]) for x in todo if x] title("Comparacion de los algoritmos vs Tabu Search") xlabel("# Clausulas satisfechas por tabu") ylabel("fraccion de # Clausulas satisfechas por tabu") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.01) savefig('plot_todos_vs_tabu.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1739, 0.0435, 0, 0.66, 0.0625, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2174, 0.0435, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('data_big.dat')", "tam=open('hard_big_tamanios')", "todo=fin.read().strip().split('\\n')", "constru=[int(x.split()[0]) for x in todo if x]", "local=[int(x.split()[1]) for x in todo if x]", "xs=tabu=[int(x.split()[2]) for x in todo if x]", "title(\"Comparaci...
#!/usr/bin/env python from matplotlib.pyplot import * files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] data = "\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]) todo=data.strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] exacto=[int(x.split()[0]) for x in todo if x] constru=[int(x.split()[1]) for x in todo if x] local=[int(x.split()[2]) for x in todo if x] tabu=[int(x.split()[3]) for x in todo if x] title("Comparacion de algoritmos de max-sat") xlabel("# Clausulas satisfacibles") ylabel("# Clausulas satisfechas") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.02) savefig('plot_todos_vs_exacto.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1739, 0.0435, 0, 0.66, 0.0556, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.2174, 0.0435, 0, 0...
[ "from matplotlib.pyplot import *", "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "data = \"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])])", "todo=data.strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]",...
#! /usr/bin/python files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#!/usr/bin/env python from matplotlib.pyplot import * files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] data = "\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]) todo=data.strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] exacto=[int(x.split()[0]) for x in todo if x] constru=[int(x.split()[1]) for x in todo if x] local=[int(x.split()[2]) for x in todo if x] tabu=[int(x.split()[3]) for x in todo if x] title("Comparacion de algoritmos de max-sat") xlabel("# Clausulas satisfacibles") ylabel("# Clausulas satisfechas") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.02) savefig('plot_todos_vs_exacto.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1739, 0.0435, 0, 0.66, 0.0556, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.2174, 0.0435, 0, 0...
[ "from matplotlib.pyplot import *", "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "data = \"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])])", "todo=data.strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]",...
#! /usr/bin/python files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#!/usr/bin/env python from matplotlib.pyplot import * #fin=open('instance80_24/data.dat') fin=open('p_iter1.dat') todo=fin.read().strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] ys=[int(x.split()[1]) for x in todo if x] #title("Cantidad de operaciones de $matching$") xlabel("MAX_ITER") ylabel("clausulas satisfechas") #plot(xs,exacto,'k.',label="exacto") plot(xs,ys,'ro',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) #ylim(ymax=89,ymin=83) savefig('MAX_ITER.png',dpi=640./8) show()
[ [ 1, 0, 0.1111, 0.0556, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0.1, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3333, 0.0556, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('p_iter1.dat')", "todo=fin.read().strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "ys=[int(x.split()[1]) for x in todo if x]", "xlabel(\"MAX_ITER\")", "ylabel(\"clausulas satisfechas\")", "plot(xs,ys,'ro',label=\"tabu\")", "legend(loc=...
#!/usr/bin/env python from matplotlib.pyplot import * #fin=open('instance80_24/data.dat') fin=open('p_iter1.dat') todo=fin.read().strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] ys=[int(x.split()[1]) for x in todo if x] #title("Cantidad de operaciones de $matching$") xlabel("MAX_ITER") ylabel("clausulas satisfechas") #plot(xs,exacto,'k.',label="exacto") plot(xs,ys,'ro',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) #ylim(ymax=89,ymin=83) savefig('MAX_ITER.png',dpi=640./8) show()
[ [ 1, 0, 0.1111, 0.0556, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0.1, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3333, 0.0556, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('p_iter1.dat')", "todo=fin.read().strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "ys=[int(x.split()[1]) for x in todo if x]", "xlabel(\"MAX_ITER\")", "ylabel(\"clausulas satisfechas\")", "plot(xs,ys,'ro',label=\"tabu\")", "legend(loc=...
#! /usr/bin/python from random import randint from random import choice INSTANCIAS = 1 MAX_CLAUS = 300 MAX_VARS = 300 MAX_VARS_POR_CLAUS = 3 f = open("hard.in",'w') for i in xrange(INSTANCIAS): c = randint(1,MAX_CLAUS) v = randint(1,MAX_VARS) f.write("%d %d\r\n"%(c,v)) for j in xrange(c): l = randint(1,randint(2,MAX_VARS_POR_CLAUS)) f.write(" %d\t\t"%l) for k in xrange(l): s = choice([-1,1]) f.write((s>0 and " " or "")+"%d\t"%(s*randint(1,v))) f.write('\r\n') f.write('-1 -1\r\n') f.close()
[ [ 1, 0, 0.0741, 0.037, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1111, 0.037, 0, 0.66, 0.1111, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 14, 0, 0.1852, 0.037, 0, 0....
[ "from random import randint", "from random import choice", "INSTANCIAS = 1", "MAX_CLAUS = 300", "MAX_VARS = 300", "MAX_VARS_POR_CLAUS = 3", "f = open(\"hard.in\",'w')", "for i in xrange(INSTANCIAS):\n\tc = randint(1,MAX_CLAUS)\n\tv = randint(1,MAX_VARS)\n\tf.write(\"%d %d\\r\\n\"%(c,v))\n\tfor j in xr...
#!/usr/bin/env python from matplotlib.pyplot import * #fin=open('instance80_24/data.dat') fin=open('data_tiempos.dat') todo=fin.read().strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] exacto=[int(x.split()[0]) for x in todo if x] constru=[int(x.split()[1]) for x in todo if x] local=[int(x.split()[2]) for x in todo if x] tabu=[int(x.split()[3]) for x in todo if x] #title("Cantidad de operaciones de $matching$") xlabel("exacto") ylabel("cs") #plot(xs,exacto,'k.',label="exacto") plot(xs,constru,'gx',label="constructiva") plot(xs,local,'b+',label="busqueda local") plot(xs,tabu,'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) #ylim(ymax=1.1) savefig('tiempos.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2174, 0.0435, 0, 0.66, 0.0667, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2609, 0.0435, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('data_tiempos.dat')", "todo=fin.read().strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "exacto=[int(x.split()[0]) for x in todo if x]", "constru=[int(x.split()[1]) for x in todo if x]", "local=[int(x.split()[2]) for x in todo if x]", "ta...
#! /usr/bin/python #files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] #f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])])) files=["exacto.log","constructiva.log","busq_local.log","tabu.log"] f=open("data_tiempos.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n") for f in files])]))
[ [ 14, 0, 0.8571, 0.1429, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.1429, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"exacto.log\",\"constructiva.log\",\"busq_local.log\",\"tabu.log\"]", "f=open(\"data_tiempos.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\") for f in files])]))" ]
#!/usr/bin/env python from matplotlib.pyplot import * #fin=open('instance80_24/data.dat') fin=open('data_tiempos.dat') todo=fin.read().strip().split('\n') xs=[int(x.split()[0]) for x in todo if x] exacto=[int(x.split()[0]) for x in todo if x] constru=[int(x.split()[1]) for x in todo if x] local=[int(x.split()[2]) for x in todo if x] tabu=[int(x.split()[3]) for x in todo if x] #title("Cantidad de operaciones de $matching$") xlabel("exacto") ylabel("cs") #plot(xs,exacto,'k.',label="exacto") plot(xs,constru,'gx',label="constructiva") plot(xs,local,'b+',label="busqueda local") plot(xs,tabu,'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) #ylim(ymax=1.1) savefig('tiempos.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2174, 0.0435, 0, 0.66, 0.0667, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2609, 0.0435, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('data_tiempos.dat')", "todo=fin.read().strip().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "exacto=[int(x.split()[0]) for x in todo if x]", "constru=[int(x.split()[1]) for x in todo if x]", "local=[int(x.split()[2]) for x in todo if x]", "ta...
#! /usr/bin/python #files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] #f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])])) files=["exacto.log","constructiva.log","busq_local.log","tabu.log"] f=open("data_tiempos.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n") for f in files])]))
[ [ 14, 0, 0.8571, 0.1429, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.1429, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"exacto.log\",\"constructiva.log\",\"busq_local.log\",\"tabu.log\"]", "f=open(\"data_tiempos.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\") for f in files])]))" ]
#! /usr/bin/python files=["exacto.out","constructiva.out","busq_local.out","tabu.out"] f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]", "f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#! /usr/bin/python files=["constructiva_big.out","busq_local_big.out","tabu_big.out"] f=open("data_big.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
[ [ 14, 0, 0.75, 0.25, 0, 0.66, 0, 598, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 1, 0.25, 0, 0.66, 1, 899, 3, 1, 0, 0, 837, 10, 9 ] ]
[ "files=[\"constructiva_big.out\",\"busq_local_big.out\",\"tabu_big.out\"]", "f=open(\"data_big.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))" ]
#!/usr/bin/env python from matplotlib.pyplot import * fin=open('data_big.dat') tam=open('hard_big_tamanios') todo=fin.read().strip().split('\n') #xs=tam.read().split() constru=[int(x.split()[0]) for x in todo if x] local=[int(x.split()[1]) for x in todo if x] xs=tabu=[int(x.split()[2]) for x in todo if x] title("Comparacion de los algoritmos vs Tabu Search") xlabel("# Clausulas satisfechas por tabu") ylabel("fraccion de # Clausulas satisfechas por tabu") #plot(xs,exacto,'k.',label="exacto") plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva") plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local") plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu") #plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) ylim(ymax=1.01) savefig('plot_todos_vs_tabu.png',dpi=640./8) show()
[ [ 1, 0, 0.087, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.1739, 0.0435, 0, 0.66, 0.0625, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2174, 0.0435, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('data_big.dat')", "tam=open('hard_big_tamanios')", "todo=fin.read().strip().split('\\n')", "constru=[int(x.split()[0]) for x in todo if x]", "local=[int(x.split()[1]) for x in todo if x]", "xs=tabu=[int(x.split()[2]) for x in todo if x]", "title(\"Comparaci...
from random import randint def mprint(m): return '\n'.join(map(lambda x:''.join([el and '#' or '_' for el in x]),m)) fout=open('test_sanos.in','w') for n in range(6,40): for caso in range(10): M=[[0]*n for el in range(n)] ks=[] for cuad in range(randint(5,2*n)): ki=randint(2,n/4+1) if ki%2==1: ki+=randint(0,10)<5 and 1 or -1 kj=randint(2,n/4+1) i,j=randint(0,n-ki),randint(0,n-kj) ok=True for unki,unkj,uni,unj in ks: #if (unj-1<=j<=unkj+unj+1 and uni-1<=i<=unki+uni+1) or (unj-1<=kj+j<=unkj+unj+1 and uni-1<=ki+i<=unki+uni+1) or (unj-1<=kj+j<=unkj+unj+1 and uni-1<=i<=unki+uni+1) or (unj-1<=j<=unkj+unj+1 and uni-1<=ki+i<=unki+uni+1): ok=False for ii in range(i,i+ki): for jj in range(j,j+kj): if M[ii][jj] or (ii<n-1 and M[ii+1][jj]) or (jj<n-1 and M[ii][jj+1]) or (ii>0 and M[ii-1][jj]) or (jj>0 and M[ii][jj-1]): ok=False if ok: ks.append((ki,kj,i,j)) for p in range(i,i+ki): for l in range(j,j+kj): M[p][l]=1 fout.write(str(n)+"\n"+mprint(M)+"\n") fout.write("-1\n\n")
[ [ 1, 0, 0.0333, 0.0333, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 2, 0, 0.1167, 0.0667, 0, 0.66, 0.25, 184, 0, 1, 1, 0, 0, 0, 3 ], [ 13, 1, 0.1333, 0.0333, 1, 0.4...
[ "from random import randint", "def mprint(m):\n\treturn '\\n'.join(map(lambda x:''.join([el and '#' or '_' for el in x]),m))", "\treturn '\\n'.join(map(lambda x:''.join([el and '#' or '_' for el in x]),m))", "fout=open('test_sanos.in','w')", "for n in range(6,40):\n\tfor caso in range(10):\n\t\tM=[[0]*n for...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed from math import sqrt seed(123) # defino el seed para hacer el experimento reproducible def runtest(li,args): # abro ./domino con parametros args fp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for caso,p in li: fp.stdin.write(str(len(caso))+"\n") # le mando el tamanio for line in caso: fp.stdin.write(line+"\n") # le mando la linea de la matriz r=fp.stdout.readline().rstrip() # recibo el resultado print "n=",len(caso)," p=",p," ",args[0],"=",r yield len(caso),p,r # lo devuelvo fp.stdin.write("-1\n") # le mando un -1 para que termine def runarchivo(archivo,args): # abro ./domino con parametros args fp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) fin=open(archivo) while 1: sze=int(fin.readline().rstrip()) if sze<0: break fp.stdin.write(str(sze)+"\n") # le mando el tamanio for line in range(sze): fp.stdin.write(fin.readline()) # le mando la linea de la matriz r=fp.stdout.readline().rstrip() # recibo el resultado print "n=",sze," ",args[0],"=",r yield sze,r # lo devuelvo fp.stdin.write("-1\n") # le mando un -1 para que termine def int2matrix(n,l): res='' while n>1: res=(n%2 and '#' or '_') + res n/=2 res=(n and '#' or '_') + res return [('_'*(l**2-len(res)) + res)[i:i+l] for i in range(0,l**2,l)] def randMatrix(n,p): #una matriz al azar con probabilidad p de que cada casilla sea sana res=[] for i in range(n): res.append('') for j in range(n): res[i]=(random()<p and '#' or '_') + res[i] return res def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) # genero la lista de los casos de prueba ms=[(randMatrix(n,p/20.),p/20.) for n in range(1,9) for p in range(1,20,1) for re in range(15)] out="" if "--time" in opts or "-t" in opts: for i in runarchivo("test_sanos.in",['time','0.003','3']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el promedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t" + "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err_sanos.dat','w').write("# N\tP\tTIEMPO\tERROR\n"+out) # lo guardo en el archivo print "\nOutput escrito a time_err_sanos.dat" out="" if "--count" in opts or "-c" in opts: for i in runarchivo("test_sanos.in",['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts_sanos.dat','w').write("# N\tP\tCOUNT\n"+out) # lo guardo en el archivo print "\nOutput escrito a counts_sanos.dat" out="" notli=[303,305,318,325,328,331,338,360,362,363,370,374,376,383,384,385,391,393,397,400,403,411,414,415,417,423,425,428,431,436,438,441,442,450,452,457,458,459,462,466,470,471,473,474,475,481,485,491,492,496,498,500,505,507,511,512,513,514,515,516,518,519,522,524,525,526,527,529,531,532,534,536,537,538,539,540,541,542,546,548,550,553,554,556,557,558,559,560,562,563,564,565,566,567,568,569,594,605,606,607,618,626,629,639,649,650,651,653,656,659,670,675,680,685,687,696,700,703,704,711,722,729,731,735,742,745,746,752,753,754,756,758,769,773,776,779,786,790,792,793,794,801,802,803,806,812,815,817,821,834,841,849,851,859,880,882,886,892,894,895,900,901,908,918,923,925,926,931,938,941,948,954,961,967,971,975,979,988,991,993,994,1002,1007,1008,1012,1017,1021,1023,1038,1041,1042,1045,1050,1056,1060,1062,1063,1075,1086,1101,1102,1106,1110,1111,1112,1120,1122,1127,1129,1131,1132,1133,1134,1135,1136,1137,1138,1141,1144,1153,1156,1164,1165,1167,1168,1177,1183,1184,1185,1189,1193,1194,1201,1214,1221,1231,1239,1260,1275,1285,1286,1294,1308,1310,1326,1327,1344,1347,1356,1362,1379,1380,1390,1415,1418,1420,1426,1428,1429,1431,1432,1437,1447,1456,1460,1464,1469,1475,1481,1488,1497,1503,1513,1515,1527,1529,1532,1534,1538,1555,1579,1584,1622,1648,1649,1671,1677,1678,1681,1688,1692,1695,1700,1701,1706,1707,1713,1715,1716,1721,1734,1735,1738,1750,1751,1762,1765,1777,1779,1793,1794,1808,1829,1830,1837,1843,1846,1850,1856,1882,1884,1889,1890,1908,1912,1917,1919,1934,1938,1939,1943,1958,1968,1976,1977,1981,1992,1994,1995,1999,2002,2003,2009,2027,2035,2039,2040,2042,2048,2066,2071,2079,2080,2081,2086,2109,2113,2130,2131,2137,2139,2141,2150,2151,2166,2175,2176,2178,2192,2199,2200,2208,2213,2232,2246,2263,2265,2266,2273,2277,2278,2279] for m in range(len(ms)): if m not in notli: out+=str(len(ms[m][0]))+"\n" for line in ms[m][0]: out+=line+"\n" open('test_imposibles.in','w').write(out+"-1\n")
[ [ 1, 0, 0.0179, 0.0179, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0357, 0.0179, 0, 0.66, 0.125, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.0536, 0.0179, 0, 0...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed", "from math import sqrt", "def runtest(li,args):\n\t# abro ./domino con parametros args\n\tfp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor caso,p in li:\n\t\tfp.stdin.w...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed from math import sqrt def runtest(li,args): # abro ./domino con parametros args fp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for caso,p in li: fp.stdin.write(str(len(caso))+"\n") # le mando el tamanio for line in caso: fp.stdin.write(line+"\n") # le mando la linea de la matriz r=fp.stdout.readline().rstrip() # recibo el resultado print "n=",len(caso)," p=",p," ",args[0],"=",r yield len(caso),p,r # lo devuelvo fp.stdin.write("-1\n") # le mando un -1 para que termine def int2matrix(n,l): res='' while n>1: res=(n%2 and '#' or '_') + res n/=2 res=(n and '#' or '_') + res return [('_'*(l**2-len(res)) + res)[i:i+l] for i in range(0,l**2,l)] def randMatrix(n,p): #una matriz al azar con probabilidad p de que cada casilla sea sana res=[] for i in range(n): res.append('') for j in range(n): res[i]=(random()<p and '#' or '_') + res[i] return res def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) seed(123) # defino el seed para hacer el experimento reproducible # genero la lista de los casos de prueba ms=[(randMatrix(n,p/20.),p/20.) for n in range(1,9) for p in range(1,20,1) for re in range(15)] out="" if "--time" in opts or "-t" in opts: for i in runtest(ms,['time','0.003','3']): # para cada caso de prueba... vals=map(float,i[2].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el promedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.1f"%i[1] +"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write("# N\tP\tTIEMPO\tERROR\n"+out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(ms,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+("%.1f"%i[1])+"\t"+i[2]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write("# N\tP\tCOUNT\n"+out) # lo guardo en el archivo print "\nOutput escrito a counts.dat" out="" for caso,p in ms: out+=str(len(caso))+"\n" for line in caso: out+=line+"\n" open('test.in','w').write(out+"-1\n")
[ [ 1, 0, 0.0244, 0.0244, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0488, 0.0244, 0, 0.66, 0.1429, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.0732, 0.0244, 0, ...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed", "from math import sqrt", "def runtest(li,args):\n\t# abro ./domino con parametros args\n\tfp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor caso,p in li:\n\t\tfp.stdin.w...
from math import cos,pi,sqrt def pretty(m): #funcion que imprime una matriz print '\n'.join([' '.join(map(str,line)) for line in m]) def productoria(li): return reduce(lambda x,y:x*y, li, 1) def sano(n): #algoritmo magico :D return int(round(productoria([sqrt(sqrt(4*cos(pi*j/(n+1))**2+4*cos(pi*k/(n+1))**2)) for k in range(1,n+1) for j in range(1,n+1)]))) f=open('Tp1Ej3.in') #abro archivo de entrada while True: #recorro los casos de prueba n=int(f.readline()) #n es el tamanio del array if n<0: break #n==-1 significa que se acabaron los casos m=[[x=='#' and 1 or 0 for x in f.readline().strip()] for line in range(n)] # en m guardo la matriz (lista de listas) # 1 es una celda sana libre. 0 es una celda rota. x es celda ocupada. v es ficha vertical. h es ficha horizontal if reduce(lambda x,y: x and y,reduce(lambda x,y:x+y, m)): #chequeo si esta toda sana print sano(n) #si esta toda sana uso el algoritmo copado :P continue #y paso al proximo caso acc=0 # contador de las distintas posibilidades pos=0 # posicion en la que estoy parado (entre 0 y n*n) (pos%n es la columna, pos/n es la fila) direccion=1 #direccion en la que estoy recorriendo. empiezo yendo para adelante while True: if pos==n*n: # se termino el tablero! acc+=1 # es porque encontre una solucion pos-=1 #vuelvo 1 direccion=-1 #empiezo a ir para atras (para cambiar algunas fichas de lugar) elif pos==-1: #termine!!!! break #salgo del loop i,j=pos/n,pos%n # i,j son los indices en la matriz (dada la pos) if direccion==1: #si estoy yendo para adelante.. if m[i][j]==1: #si esta posicion esta sana.. if i<n-1 and m[i+1][j]==1: #si hay espacio para poner una ficha verticalmente m[i][j]='v' # marco esta posicion con una v m[i+1][j]='x' # y marco la posicion de abajo como ocupada elif j<n-1 and m[i][j+1]==1: #si hay espacio para poner una ficha horizontalmente m[i][j]='h' # marco esta posicion con una h m[i][j+1]='x' # y marco la posicion de al lado como ocupada pos+=1 # de paso aumento el pos porque es obvio que la proxima esta ocupada.. i,j=pos/n,pos%n #actualizo los indices.. else: # no hay espacio para poner una ficha!! este camino no anduvo! i,j=pos/n,pos%n #actualizo los indices.. direccion=-1 # empiezo a ir para atras. else: # si estaba ocupada o rota pass #no hago nada :P else: #si estoy yendo para atras.. if m[i][j]=='v': #si me encuentro con una ficha puesta verticalmente.. #voy a probar de poner esta ficha horizontalmente if j<n-1 and m[i][j+1]: m[i+1][j]=1 #saco la ficha vertical que estaba m[i][j]='h' #pongo una horizontal m[i][j+1]='x' #(y ocupo la proxima celda) direccion=1 # y empiezo a ir para adelante buscando combinaciones nuevas else: #si no puedo ponerla horizontalmente m[i][j]=1 #saco la anterior m[i+1][j]=1 elif m[i][j]=='h': #si me encuentro con una ficha puesta horizontalmente.. m[i][j]=1 # la saco m[i][j+1]=1 pos+=direccion #me muevo una celda en el sentido de la direccion print acc
[ [ 1, 0, 0.0139, 0.0139, 0, 0.66, 0, 526, 0, 3, 0, 0, 526, 0, 0 ], [ 2, 0, 0.0556, 0.0417, 0, 0.66, 0.2, 369, 0, 1, 0, 0, 0, 0, 4 ], [ 8, 1, 0.0694, 0.0139, 1, 0.75,...
[ "from math import cos,pi,sqrt", "def pretty(m):\n\t#funcion que imprime una matriz\n\tprint('\\n'.join([' '.join(map(str,line)) for line in m]))", "\tprint('\\n'.join([' '.join(map(str,line)) for line in m]))", "def productoria(li):\n\treturn reduce(lambda x,y:x*y, li, 1)", "\treturn reduce(lambda x,y:x*y, ...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed from math import sqrt def runtest(li,args): # abro ./domino con parametros args fp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for caso,p in li: fp.stdin.write(str(len(caso))+"\n") # le mando el tamanio for line in caso: fp.stdin.write(line+"\n") # le mando la linea de la matriz r=fp.stdout.readline().rstrip() # recibo el resultado print "n=",len(caso)," p=",p," ",args[0],"=",r yield len(caso),p,r # lo devuelvo fp.stdin.write("-1\n") # le mando un -1 para que termine def int2matrix(n,l): res='' while n>1: res=(n%2 and '#' or '_') + res n/=2 res=(n and '#' or '_') + res return [('_'*(l**2-len(res)) + res)[i:i+l] for i in range(0,l**2,l)] def randMatrix(n,p): #una matriz al azar con probabilidad p de que cada casilla sea sana res=[] for i in range(n): res.append('') for j in range(n): res[i]=(random()<p and '#' or '_') + res[i] return res def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) seed(123) # defino el seed para hacer el experimento reproducible # genero la lista de los casos de prueba ms=[(randMatrix(n,p/20.),p/20.) for n in range(1,9) for p in range(1,20,1) for re in range(15)] out="" if "--time" in opts or "-t" in opts: for i in runtest(ms,['time','0.003','3']): # para cada caso de prueba... vals=map(float,i[2].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el promedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.1f"%i[1] +"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write("# N\tP\tTIEMPO\tERROR\n"+out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(ms,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+("%.1f"%i[1])+"\t"+i[2]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write("# N\tP\tCOUNT\n"+out) # lo guardo en el archivo print "\nOutput escrito a counts.dat" out="" for caso,p in ms: out+=str(len(caso))+"\n" for line in caso: out+=line+"\n" open('test.in','w').write(out+"-1\n")
[ [ 1, 0, 0.0244, 0.0244, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0488, 0.0244, 0, 0.66, 0.1429, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.0732, 0.0244, 0, ...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed", "from math import sqrt", "def runtest(li,args):\n\t# abro ./domino con parametros args\n\tfp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor caso,p in li:\n\t\tfp.stdin.w...
#!/usr/bin/env python import getopt,sys import subprocess from random import randint,seed from math import sqrt def runtest(li,args): # abro ./amigos con parametros: time 0.1 3 fp=subprocess.Popen(['./intervalos']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for i in li: fp.stdin.write(str(len(i))+"\n"+' '.join(map(str,i))+"\n") # le manda la instancia r=fp.stdout.readline().rstrip() # recibo el resultado print "n=",len(i)," ",args[0],"=",r yield len(i),r # lo devuelvo fp.stdin.write("-1\n") def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) seed(1234) # defino el seed para hacer el experimento reproducible test=open('test.in') li=[] while 1: inst=map(int,test.readline().split()) if inst[0]==-1: break li.append(inst[1:]) out="" if "--time" in opts or "-t" in opts: for i in runtest(li,['time','0.1','3']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(li,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a counts.dat"
[ [ 1, 0, 0.0476, 0.0476, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0952, 0.0476, 0, 0.66, 0.2, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.1429, 0.0476, 0, 0.6...
[ "import getopt,sys", "import subprocess", "from random import randint,seed", "from math import sqrt", "def runtest(li,args):\n\t# abro ./amigos con parametros: time 0.1 3\n\tfp=subprocess.Popen(['./intervalos']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor i in li:\n\t\tfp.stdin.wr...
f=open('Tp1Ej1.in') while True: li=map(float,f.readline().rsplit()) if li[0]<0: break li.pop(0) li.sort() mi,count=li.pop(0)+1,1 for x in li: if x>mi: count+=1 mi=x+1 print count
[ [ 14, 0, 0.0833, 0.0833, 0, 0.66, 0, 899, 3, 1, 0, 0, 693, 10, 1 ], [ 5, 0, 0.5833, 0.9167, 0, 0.66, 1, 0, 1, 0, 0, 0, 0, 0, 7 ], [ 14, 1, 0.25, 0.0833, 1, 0.89, ...
[ "f=open('Tp1Ej1.in')", "while True:\n\tli=map(float,f.readline().rsplit())\n\tif li[0]<0: break\n\tli.pop(0)\n\tli.sort()\n\tmi,count=li.pop(0)+1,1\n\tfor x in li:\n\t\tif x>mi:", "\tli=map(float,f.readline().rsplit())", "\tif li[0]<0: break", "\tli.pop(0)", "\tli.sort()", "\tmi,count=li.pop(0)+1,1", ...
#!/usr/bin/env python import getopt,sys import subprocess from random import randint,seed from math import sqrt def runtest(li,args): # abro ./amigos con parametros: time 0.1 3 fp=subprocess.Popen(['./intervalos']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for i in li: fp.stdin.write(str(len(i))+"\n"+' '.join(map(str,i))+"\n") # le manda la instancia r=fp.stdout.readline().rstrip() # recibo el resultado print "n=",len(i)," ",args[0],"=",r yield len(i),r # lo devuelvo fp.stdin.write("-1\n") def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) seed(1234) # defino el seed para hacer el experimento reproducible test=open('test.in') li=[] while 1: inst=map(int,test.readline().split()) if inst[0]==-1: break li.append(inst[1:]) out="" if "--time" in opts or "-t" in opts: for i in runtest(li,['time','0.1','3']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(li,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a counts.dat"
[ [ 1, 0, 0.0476, 0.0476, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0952, 0.0476, 0, 0.66, 0.2, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.1429, 0.0476, 0, 0.6...
[ "import getopt,sys", "import subprocess", "from random import randint,seed", "from math import sqrt", "def runtest(li,args):\n\t# abro ./amigos con parametros: time 0.1 3\n\tfp=subprocess.Popen(['./intervalos']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor i in li:\n\t\tfp.stdin.wr...
# This file is an introductory example to # the python language of programmation. import numpy as np; def power(x,n): """ The function "power" takes two arguments : x is a real number n is an integer and returns the value y = x^n""" if (n == 0): y = 1; elif (n == 1): y = x; elif ((n %2) == 0): tmp = power (x,n/2); y = tmp*tmp; else: tmp = power(x,(n-1)/2); y = tmp*tmp*x; return y def puissances2 (x): for i in numpy.arange(10,x): print "2^", i," = ", power(2,i) def fiborec (x): if (x==0): return 0 elif (x==1): return 1 else : return (fibo(x-1) + fibo(x-2)) def fiboiter (x): first = 0 second = 1 for i in range(0,x): tmp = first + second first= second second=tmp return tmp def addmatrix(x): mat= np.array([[1,2,7], [2,5,9], [1,4,6]]) return(mat + x) def row(x): mat= np.array([[1,2,7], [2,5,9], [1,4,6]]) return(mat[x,:]) def column(x): mat= np.array([[1,2,7], [2,5,9], [1,4,6]]) return(mat[:,x]) def GenereMat(n): mat = np.ones((n,n)) for i in range(0,n): mat[:,i] = (1 + i * np.ones(n)) return (mat) def Polynome(x): p= np.poly1d([1,0]) return(p(x)*p(x) +2 *p(x) +1) def Recherche_dichotomique (P, a, b): m = (a+b)/2 if ((a-m) <= 0.1): return(m) if (P(a)*P(m) <= 0): return (Recherche_dichotomique(P, a, m)) elif (P(b)*P(m) <=0): return (Recherche_dichotomique(P, m, b)) else: return("Impossible")
[ [ 1, 0, 0.037, 0.0123, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.1605, 0.2099, 0, 0.66, 0.1, 632, 0, 2, 1, 0, 0, 0, 2 ], [ 8, 1, 0.0926, 0.0494, 1, 0.54, ...
[ "import numpy as np;", "def power(x,n):\n \"\"\" The function \"power\" takes two arguments : \n x is a real number\n n is an integer\n and returns the value y = x^n\"\"\"\n \n if (n == 0):\n y = 1;", " \"\"\" The function \"power\" takes two arguments : \n x is a real number\n ...
#Ceci est un commentaire en python. #Début du fichier.
[]
[]
# This is Python example on how to use Mongoose embeddable web server, # http://code.google.com/p/mongoose # # Before using the mongoose module, make sure that Mongoose shared library is # built and present in the current (or system library) directory import mongoose import sys # Handle /show and /form URIs. def EventHandler(event, conn, info): if event == mongoose.HTTP_ERROR: conn.printf('%s', 'HTTP/1.0 200 OK\r\n') conn.printf('%s', 'Content-Type: text/plain\r\n\r\n') conn.printf('HTTP error: %d\n', info.status_code) return True elif event == mongoose.NEW_REQUEST and info.uri == '/show': conn.printf('%s', 'HTTP/1.0 200 OK\r\n') conn.printf('%s', 'Content-Type: text/plain\r\n\r\n') conn.printf('%s %s\n', info.request_method, info.uri) if info.request_method == 'POST': content_len = conn.get_header('Content-Length') post_data = conn.read(int(content_len)) my_var = conn.get_var(post_data, 'my_var') else: my_var = conn.get_var(info.query_string, 'my_var') conn.printf('my_var: %s\n', my_var or '<not set>') conn.printf('HEADERS: \n') for header in info.http_headers[:info.num_headers]: conn.printf(' %s: %s\n', header.name, header.value) return True elif event == mongoose.NEW_REQUEST and info.uri == '/form': conn.write('HTTP/1.0 200 OK\r\n' 'Content-Type: text/html\r\n\r\n' 'Use GET: <a href="/show?my_var=hello">link</a>' '<form action="/show" method="POST">' 'Use POST: type text and submit: ' '<input type="text" name="my_var"/>' '<input type="submit"/>' '</form>') return True elif event == mongoose.NEW_REQUEST and info.uri == '/secret': conn.send_file('/etc/passwd') return True else: return False # Create mongoose object, and register '/foo' URI handler # List of options may be specified in the contructor server = mongoose.Mongoose(EventHandler, document_root='/tmp', listening_ports='8080') print ('Mongoose started on port %s, press enter to quit' % server.get_option('listening_ports')) sys.stdin.read(1) # Deleting server object stops all serving threads print 'Stopping server.' del server
[ [ 1, 0, 0.1129, 0.0161, 0, 0.66, 0, 755, 0, 1, 0, 0, 755, 0, 0 ], [ 1, 0, 0.129, 0.0161, 0, 0.66, 0.1667, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 2, 0, 0.4597, 0.5806, 0, 0...
[ "import mongoose", "import sys", "def EventHandler(event, conn, info):\n if event == mongoose.HTTP_ERROR:\n conn.printf('%s', 'HTTP/1.0 200 OK\\r\\n')\n conn.printf('%s', 'Content-Type: text/plain\\r\\n\\r\\n')\n conn.printf('HTTP error: %d\\n', info.status_code)\n return True\n ...
# Copyright (c) 2004-2009 Sergey Lyubka # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # $Id: mongoose.py 471 2009-08-30 14:30:21Z valenok $ """ This module provides python binding for the Mongoose web server. There are two classes defined: Connection: - wraps all functions that accept struct mg_connection pointer as first argument. Mongoose: wraps all functions that accept struct mg_context pointer as first argument. Creating Mongoose object automatically starts server, deleting object automatically stops it. There is no need to call mg_start() or mg_stop(). """ import ctypes import os NEW_REQUEST = 0 HTTP_ERROR = 1 EVENT_LOG = 2 INIT_SSL = 3 class mg_header(ctypes.Structure): """A wrapper for struct mg_header.""" _fields_ = [ ('name', ctypes.c_char_p), ('value', ctypes.c_char_p), ] class mg_request_info(ctypes.Structure): """A wrapper for struct mg_request_info.""" _fields_ = [ ('user_data', ctypes.c_char_p), ('request_method', ctypes.c_char_p), ('uri', ctypes.c_char_p), ('http_version', ctypes.c_char_p), ('query_string', ctypes.c_char_p), ('remote_user', ctypes.c_char_p), ('log_message', ctypes.c_char_p), ('remote_ip', ctypes.c_long), ('remote_port', ctypes.c_int), ('status_code', ctypes.c_int), ('is_ssl', ctypes.c_int), ('num_headers', ctypes.c_int), ('http_headers', mg_header * 64), ] mg_callback_t = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(mg_request_info)) class Connection(object): """A wrapper class for all functions that take struct mg_connection * as the first argument.""" def __init__(self, mongoose, connection): self.m = mongoose self.conn = ctypes.c_void_p(connection) def get_header(self, name): val = self.m.dll.mg_get_header(self.conn, name) return ctypes.c_char_p(val).value def get_var(self, data, name): size = data and len(data) or 0 buf = ctypes.create_string_buffer(size) n = self.m.dll.mg_get_var(data, size, name, buf, size) return n >= 0 and buf or None def printf(self, fmt, *args): val = self.m.dll.mg_printf(self.conn, fmt, *args) return ctypes.c_int(val).value def write(self, data): val = self.m.dll.mg_write(self.conn, data, len(data)) return ctypes.c_int(val).value def read(self, size): buf = ctypes.create_string_buffer(size) n = self.m.dll.mg_read(self.conn, buf, size) return n <= 0 and None or buf[:n] def send_file(self, path): self.m.dll.mg_send_file(self.conn, path) class Mongoose(object): """A wrapper class for Mongoose shared library.""" def __init__(self, callback, **kwargs): dll_extension = os.name == 'nt' and 'dll' or 'so' self.dll = ctypes.CDLL('_mongoose.%s' % dll_extension) self.dll.mg_start.restype = ctypes.c_void_p self.dll.mg_modify_passwords_file.restype = ctypes.c_int self.dll.mg_read.restype = ctypes.c_int self.dll.mg_write.restype = ctypes.c_int self.dll.mg_printf.restype = ctypes.c_int self.dll.mg_get_header.restype = ctypes.c_char_p self.dll.mg_get_var.restype = ctypes.c_int self.dll.mg_get_cookie.restype = ctypes.c_int self.dll.mg_get_option.restype = ctypes.c_char_p if callback: # Create a closure that will be called by the shared library. def func(event, connection, request_info): # Wrap connection pointer into the connection # object and call Python callback conn = Connection(self, connection) return callback(event, conn, request_info.contents) and 1 or 0 # Convert the closure into C callable object self.callback = mg_callback_t(func) self.callback.restype = ctypes.c_char_p else: self.callback = ctypes.c_void_p(0) args = [y for x in kwargs.items() for y in x] + [None] options = (ctypes.c_char_p * len(args))(*args) ret = self.dll.mg_start(self.callback, 0, options) self.ctx = ctypes.c_void_p(ret) def __del__(self): """Destructor, stop Mongoose instance.""" self.dll.mg_stop(self.ctx) def get_option(self, name): return self.dll.mg_get_option(self.ctx, name)
[ [ 8, 0, 0.1855, 0.0881, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.2453, 0.0063, 0, 0.66, 0.0909, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 1, 0, 0.2516, 0.0063, 0, 0.66...
[ "\"\"\"\nThis module provides python binding for the Mongoose web server.\n\nThere are two classes defined:\n\n Connection: - wraps all functions that accept struct mg_connection pointer\n as first argument.", "import ctypes", "import os", "NEW_REQUEST = 0", "HTTP_ERROR = 1", "EVENT_LOG = 2", "INIT_...
#!/usr/bin/python # Copyright 2011 Google, Inc. All Rights Reserved. # simple script to walk source tree looking for third-party licenses # dumps resulting html page to stdout import os, re, mimetypes, sys # read source directories to scan from command line SOURCE = sys.argv[1:] # regex to find /* */ style comment blocks COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL) # regex used to detect if comment block is a license COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE) COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE) EXCLUDE_TYPES = [ "application/xml", "image/png", ] # list of known licenses; keys are derived by stripping all whitespace and # forcing to lowercase to help combine multiple files that have same license. KNOWN_LICENSES = {} class License: def __init__(self, license_text): self.license_text = license_text self.filenames = [] # add filename to the list of files that have the same license text def add_file(self, filename): if filename not in self.filenames: self.filenames.append(filename) LICENSE_KEY = re.compile(r"[^\w]") def find_license(license_text): # TODO(alice): a lot these licenses are almost identical Apache licenses. # Most of them differ in origin/modifications. Consider combining similar # licenses. license_key = LICENSE_KEY.sub("", license_text).lower() if license_key not in KNOWN_LICENSES: KNOWN_LICENSES[license_key] = License(license_text) return KNOWN_LICENSES[license_key] def discover_license(exact_path, filename): # when filename ends with LICENSE, assume applies to filename prefixed if filename.endswith("LICENSE"): with open(exact_path) as file: license_text = file.read() target_filename = filename[:-len("LICENSE")] if target_filename.endswith("."): target_filename = target_filename[:-1] find_license(license_text).add_file(target_filename) return None # try searching for license blocks in raw file mimetype = mimetypes.guess_type(filename) if mimetype in EXCLUDE_TYPES: return None with open(exact_path) as file: raw_file = file.read() # include comments that have both "license" and "copyright" in the text for comment in COMMENT_BLOCK.finditer(raw_file): comment = comment.group(1) if COMMENT_LICENSE.search(comment) is None: continue if COMMENT_COPYRIGHT.search(comment) is None: continue find_license(comment).add_file(filename) for source in SOURCE: for root, dirs, files in os.walk(source): for name in files: discover_license(os.path.join(root, name), name) print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>" for license in KNOWN_LICENSES.values(): print "<h3>Notices for files:</h3><ul>" filenames = license.filenames filenames.sort() for filename in filenames: print "<li>%s</li>" % (filename) print "</ul>" print "<pre>%s</pre>" % license.license_text print "</body></html>"
[ [ 1, 0, 0.0816, 0.0102, 0, 0.66, 0, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 14, 0, 0.1224, 0.0102, 0, 0.66, 0.0714, 792, 6, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1531, 0.0102, 0, ...
[ "import os, re, mimetypes, sys", "SOURCE = sys.argv[1:]", "COMMENT_BLOCK = re.compile(r\"(/\\*.+?\\*/)\", re.MULTILINE | re.DOTALL)", "COMMENT_LICENSE = re.compile(r\"(license)\", re.IGNORECASE)", "COMMENT_COPYRIGHT = re.compile(r\"(copyright)\", re.IGNORECASE)", "EXCLUDE_TYPES = [\n \"application/xml\...
# -*- coding: utf-8 -*- # # jQuery File Upload Plugin GAE Python Example 2.0 # https://github.com/blueimp/jQuery-File-Upload # # Copyright 2011, Sebastian Tschan # https://blueimp.net # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # from __future__ import with_statement from google.appengine.api import files, images from google.appengine.ext import blobstore, deferred from google.appengine.ext.webapp import blobstore_handlers import json, re, urllib, webapp2 WEBSITE = 'http://blueimp.github.com/jQuery-File-Upload/' MIN_FILE_SIZE = 1 # bytes MAX_FILE_SIZE = 5000000 # bytes IMAGE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)') ACCEPT_FILE_TYPES = IMAGE_TYPES THUMBNAIL_MODIFICATOR = '=s80' # max width / height EXPIRATION_TIME = 300 # seconds def cleanup(blob_keys): blobstore.delete(blob_keys) class UploadHandler(webapp2.RequestHandler): def initialize(self, request, response): super(UploadHandler, self).initialize(request, response) self.response.headers['Access-Control-Allow-Origin'] = '*' self.response.headers[ 'Access-Control-Allow-Methods' ] = 'OPTIONS, HEAD, GET, POST, PUT, DELETE' def validate(self, file): if file['size'] < MIN_FILE_SIZE: file['error'] = 'File is too small' elif file['size'] > MAX_FILE_SIZE: file['error'] = 'File is too big' elif not ACCEPT_FILE_TYPES.match(file['type']): file['error'] = 'Filetype not allowed' else: return True return False def get_file_size(self, file): file.seek(0, 2) # Seek to the end of the file size = file.tell() # Get the position of EOF file.seek(0) # Reset the file position to the beginning return size def write_blob(self, data, info): blob = files.blobstore.create( mime_type=info['type'], _blobinfo_uploaded_filename=info['name'] ) with files.open(blob, 'a') as f: f.write(data) files.finalize(blob) return files.blobstore.get_blob_key(blob) def handle_upload(self): results = [] blob_keys = [] for name, fieldStorage in self.request.POST.items(): if type(fieldStorage) is unicode: continue result = {} result['name'] = re.sub(r'^.*\\', '', fieldStorage.filename) result['type'] = fieldStorage.type result['size'] = self.get_file_size(fieldStorage.file) if self.validate(result): blob_key = str( self.write_blob(fieldStorage.value, result) ) blob_keys.append(blob_key) result['delete_type'] = 'DELETE' result['delete_url'] = self.request.host_url +\ '/?key=' + urllib.quote(blob_key, '') if (IMAGE_TYPES.match(result['type'])): try: result['url'] = images.get_serving_url( blob_key, secure_url=self.request.host_url\ .startswith('https') ) result['thumbnail_url'] = result['url'] +\ THUMBNAIL_MODIFICATOR except: # Could not get an image serving url pass if not 'url' in result: result['url'] = self.request.host_url +\ '/' + blob_key + '/' + urllib.quote( result['name'].encode('utf-8'), '') results.append(result) deferred.defer( cleanup, blob_keys, _countdown=EXPIRATION_TIME ) return results def options(self): pass def head(self): pass def get(self): self.redirect(WEBSITE) def post(self): if (self.request.get('_method') == 'DELETE'): return self.delete() result = {'files': self.handle_upload()} s = json.dumps(result, separators=(',',':')) redirect = self.request.get('redirect') if redirect: return self.redirect(str( redirect.replace('%s', urllib.quote(s, ''), 1) )) if 'application/json' in self.request.headers.get('Accept'): self.response.headers['Content-Type'] = 'application/json' self.response.write(s) def delete(self): blobstore.delete(self.request.get('key') or '') class DownloadHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, key, filename): if not blobstore.get(key): self.error(404) else: # Cache for the expiration time: self.response.headers['Cache-Control'] =\ 'public,max-age=%d' % EXPIRATION_TIME self.send_blob(key, save_as=filename) app = webapp2.WSGIApplication( [ ('/', UploadHandler), ('/([^/]+)/([^/]+)', DownloadHandler) ], debug=True )
[ [ 1, 0, 0.0867, 0.0067, 0, 0.66, 0, 777, 0, 1, 0, 0, 777, 0, 0 ], [ 1, 0, 0.0933, 0.0067, 0, 0.66, 0.0667, 279, 0, 2, 0, 0, 279, 0, 0 ], [ 1, 0, 0.1, 0.0067, 0, 0.6...
[ "from __future__ import with_statement", "from google.appengine.api import files, images", "from google.appengine.ext import blobstore, deferred", "from google.appengine.ext.webapp import blobstore_handlers", "import json, re, urllib, webapp2", "WEBSITE = 'http://blueimp.github.com/jQuery-File-Upload/'", ...
''' Module which prompts the user for translations and saves them. TODO: implement @author: Rodrigo Damazio ''' class Translator(object): ''' classdocs ''' def __init__(self, language): ''' Constructor ''' self._language = language def Translate(self, string_names): print string_names
[ [ 8, 0, 0.1905, 0.3333, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.7143, 0.619, 0, 0.66, 1, 229, 0, 2, 0, 0, 186, 0, 1 ], [ 8, 1, 0.5238, 0.1429, 1, 0.29, ...
[ "'''\nModule which prompts the user for translations and saves them.\n\nTODO: implement\n\n@author: Rodrigo Damazio\n'''", "class Translator(object):\n '''\n classdocs\n '''\n\n def __init__(self, language):\n '''\n Constructor", " '''\n classdocs\n '''", " def __init__(self, language):\n '''...
''' Module which brings history information about files from Mercurial. @author: Rodrigo Damazio ''' import re import subprocess REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*') def _GetOutputLines(args): ''' Runs an external process and returns its output as a list of lines. @param args: the arguments to run ''' process = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines = True, shell = False) output = process.communicate()[0] return output.splitlines() def FillMercurialRevisions(filename, parsed_file): ''' Fills the revs attribute of all strings in the given parsed file with a list of revisions that touched the lines corresponding to that string. @param filename: the name of the file to get history for @param parsed_file: the parsed file to modify ''' # Take output of hg annotate to get revision of each line output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename]) # Create a map of line -> revision (key is list index, line 0 doesn't exist) line_revs = ['dummy'] for line in output_lines: rev_match = REVISION_REGEX.match(line) if not rev_match: raise 'Unexpected line of output from hg: %s' % line rev_hash = rev_match.group('hash') line_revs.append(rev_hash) for str in parsed_file.itervalues(): # Get the lines that correspond to each string start_line = str['startLine'] end_line = str['endLine'] # Get the revisions that touched those lines revs = [] for line_number in range(start_line, end_line + 1): revs.append(line_revs[line_number]) # Merge with any revisions that were already there # (for explict revision specification) if 'revs' in str: revs += str['revs'] # Assign the revisions to the string str['revs'] = frozenset(revs) def DoesRevisionSuperceed(filename, rev1, rev2): ''' Tells whether a revision superceeds another. This essentially means that the older revision is an ancestor of the newer one. This also returns True if the two revisions are the same. @param rev1: the revision that may be superceeding the other @param rev2: the revision that may be superceeded @return: True if rev1 superceeds rev2 or they're the same ''' if rev1 == rev2: return True # TODO: Add filename args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename] output_lines = _GetOutputLines(args) return rev2 in output_lines def NewestRevision(filename, rev1, rev2): ''' Returns which of two revisions is closest to the head of the repository. If none of them is the ancestor of the other, then we return either one. @param rev1: the first revision @param rev2: the second revision ''' if DoesRevisionSuperceed(filename, rev1, rev2): return rev1 return rev2
[ [ 8, 0, 0.0319, 0.0532, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0745, 0.0106, 0, 0.66, 0.1429, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0851, 0.0106, 0, 0.66...
[ "'''\nModule which brings history information about files from Mercurial.\n\n@author: Rodrigo Damazio\n'''", "import re", "import subprocess", "REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*')", "def _GetOutputLines(args):\n '''\n Runs an external process and returns its output as a list of lines...
''' Module which parses a string XML file. @author: Rodrigo Damazio ''' from xml.parsers.expat import ParserCreate import re #import xml.etree.ElementTree as ET class StringsParser(object): ''' Parser for string XML files. This object is not thread-safe and should be used for parsing a single file at a time, only. ''' def Parse(self, file): ''' Parses the given file and returns a dictionary mapping keys to an object with attributes for that key, such as the value, start/end line and explicit revisions. In addition to the standard XML format of the strings file, this parser supports an annotation inside comments, in one of these formats: <!-- KEEP_PARENT name="bla" --> <!-- KEEP_PARENT name="bla" rev="123456789012" --> Such an annotation indicates that we're explicitly inheriting form the master file (and the optional revision says that this decision is compatible with the master file up to that revision). @param file: the name of the file to parse ''' self._Reset() # Unfortunately expat is the only parser that will give us line numbers self._xml_parser = ParserCreate() self._xml_parser.StartElementHandler = self._StartElementHandler self._xml_parser.EndElementHandler = self._EndElementHandler self._xml_parser.CharacterDataHandler = self._CharacterDataHandler self._xml_parser.CommentHandler = self._CommentHandler file_obj = open(file) self._xml_parser.ParseFile(file_obj) file_obj.close() return self._all_strings def _Reset(self): self._currentString = None self._currentStringName = None self._currentStringValue = None self._all_strings = {} def _StartElementHandler(self, name, attrs): if name != 'string': return if 'name' not in attrs: return assert not self._currentString assert not self._currentStringName self._currentString = { 'startLine' : self._xml_parser.CurrentLineNumber, } if 'rev' in attrs: self._currentString['revs'] = [attrs['rev']] self._currentStringName = attrs['name'] self._currentStringValue = '' def _EndElementHandler(self, name): if name != 'string': return assert self._currentString assert self._currentStringName self._currentString['value'] = self._currentStringValue self._currentString['endLine'] = self._xml_parser.CurrentLineNumber self._all_strings[self._currentStringName] = self._currentString self._currentString = None self._currentStringName = None self._currentStringValue = None def _CharacterDataHandler(self, data): if not self._currentString: return self._currentStringValue += data _KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+' r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?' r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*', re.MULTILINE | re.DOTALL) def _CommentHandler(self, data): keep_parent_match = self._KEEP_PARENT_REGEX.match(data) if not keep_parent_match: return name = keep_parent_match.group('name') self._all_strings[name] = { 'keepParent' : True, 'startLine' : self._xml_parser.CurrentLineNumber, 'endLine' : self._xml_parser.CurrentLineNumber } rev = keep_parent_match.group('rev') if rev: self._all_strings[name]['revs'] = [rev]
[ [ 8, 0, 0.0261, 0.0435, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0609, 0.0087, 0, 0.66, 0.3333, 573, 0, 1, 0, 0, 573, 0, 0 ], [ 1, 0, 0.0696, 0.0087, 0, 0.66...
[ "'''\nModule which parses a string XML file.\n\n@author: Rodrigo Damazio\n'''", "from xml.parsers.expat import ParserCreate", "import re", "class StringsParser(object):\n '''\n Parser for string XML files.\n\n This object is not thread-safe and should be used for parsing a single file at\n a time, only.\n...
#!/usr/bin/python ''' Entry point for My Tracks i18n tool. @author: Rodrigo Damazio ''' import mytracks.files import mytracks.translate import mytracks.validate import sys def Usage(): print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0] print 'Commands are:' print ' cleanup' print ' translate' print ' validate' sys.exit(1) def Translate(languages): ''' Asks the user to interactively translate any missing or oudated strings from the files for the given languages. @param languages: the languages to translate ''' validator = mytracks.validate.Validator(languages) validator.Validate() missing = validator.missing_in_lang() outdated = validator.outdated_in_lang() for lang in languages: untranslated = missing[lang] + outdated[lang] if len(untranslated) == 0: continue translator = mytracks.translate.Translator(lang) translator.Translate(untranslated) def Validate(languages): ''' Computes and displays errors in the string files for the given languages. @param languages: the languages to compute for ''' validator = mytracks.validate.Validator(languages) validator.Validate() error_count = 0 if (validator.valid()): print 'All files OK' else: for lang, missing in validator.missing_in_master().iteritems(): print 'Missing in master, present in %s: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, missing in validator.missing_in_lang().iteritems(): print 'Missing in %s, present in master: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, outdated in validator.outdated_in_lang().iteritems(): print 'Outdated in %s: %s:' % (lang, str(outdated)) error_count = error_count + len(outdated) return error_count if __name__ == '__main__': argv = sys.argv argc = len(argv) if argc < 2: Usage() languages = mytracks.files.GetAllLanguageFiles() if argc == 3: langs = set(argv[2:]) if not langs.issubset(languages): raise 'Language(s) not found' # Filter just to the languages specified languages = dict((lang, lang_file) for lang, lang_file in languages.iteritems() if lang in langs or lang == 'en' ) cmd = argv[1] if cmd == 'translate': Translate(languages) elif cmd == 'validate': error_count = Validate(languages) else: Usage() error_count = 0 print '%d errors found.' % error_count
[ [ 8, 0, 0.0417, 0.0521, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0833, 0.0104, 0, 0.66, 0.125, 640, 0, 1, 0, 0, 640, 0, 0 ], [ 1, 0, 0.0938, 0.0104, 0, 0.66,...
[ "'''\nEntry point for My Tracks i18n tool.\n\n@author: Rodrigo Damazio\n'''", "import mytracks.files", "import mytracks.translate", "import mytracks.validate", "import sys", "def Usage():\n print('Usage: %s <command> [<language> ...]\\n' % sys.argv[0])\n print('Commands are:')\n print(' cleanup')\n p...
''' Module which compares languague files to the master file and detects issues. @author: Rodrigo Damazio ''' import os from mytracks.parser import StringsParser import mytracks.history class Validator(object): def __init__(self, languages): ''' Builds a strings file validator. Params: @param languages: a dictionary mapping each language to its corresponding directory ''' self._langs = {} self._master = None self._language_paths = languages parser = StringsParser() for lang, lang_dir in languages.iteritems(): filename = os.path.join(lang_dir, 'strings.xml') parsed_file = parser.Parse(filename) mytracks.history.FillMercurialRevisions(filename, parsed_file) if lang == 'en': self._master = parsed_file else: self._langs[lang] = parsed_file self._Reset() def Validate(self): ''' Computes whether all the data in the files for the given languages is valid. ''' self._Reset() self._ValidateMissingKeys() self._ValidateOutdatedKeys() def valid(self): return (len(self._missing_in_master) == 0 and len(self._missing_in_lang) == 0 and len(self._outdated_in_lang) == 0) def missing_in_master(self): return self._missing_in_master def missing_in_lang(self): return self._missing_in_lang def outdated_in_lang(self): return self._outdated_in_lang def _Reset(self): # These are maps from language to string name list self._missing_in_master = {} self._missing_in_lang = {} self._outdated_in_lang = {} def _ValidateMissingKeys(self): ''' Computes whether there are missing keys on either side. ''' master_keys = frozenset(self._master.iterkeys()) for lang, file in self._langs.iteritems(): keys = frozenset(file.iterkeys()) missing_in_master = keys - master_keys missing_in_lang = master_keys - keys if len(missing_in_master) > 0: self._missing_in_master[lang] = missing_in_master if len(missing_in_lang) > 0: self._missing_in_lang[lang] = missing_in_lang def _ValidateOutdatedKeys(self): ''' Computers whether any of the language keys are outdated with relation to the master keys. ''' for lang, file in self._langs.iteritems(): outdated = [] for key, str in file.iteritems(): # Get all revisions that touched master and language files for this # string. master_str = self._master[key] master_revs = master_str['revs'] lang_revs = str['revs'] if not master_revs or not lang_revs: print 'WARNING: No revision for %s in %s' % (key, lang) continue master_file = os.path.join(self._language_paths['en'], 'strings.xml') lang_file = os.path.join(self._language_paths[lang], 'strings.xml') # Assume that the repository has a single head (TODO: check that), # and as such there is always one revision which superceeds all others. master_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2), master_revs) lang_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2), lang_revs) # If the master version is newer than the lang version if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev): outdated.append(key) if len(outdated) > 0: self._outdated_in_lang[lang] = outdated
[ [ 8, 0, 0.0304, 0.0522, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0696, 0.0087, 0, 0.66, 0.25, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0783, 0.0087, 0, 0.66, ...
[ "'''\nModule which compares languague files to the master file and detects\nissues.\n\n@author: Rodrigo Damazio\n'''", "import os", "from mytracks.parser import StringsParser", "import mytracks.history", "class Validator(object):\n\n def __init__(self, languages):\n '''\n Builds a strings file valida...
''' Module for dealing with resource files (but not their contents). @author: Rodrigo Damazio ''' import os.path from glob import glob import re MYTRACKS_RES_DIR = 'MyTracks/res' ANDROID_MASTER_VALUES = 'values' ANDROID_VALUES_MASK = 'values-*' def GetMyTracksDir(): ''' Returns the directory in which the MyTracks directory is located. ''' path = os.getcwd() while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)): if path == '/': raise 'Not in My Tracks project' # Go up one level path = os.path.split(path)[0] return path def GetAllLanguageFiles(): ''' Returns a mapping from all found languages to their respective directories. ''' mytracks_path = GetMyTracksDir() res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK) language_dirs = glob(res_dir) master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES) if len(language_dirs) == 0: raise 'No languages found!' if not os.path.isdir(master_dir): raise 'Couldn\'t find master file' language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs] language_tuples.append(('en', master_dir)) return dict(language_tuples)
[ [ 8, 0, 0.0667, 0.1111, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1333, 0.0222, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.1556, 0.0222, 0, 0.66, ...
[ "'''\nModule for dealing with resource files (but not their contents).\n\n@author: Rodrigo Damazio\n'''", "import os.path", "from glob import glob", "import re", "MYTRACKS_RES_DIR = 'MyTracks/res'", "ANDROID_MASTER_VALUES = 'values'", "ANDROID_VALUES_MASK = 'values-*'", "def GetMyTracksDir():\n '''\n...
import urllib, urllib.request, io, os, sys, re url = "http://music.baidu.com/search/lrc" search = [('key','蒙娜丽莎的眼泪')] url_String = url + "?" + urllib.parse.urlencode(search) print(url_String) req = urllib.request.Request(url_String) fd = urllib.request.urlopen(req) print(fd) xx = fd.read() yy = xx.decode().split("'") i=0 while i<len(yy): m=re.search("\.lrc",yy[i]) if m is not None: yyy = "http://music.baidu.com" + yy[i] print (yyy) fileName = "E:\\lrc\\" + str(i) +".txt" lrc = urllib.request.Request(yyy) lrc2 = urllib.request.urlopen(lrc).read() filehandle = open(fileName,"w",encoding='utf-8') filehandle.write(lrc2.decode()) filehandle.close() print (fileName); i=i+1
[ [ 1, 0, 0.0417, 0.0417, 0, 0.66, 0, 614, 0, 6, 0, 0, 614, 0, 0 ], [ 14, 0, 0.0833, 0.0417, 0, 0.66, 0.0909, 789, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.125, 0.0417, 0, 0...
[ "import urllib, urllib.request, io, os, sys, re", "url = \"http://music.baidu.com/search/lrc\"", "search = [('key','蒙娜丽莎的眼泪')]", "url_String = url + \"?\" + urllib.parse.urlencode(search)", "print(url_String)", "req = urllib.request.Request(url_String)", "fd = urllib.request.urlopen(req)", "print(fd)"...
import random print 200 letras = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] for i in range(501,701): x=random.randint(0,len(letras)-1) s="" for j in range(i): s+=str(letras[(x+j) % len(letras)]) print "*",s
[ [ 1, 0, 0.0769, 0.0769, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 8, 0, 0.1538, 0.0769, 0, 0.66, 0.3333, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 14, 0, 0.3077, 0.0769, 0, 0...
[ "import random", "print(200)", "letras = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']", "for i in range(501,701):\n x=random.randint(0,len(letras)-1)\n s=\"\"\n for j in range(i):\n s+=str(letras[(x+j) % len(letras)])\n print(\"*\...
import random print 500 letras = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] for i in range(999501,1000001): x=random.randint(0,len(letras)-1) s="" for j in range(i): s+=str(letras[(x+j) % len(letras)]) print s
[ [ 1, 0, 0.0769, 0.0769, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 8, 0, 0.1538, 0.0769, 0, 0.66, 0.3333, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 14, 0, 0.3077, 0.0769, 0, 0...
[ "import random", "print(500)", "letras = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']", "for i in range(999501,1000001):\n x=random.randint(0,len(letras)-1)\n s=\"\"\n for j in range(i):\n s+=str(letras[(x+j) % len(letras)])\n pri...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- class GrafoCircular: def __init__(self,n,acuerdos): self.n = n self.lista_acuerdos = acuerdos # creo la matriz de acuerdos self.acuerdos = [] for i in range(n): self.acuerdos.append([0]*n) for a in acuerdos: self.acuerdos[a[0]][a[1]] = 1 self.acuerdos[a[1]][a[0]] = 1 # FIXME: la version de produccion no lleva esto # cuantos acuerdos hay? (para benchmarking posterior) self.m = sum([sum(x) for x in self.acuerdos]) / 2 def estanConectados(self,a,b): return bool(self.acuerdos[a][b]) def __repr__(self): return '<GrafoCircular de %s ciudades y %s acuerdos>' % (self.n, self.m)
[ [ 3, 0, 0.5714, 0.8929, 0, 0.66, 0, 202, 0, 3, 0, 0, 0, 0, 5 ], [ 2, 1, 0.4643, 0.6071, 1, 0.29, 0, 555, 0, 3, 0, 0, 0, 0, 4 ], [ 14, 2, 0.2143, 0.0357, 2, 0.68, ...
[ "class GrafoCircular:\n def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de acuerdos\n self.acuerdos = []", " def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- class GrafoCircular: def __init__(self,n,acuerdos): self.n = n self.lista_acuerdos = acuerdos # creo la matriz de acuerdos self.acuerdos = [] for i in range(n): self.acuerdos.append([0]*n) for a in acuerdos: self.acuerdos[a[0]][a[1]] = 1 self.acuerdos[a[1]][a[0]] = 1 # FIXME: la version de produccion no lleva esto # cuantos acuerdos hay? (para benchmarking posterior) self.m = sum([sum(x) for x in self.acuerdos]) / 2 def estanConectados(self,a,b): return bool(self.acuerdos[a][b]) def __repr__(self): return '<GrafoCircular de %s ciudades y %s acuerdos>' % (self.n, self.m)
[ [ 3, 0, 0.5714, 0.8929, 0, 0.66, 0, 202, 0, 3, 0, 0, 0, 0, 5 ], [ 2, 1, 0.4643, 0.6071, 1, 0.48, 0, 555, 0, 3, 0, 0, 0, 0, 4 ], [ 14, 2, 0.2143, 0.0357, 2, 0.16, ...
[ "class GrafoCircular:\n def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de acuerdos\n self.acuerdos = []", " def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- class Grafo: def __init__(self,n,acuerdos): self.n = n self.lista_acuerdos = acuerdos # creo la matriz de acuerdos self.acuerdos = [] for i in range(n): self.acuerdos.append([0]*n) for a in acuerdos: self.acuerdos[a[0]][a[1]] = 1 self.acuerdos[a[1]][a[0]] = 1 # FIXME: la version de produccion no lleva esto # cuantos acuerdos hay? (para benchmarking posterior) self.m = sum([sum(x) for x in self.acuerdos]) / 2 def estanConectados(self,a,b): return bool(self.acuerdos[a][b]) def __repr__(self): return '<GrafoCircular de %s ciudades y %s acuerdos>' % (self.n, self.m)
[ [ 3, 0, 0.5714, 0.8929, 0, 0.66, 0, 330, 0, 3, 0, 0, 0, 0, 5 ], [ 2, 1, 0.4643, 0.6071, 1, 0.03, 0, 555, 0, 3, 0, 0, 0, 0, 4 ], [ 14, 2, 0.2143, 0.0357, 2, 0.63, ...
[ "class Grafo:\n def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de acuerdos\n self.acuerdos = []", " def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de acuerdo...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- from grafo import Grafo from sets import Set import os import random def ordenar(t): if t[0] < t[1]: return t else: return (t[1],t[0]) def generarInstancia(ciudades=10, acuerdos=None): if acuerdos is None: acuerdos = random.randint(1, ciudades**2/2) acs = Set() cds = range(ciudades) for i in xrange(acuerdos): acs.add(ordenar(tuple(random.sample(cds,2)))) return Grafo(ciudades, list(acs)) def generarInstanciaConSolucion(ciudades=10, acuerdos=None): if acuerdos is None: acuerdos = random.randint(ciudades, ciudades**2/2) acs = Set() cds = range(ciudades) # agrego una solucion trivial for i in xrange(ciudades-1): acs.add((i, i+1)) for i in xrange(acuerdos-ciudades+1): acs.add(ordenar(tuple(random.sample(cds,2)))) return Grafo(ciudades, list(acs)) def generarInstanciaSinSolucion(ciudades=10, acuerdos=None): if acuerdos is None: acuerdos = random.randint(1, ciudades**2/2) acs = Set() cds = range(ciudades) # saco una ciudad al azar, asi el grafo no queda conexo # y fuerzo que no haya ninguna solucion valida random.shuffle(cds) cds.pop() cds.sort() for i in xrange(acuerdos): acs.add(ordenar(tuple(random.sample(cds,2)))) return Grafo(ciudades, list(acs)) def imprimirInstancia(g): print "%s %s" % (g.n, g.m) for each in g.lista_acuerdos: print "%s %s" % (each[0] + 1, each[1] + 1) print "0 0" if __name__ == '__main__': # Ejemplos de uso g1 = generarInstancia(ciudades=20, acuerdos=100) imprimirInstancia(g1) g2 = generarInstanciaConSolucion(ciudades=20, acuerdos=100) g3 = generarInstanciaSinSolucion(ciudades=20, acuerdos=100)
[ [ 1, 0, 0.0519, 0.013, 0, 0.66, 0, 503, 0, 1, 0, 0, 503, 0, 0 ], [ 1, 0, 0.0779, 0.013, 0, 0.66, 0.1111, 842, 0, 1, 0, 0, 842, 0, 0 ], [ 1, 0, 0.0909, 0.013, 0, 0.6...
[ "from grafo import Grafo", "from sets import Set", "import os", "import random", "def ordenar(t):\n if t[0] < t[1]:\n return t\n else:\n return (t[1],t[0])", " if t[0] < t[1]:\n return t\n else:\n return (t[1],t[0])", " return t", " return (t[1],t[...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- from grafo import Grafo from sets import Set import os import random def ordenar(t): if t[0] < t[1]: return t else: return (t[1],t[0]) def generarInstancia(ciudades=10, acuerdos=None): if acuerdos is None: acuerdos = random.randint(1, ciudades**2/2) acs = Set() cds = range(ciudades) for i in xrange(acuerdos): acs.add(ordenar(tuple(random.sample(cds,2)))) return Grafo(ciudades, list(acs)) def generarInstanciaConSolucion(ciudades=10, acuerdos=None): if acuerdos is None: acuerdos = random.randint(ciudades, ciudades**2/2) acs = Set() cds = range(ciudades) # agrego una solucion trivial for i in xrange(ciudades-1): acs.add((i, i+1)) for i in xrange(acuerdos-ciudades+1): acs.add(ordenar(tuple(random.sample(cds,2)))) return Grafo(ciudades, list(acs)) def generarInstanciaSinSolucion(ciudades=10, acuerdos=None): if acuerdos is None: acuerdos = random.randint(1, ciudades**2/2) acs = Set() cds = range(ciudades) # saco una ciudad al azar, asi el grafo no queda conexo # y fuerzo que no haya ninguna solucion valida random.shuffle(cds) cds.pop() cds.sort() for i in xrange(acuerdos): acs.add(ordenar(tuple(random.sample(cds,2)))) return Grafo(ciudades, list(acs)) def imprimirInstancia(g): print "%s %s" % (g.n, g.m) for each in g.lista_acuerdos: print "%s %s" % (each[0] + 1, each[1] + 1) print "0 0" if __name__ == '__main__': # Ejemplos de uso g1 = generarInstancia(ciudades=20, acuerdos=100) imprimirInstancia(g1) g2 = generarInstanciaConSolucion(ciudades=20, acuerdos=100) g3 = generarInstanciaSinSolucion(ciudades=20, acuerdos=100)
[ [ 1, 0, 0.0519, 0.013, 0, 0.66, 0, 503, 0, 1, 0, 0, 503, 0, 0 ], [ 1, 0, 0.0779, 0.013, 0, 0.66, 0.1111, 842, 0, 1, 0, 0, 842, 0, 0 ], [ 1, 0, 0.0909, 0.013, 0, 0.6...
[ "from grafo import Grafo", "from sets import Set", "import os", "import random", "def ordenar(t):\n if t[0] < t[1]:\n return t\n else:\n return (t[1],t[0])", " if t[0] < t[1]:\n return t\n else:\n return (t[1],t[0])", " return t", " return (t[1],t[...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- class Grafo: def __init__(self,n,acuerdos): self.n = n self.lista_acuerdos = acuerdos # creo la matriz de acuerdos self.acuerdos = [] for i in range(n): self.acuerdos.append([0]*n) for a in acuerdos: self.acuerdos[a[0]][a[1]] = 1 self.acuerdos[a[1]][a[0]] = 1 # FIXME: la version de produccion no lleva esto # cuantos acuerdos hay? (para benchmarking posterior) self.m = sum([sum(x) for x in self.acuerdos]) / 2 def estanConectados(self,a,b): return bool(self.acuerdos[a][b]) def __repr__(self): return '<GrafoCircular de %s ciudades y %s acuerdos>' % (self.n, self.m)
[ [ 3, 0, 0.5714, 0.8929, 0, 0.66, 0, 330, 0, 3, 0, 0, 0, 0, 5 ], [ 2, 1, 0.4643, 0.6071, 1, 0.13, 0, 555, 0, 3, 0, 0, 0, 0, 4 ], [ 14, 2, 0.2143, 0.0357, 2, 0.53, ...
[ "class Grafo:\n def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de acuerdos\n self.acuerdos = []", " def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de acuerdo...
############################################################################# valor=[] num = 0 visitado = [] fuerte = [] ############################################################################# # grafo sobre listas de adyacencia # FIXME: a las 5 a.m me parecio re coherente que si llegan se llamen out # y si salen se llaman in :S class Grafo: def __init__(self,nodos, relacion): self.nodos = nodos self.verticesIn = [[] for x in range(nodos)] self.verticesOut = [[] for x in range(nodos)] for each in relacion: self.verticesIn[each[0]].append(each[1]) self.verticesOut[each[1]].append(each[0]) def __str__(self): ret = "grafo con: "+str(self.nodos)+" nodos\n" for each in range(self.nodos): for each1 in self.verticesIn[each]: ret += str((each,each1)) + " " return ret ############################################################################ #realiza busqueda en profundidad #indexa los elementos segun el orden de la llamada recursiva #es decir, "apila" los elementos def auxbfp(grafo): global visitado global valor visitado = [0]*grafo.nodos valor = [0]*grafo.nodos global num num = 0 for i in range(grafo.nodos): if visitado[i] == 0: bfp(grafo,i) #la funcion que hace la logica del bfp que indexa def bfp(grafo,nodo): global num global visitado global valor visitado[nodo] = 1 for each in grafo.verticesIn[nodo]: if visitado[each] == 0: bfp(grafo,each) valor[num] = nodo num +=1 #transforma un grafo g en g^t, donde # g = (x,v) -> g^t = (x,v') # v'={(a,b) / (b,a) \in v} # en criollo, tiene los mismos nodos, y las flechas al reves def invertirGrafo(grafo): x=[] for each in range(grafo.nodos): for each1 in grafo.verticesIn[each]: x.append((each1,each)) return Grafo(grafo.nodos,x) # busqueda en profuncidad, parte de un nodo y mete todos los q visita en una lista # en el contexto en que se llama, logra armar las componentes fuertemente conexas de g def bfp2(grafo,nodo): global fuerte global visitado visitado[nodo] = 1 for each in grafo.verticesIn[nodo]: if visitado[each] == 0: bfp2(grafo,each) fuerte.append(nodo) # devuelve las componentes fuertemente conexas del grafo # usando el algoritmo de Kosaraju def armarFuertes(grafo): global visitado global fuerte global valor auxbfp(grafo) visitado=[0]*grafo.nodos g = invertirGrafo(grafo) fuertes = [] valor.reverse() for each in valor : if visitado[each] == 0: bfp2(g,each) fuertes.append(fuerte) fuerte=[] return fuertes def ejercicio1(grafo): global fuerte fuerte = [] fuertes = armarFuertes(grafo) dondeQuedo=[0]*grafo.nodos #en donde quedo guardo en que componente fuertemente conexa quedo cada elemento #es util para crear el grafo reducido con buen orden for i in range(len(fuertes)): for each1 in fuertes[i]: dondeQuedo[each1] = i x=[] # armo los vertices del nuevo grafo # filtro los vertices intra componente # pero quedan vertices repetidos # como diria page, la soba for i in range(grafo.nodos): for each in grafo.verticesIn[i]: if dondeQuedo[i] != dondeQuedo[each]: x.append((dondeQuedo[i],dondeQuedo[each])) #creo el grafo reducido g1=Grafo(len(fuertes),x) #galerazo: si el grafo de los partidos arreglados de un torneo, no tiene ciclos # el torneo se puede arreglar si y solo si hay un unico tipo tal que no le gana nadie # 0 no puede haber porq sino hay un ciclo en algun lado # si hay 2 o mas, no los puedo eliminar porq no les gana nadie # si hay uno, es la raiz de un pseudo-arbol (grafo dirigido aciclico) y es lo q busco #aplico galerazo para decidir quien gana yaHayUno=False quien = None for each in range(g1.nodos): if g1.verticesOut[each] == [] and not yaHayUno: quien = each yaHayUno = True elif g1.verticesOut[each] == [] and yaHayUno: print "nadie" return if not yaHayUno: print "asdsadsadsadsadsadsadasdsasad la reconchaPuta" print fuertes[quien] g = Grafo(9,[(0,1),(0,6),(6,7),(7,0),(1,3),(1,5),(5,4),(3,4),(3,2),(2,1),(2,0),(8,5),(4,8)]) ejercicio1(g) g = Grafo(3,[(0,1),(1,2),(2,0)]) ejercicio1(g) g= Grafo(3,[(0,1),(0,2)]) ejercicio1(g) g = Grafo(3,[(0,1),(2,1)]) ejercicio1(g) g = Grafo(10, [(0,1),(1,2),(2,3),(3,1),(3,4),(4,0),(4,5),(0,6),(6,5),(7,8)]) ejercicio1(g) g = Grafo(8, [(0,1),(1,2),(1,3),(0,4),(4,5),(5,6),(5,7)]) ejercicio1(g) g = Grafo(8, [(0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7)]) ejercicio1(g) g = Grafo(7, [(0,1),(1,2),(0,3),(3,4),(4,5),(4,6),(6,5),(6,3)])
[ [ 14, 0, 0.0133, 0.0067, 0, 0.66, 0, 580, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.02, 0.0067, 0, 0.66, 0.04, 328, 1, 0, 0, 0, 0, 1, 0 ], [ 14, 0, 0.0267, 0.0067, 0, 0.66,...
[ "valor=[]", "num = 0", "visitado = []", "fuerte = []", "class Grafo:\n def __init__(self,nodos, relacion):\n self.nodos = nodos\n self.verticesIn = [[] for x in range(nodos)]\n self.verticesOut = [[] for x in range(nodos)]\n for each in relacion:\n self.verticesIn[e...
import random import psyco psyco.full() class Grafo: def __init__(self,nodos, relacion): self.nodos = nodos self.verticesIn = [[] for x in range(nodos)] self.verticesOut = [[] for x in range(nodos)] for each in relacion: self.verticesIn[each[0]].append(each[1]) self.verticesOut[each[1]].append(each[0]) def __str__(self): ret = "grafo con: "+str(self.nodos)+" nodos\n" for each in range(self.nodos): for each1 in self.verticesIn[each]: ret += str((each,each1)) + " " return ret def armarDigrafo(n,m): matriz=[[ 0 for x in range(n)] for y in range(n)] pares = [(x,y) for x in range(n) for y in range(n) if x != y] z=random.sample(pares,m) ## for i in range(m): ## x=random.randint(0,n-1) ## y=random.randint(0,n-1) ## while x == y or matriz[y][x] == 1 or matriz[x][y] == 1: ## x=random.randint(0,n-1) ## y=random.randint(0,n-1) for (x,y) in z: matriz[x][y] = 1 relacion = [(x,y) for x in range(n) for y in range(n) if matriz[x][y] == 1] return relacion def resolver(grafo): global visitado res = [] for each in range(grafo.nodos): visitado = [0]*grafo.nodos if bfp(grafo,each) == grafo.nodos: res.append(each) return res def test(n,m): outp = open("test"+str(n)+str(m)+"salida.txt","w") outp1 = open("test"+str(n)+str(m)+".txt","w") for each in range(100,n): each1=((each-1)*each)/2 for each1 in range(1,min(((each-1)*each)/2,m)): rel = armarDigrafo(each,each1) outp1.write(str(each)+" "+str(each1)+"\n") if(len(rel) != each1): print "putaaaaaaaaaaaa" return for each2 in rel: outp1.write(str(each2[0]+1)+" "+ str(each2[1]+1)+"\n") g = Grafo(each,rel) res = resolver(g) sol = str(len(res)) for each3 in res: sol +=" "+str(each3+1) outp.write(sol+"\n") outp1.write("0 0") visitado =[] def bfp(grafo,nodo): global visitado if visitado[nodo] == 1: return 0 visitado[nodo] = 1 res = 0 for each in grafo.verticesIn[nodo]: if visitado[each] == 0: res+=bfp(grafo,each) return 1+res test(100,1000)
[ [ 1, 0, 0.0125, 0.0125, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.025, 0.0125, 0, 0.66, 0.1111, 17, 0, 1, 0, 0, 17, 0, 0 ], [ 8, 0, 0.0375, 0.0125, 0, 0.6...
[ "import random", "import psyco", "psyco.full()", "class Grafo:\n def __init__(self,nodos, relacion):\n self.nodos = nodos\n self.verticesIn = [[] for x in range(nodos)]\n self.verticesOut = [[] for x in range(nodos)]\n for each in relacion:\n self.verticesIn[each[0]]....
#!/usr/bin/python # -*- coding: iso-8859-1 -*- class GrafoCircular: def __init__(self,n,acuerdos): self.n = n self.lista_acuerdos = acuerdos # creo la matriz de acuerdos self.acuerdos = [] for i in range(n): self.acuerdos.append([0]*n) for a in acuerdos: self.acuerdos[a[0]][a[1]] = 1 self.acuerdos[a[1]][a[0]] = 1 # FIXME: la version de produccion no lleva esto # cuantos acuerdos hay? (para benchmarking posterior) self.m = sum([sum(x) for x in self.acuerdos]) / 2 def estanConectados(self,a,b): return bool(self.acuerdos[a][b]) def __repr__(self): return '<GrafoCircular de %s ciudades y %s acuerdos>' % (self.n, self.m)
[ [ 3, 0, 0.5714, 0.8929, 0, 0.66, 0, 202, 0, 3, 0, 0, 0, 0, 5 ], [ 2, 1, 0.4643, 0.6071, 1, 0.06, 0, 555, 0, 3, 0, 0, 0, 0, 4 ], [ 14, 2, 0.2143, 0.0357, 2, 0.32, ...
[ "class GrafoCircular:\n def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de acuerdos\n self.acuerdos = []", " def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- class GrafoCircular: def __init__(self,n,acuerdos): self.n = n self.lista_acuerdos = acuerdos # creo la matriz de acuerdos self.acuerdos = [] for i in range(n): self.acuerdos.append([0]*n) for a in acuerdos: self.acuerdos[a[0]][a[1]] = 1 self.acuerdos[a[1]][a[0]] = 1 # FIXME: la version de produccion no lleva esto # cuantos acuerdos hay? (para benchmarking posterior) self.m = sum([sum(x) for x in self.acuerdos]) / 2 def estanConectados(self,a,b): return bool(self.acuerdos[a][b]) def __repr__(self): return '<GrafoCircular de %s ciudades y %s acuerdos>' % (self.n, self.m)
[ [ 3, 0, 0.5714, 0.8929, 0, 0.66, 0, 202, 0, 3, 0, 0, 0, 0, 5 ], [ 2, 1, 0.4643, 0.6071, 1, 0.49, 0, 555, 0, 3, 0, 0, 0, 0, 4 ], [ 14, 2, 0.2143, 0.0357, 2, 0.43, ...
[ "class GrafoCircular:\n def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de acuerdos\n self.acuerdos = []", " def __init__(self,n,acuerdos):\n self.n = n\n self.lista_acuerdos = acuerdos\n\n # creo la matriz de...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- from grafocircular import GrafoCircular from sets import Set import random ################################################################# # Generador de instancias de barcos y ciudades # ################################################################# def ordenar(t): if t[0] < t[1]: return t else: return (t[1],t[0]) def generarInstancia(ciudades=10, acuerdos=None): if acuerdos is None: acuerdos = random.randint(1, ciudades**2) acs = Set() cds = range(ciudades) for i in range(acuerdos): acs.add(ordenar(tuple(random.sample(cds,2)))) return GrafoCircular(ciudades, list(acs)) def imprimirInstancia(ciudades=10, acuerdos=None): g = generarInstancia(ciudades, acuerdos) print "%s %s" % (g.n, g.m) for each in g.lista_acuerdos: print "%s %s" % each
[ [ 1, 0, 0.1212, 0.0303, 0, 0.66, 0, 295, 0, 1, 0, 0, 295, 0, 0 ], [ 1, 0, 0.1515, 0.0303, 0, 0.66, 0.2, 842, 0, 1, 0, 0, 842, 0, 0 ], [ 1, 0, 0.1818, 0.0303, 0, 0.6...
[ "from grafocircular import GrafoCircular", "from sets import Set", "import random", "def ordenar(t):\n if t[0] < t[1]:\n return t\n else:\n return (t[1],t[0])", " if t[0] < t[1]:\n return t\n else:\n return (t[1],t[0])", " return t", " return (t[1],t...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- from grafocircular import GrafoCircular from sets import Set import random ################################################################# # Generador de instancias de barcos y ciudades # ################################################################# def ordenar(t): if t[0] < t[1]: return t else: return (t[1],t[0]) def generarInstancia(ciudades=10, acuerdos=None): if acuerdos is None: acuerdos = random.randint(1, ciudades**2) acs = Set() cds = range(ciudades) for i in range(acuerdos): acs.add(ordenar(tuple(random.sample(cds,2)))) return GrafoCircular(ciudades, list(acs)) def imprimirInstancia(ciudades=10, acuerdos=None): g = generarInstancia(ciudades, acuerdos) print "%s %s" % (g.n, g.m) for each in g.lista_acuerdos: print "%s %s" % each
[ [ 1, 0, 0.1212, 0.0303, 0, 0.66, 0, 295, 0, 1, 0, 0, 295, 0, 0 ], [ 1, 0, 0.1515, 0.0303, 0, 0.66, 0.2, 842, 0, 1, 0, 0, 842, 0, 0 ], [ 1, 0, 0.1818, 0.0303, 0, 0.6...
[ "from grafocircular import GrafoCircular", "from sets import Set", "import random", "def ordenar(t):\n if t[0] < t[1]:\n return t\n else:\n return (t[1],t[0])", " if t[0] < t[1]:\n return t\n else:\n return (t[1],t[0])", " return t", " return (t[1],t...
#!/usr/bin/env python """ svg.py - Construct/display SVG scenes. The following code is a lightweight wrapper around SVG files. The metaphor is to construct a scene, add objects to it, and then write it to a file to display it. This program uses ImageMagick to display the SVG files. ImageMagick also does a remarkable job of converting SVG files into other formats. """ import os display_prog = 'display' # Command to execute to display images. class Scene: def __init__(self,name="svg",height=400,width=400): self.name = name self.items = [] self.height = height self.width = width return def add(self,item): self.items.append(item) def strarray(self): var = ["<?xml version=\"1.0\"?>\n", "<svg height=\"%d\" width=\"%d\" >\n" % (self.height,self.width), " <g style=\"fill-opacity:1.0; stroke:black;\n", " stroke-width:1;\">\n"] for item in self.items: var += item.strarray() var += [" </g>\n</svg>\n"] return var def write_svg(self,filename=None): if filename: self.svgname = filename else: self.svgname = self.name + ".svg" file = open(self.svgname,'w') file.writelines(self.strarray()) file.close() return def display(self,prog=display_prog): os.system("%s %s" % (prog,self.svgname)) return class Line: def __init__(self,start,end): self.start = start #xy tuple self.end = end #xy tuple return def strarray(self): return [" <line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n" %\ (self.start[0],self.start[1],self.end[0],self.end[1])] class Circle: def __init__(self,center,radius,color): self.center = center #xy tuple self.radius = radius #xy tuple self.color = color #rgb tuple in range(0,256) return def strarray(self): return [" <circle cx=\"%d\" cy=\"%d\" r=\"%d\"\n" %\ (self.center[0],self.center[1],self.radius), " style=\"fill:%s;\" />\n" % colorstr(self.color)] class Rectangle: def __init__(self,origin,height,width,color): self.origin = origin self.height = height self.width = width self.color = color return def strarray(self): return [" <rect x=\"%d\" y=\"%d\" height=\"%d\"\n" %\ (self.origin[0],self.origin[1],self.height), " width=\"%d\" style=\"fill:%s;\" />\n" %\ (self.width,colorstr(self.color))] class Text: def __init__(self,origin,text,size=24): self.origin = origin self.text = text self.size = size return def strarray(self): return [" <text x=\"%d\" y=\"%d\" font-size=\"%d\">\n" %\ (self.origin[0],self.origin[1],self.size), " %s\n" % self.text, " </text>\n"] def colorstr(rgb): return "#%x%x%x" % (rgb[0]/16,rgb[1]/16,rgb[2]/16) def test(): scene = Scene('test') scene.add(Rectangle((100,100),200,200,(0,255,255))) scene.add(Line((200,200),(200,300))) scene.add(Line((200,200),(300,200))) scene.add(Line((200,200),(100,200))) scene.add(Line((200,200),(200,100))) scene.add(Circle((200,200),30,(0,0,255))) scene.add(Circle((200,300),30,(0,255,0))) scene.add(Circle((300,200),30,(255,0,0))) scene.add(Circle((100,200),30,(255,255,0))) scene.add(Circle((200,100),30,(255,0,255))) scene.add(Text((50,50),"Testing SVG")) scene.write_svg() scene.display() return if __name__ == '__main__': test()
[ [ 8, 0, 0.0542, 0.0833, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1083, 0.0083, 0, 0.66, 0.1, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 14, 0, 0.1167, 0.0083, 0, 0.66, ...
[ "\"\"\"\nsvg.py - Construct/display SVG scenes.\n\nThe following code is a lightweight wrapper around SVG files. The metaphor\nis to construct a scene, add objects to it, and then write it to a file\nto display it.\n\nThis program uses ImageMagick to display the SVG files. ImageMagick also", "import os", "displ...
from GrafoBipartito import * from GeneradorGrafos import * from Dibujador import * # grafo: todos los nodos y ejes, p1 p2 estaRel(v,u) #dibujo: l1, l2 los nodos que no se pueden mover class HeuristicaInsercionEjes (ResolvedorConstructivo): # establece el rango en el cual se puede insertar un nodo # basicamente me fijo que si el tipo esta marcado, no lo trate de poner # antes de su anterior y despues de su posterior def _rango(self,x,pi,marcados): if x not in marcados: return range(len(pi)+1) else: posxMarcado = marcados.index(x) anterior=0 siguiente=len(pi)+1 if posxMarcado != 0: anterior= pi.index(marcados[posxMarcado-1])+1 if posxMarcado != len(marcados)-1: siguiente = pi.index(marcados[posxMarcado+1])+1 z=range(anterior,siguiente) if z == []: print "error", z,pi,marcados assert z != [] return z #establece los cruces entre dos nodos x e y para un dibujo dado def crucesEntre(self,x,y,p1,p2,losEjesDe): indiceX = p1.index(x) indiceY = p1.index(y) acum=0 for each in losEjesDe[x]: indiceEach = p2.index(each) for each2 in losEjesDe[y]: if indiceEach > p2.index(each2): acum += 1 return acum # heuristica de inserccion de nodos # alfa = 1 se escojen los ejes de manera de poner los q tienen un extremo adentro # alfa != 1 se eligen al azar def resolver(self,marcados1=None,marcados2=None,nodosAponer1 = None, nodosAponer2=None, p1Entrada=None,p2Entrada=None,alfa=1): #renombres p1 = list(self.dibujo.g.p1) p2 = list(self.dibujo.g.p2) grafo = self.dibujo.g dibujo=self.dibujo if marcados1 == None: #separo a los q ya estan en el dibujo (son los q tengo q mantener ordenados) marcadosl1 = list(self.dibujo.l1) else: marcadosl1 = marcados1 if marcados2 == None: marcadosl2 = list(self.dibujo.l2) else: marcadosl2 = marcados2 #print marcadosl1 #print marcadosl2 #obtengo los que tengo que poner (los q me dieron para agregar) if nodosAponer1 == None: v1 = [x for x in p1 if x not in marcadosl1] else: v1 = nodosAponer1 if nodosAponer2 == None: v2 = [y for y in p2 if y not in marcadosl2] else: v2 = nodosAponer2 #meto a todos los nodos en un "dibujo" if p1Entrada == None: p1Parcial = marcadosl1[:] else: p1Parcial = p1Entrada if p2Entrada == None: p2Parcial = marcadosl2[:] else: p2Parcial = p2Entrada #agarro los ejes del grafo ejes = list(grafo.ejes) #estos son los q ya meti y q tengo q considerar para armar el grafo ejesPuestos = [ (x,y) for (x,y) in ejes if (x in marcadosl1 and y in marcadosl2) ] #separo los q todavia no puse (Porq tienen algun nodo q no meti) ejesSinPoner = [(x,y) for (x,y) in ejes if (x in p1Parcial or y in p2Parcial) and (x,y) not in ejesPuestos] ejesSinPoner += [(x,y) for (x,y) in ejes if (x in v1 and y in v2)] #cruces=self.contarCruces(p1Parcial,p2Parcial,ejesPuestos) losEjesDe ={} #lista de adyacencia del grafo for each in (p1Parcial+p2Parcial+v1+v2): losEjesDe[each]=[] #solo pongo los ejes de los nodos fijos for (x,y) in ejesPuestos: losEjesDe[x]+=[y] losEjesDe[y]+=[x] #puesto me va a permitir saber si el nodo ya lo puse #por lo cual tengo q sacarlo y reinsertar #o es la primera vez que lo pongo puesto = {} for each in v1+v2: puesto[each] = False for each in p2Parcial + p1Parcial: puesto[each] = True #indices de los nodos en su pi correspondiente indice1 = {} indice2 = {} for par in range(len(ejesSinPoner)): #caso en el que no hay q elegir al azar if alfa == 10: each = ejesSinPoner[par] else: each = random.choice(ejesSinPoner) ejesSinPoner.remove(each) (x,y) = each cantCruces = None Pos = (None, None) #si estaba puesto lo saco, sino lo marco como q apartir de ahora #ya esta puesto if puesto[x]: p1Parcial.remove(x) else: puesto[x] = True if puesto[y]: p2Parcial.remove(y) else: puesto[y] = True #pongo el nuevo eje ejesPuestos.append((x,y)) losEjesDe[x].append(y) losEjesDe[y].append(x) #obtengo entre que nodos puedo meter a x y a y rangoi = self._rango(x,p1Parcial,marcadosl1) rangoj = self._rango(y,p2Parcial,marcadosl2) i1 = rangoi[0] j1 = rangoj[0] #lo meto en el primer lugar posible p1Parcial.insert(i1,x) pos = (i1,j1) p2Parcial.insert(j1,y) for i in range(len(p1Parcial)): indice1[p1Parcial[i]] = i for i in range(len(p2Parcial)): indice2[p2Parcial[i]] = i crucesInicial = contadorDeCruces(p1Parcial,p2Parcial,losEjesDe,indice1=indice1,indice2=indice2) cruces=crucesInicial iteracionesi = 0 posiblesPosiciones=[] for i in rangoi: iteracionesj = 0 # lo dejo en la pos i y miro todas las posiciones de p2 posibles para el nodo y for j in rangoj: actual = cruces ## print "al ubicarlos asi tengo:",actual ## print "p1",p1Parcial ## print "p2",p2Parcial if iteracionesj != len(rangoj) -1: #lo que hacemos es contar los cruces asi como estan y swapeados para saber como #cambia la cantidad de cruces crucesj = crucesEntre(y,p2Parcial[j+1],p1Parcial,losEjesDe, indice2 = indice1) crucesj1 = crucesEntre(p2Parcial[j+1],y,p1Parcial,losEjesDe, indice2 = indice1) cruces = cruces - crucesj + crucesj1 #swapeo de verdad los nodos auxj=p2Parcial[j] p2Parcial[j] = p2Parcial[j+1] p2Parcial[j+1] = auxj # si ponerlos en i,j me baja los cruces, actualizo if cantCruces == None or actual <= cantCruces: if cantCruces == actual: posiblesPosiciones.append((i,j)) else: posiblesPosiciones=[(i,j)] cantCruces=actual pos=(i,j) iteracionesj +=1 p2Parcial.remove(y) #ahora paso al nodo x a su proxima posicion if iteracionesi != len(rangoi) - 1: p2Parcial.insert(j1,y) crucesi = crucesEntre(x,p1Parcial[i+1],p2Parcial,losEjesDe,indice2=indice2) crucesi1 = crucesEntre(p1Parcial[i+1],x,p2Parcial,losEjesDe,indice2=indice2) cruces = crucesInicial - crucesi + crucesi1 crucesInicial = cruces indice1[p1Parcial[i]] = i+1 indice1[p1Parcial[i+1]] = i aux = p1Parcial[i] p1Parcial[i] = p1Parcial[i+1] p1Parcial[i+1] = aux iteracionesi += 1 p1Parcial.remove(x) if alfa != 0: pos = random.choice(posiblesPosiciones) p1Parcial.insert(pos[0],x) p2Parcial.insert(pos[1],y) #print (x,y) #print p1Parcial #print p2Parcial ## print "al eje ",(x,y),"lo inserte en",pos ## print "al hacerlo el grafo tiene", cantCruces, "cruces" ## print "p1:",p1Parcial ## print "p2:",p2Parcial #aplico una mejora a la solucion dada: si crucesEntre(x,y) >= crucesEntre(y,x), es mejor intercambiarlo (solo vale para posicioes adyacentes) for each in v1: if not puesto[each]: p1Parcial.append(each) for each in v2: if not puesto[each]: p2Parcial.append(each) return Dibujo(grafo,p1Parcial,p2Parcial) if __name__ == '__main__': #g = generarGrafoBipartitoAleatorio(5,5,11) #print 'nodos =', g.p1 #print 'nodos =', g.p2 #print 'ejes =', g.ejes #dib = generarDibujoAleatorio(g,2,2) g=GrafoBipartito(Set([1,2,3,4,5,6]),Set([7,8,9,10,11,12]),Set( [(x+1,y) for x in range(6) for y in range(7,13) if (x + y) % 2 == 0])) dib = Dibujo(g,[1,2,3],[7,8,9]) resultado = HeuristicaInsercionEjes(dib).resolver(alfa=0) print "ahora dio", resultado.contarCruces() DibujadorGrafoBipartito(resultado).grabar('dibujo.svg')
[ [ 1, 0, 0.0065, 0.0065, 0, 0.66, 0, 16, 0, 1, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0131, 0.0065, 0, 0.66, 0.3333, 590, 0, 1, 0, 0, 590, 0, 0 ], [ 1, 0, 0.0196, 0.0065, 0, 0....
[ "from GrafoBipartito import *", "from GeneradorGrafos import *", "from Dibujador import *", "class HeuristicaInsercionEjes (ResolvedorConstructivo):\n \n # establece el rango en el cual se puede insertar un nodo\n # basicamente me fijo que si el tipo esta marcado, no lo trate de poner\n # ...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo class ResolvedorBasico(ResolvedorConstructivo): def resolver(self): g = self.dibujo.g d = self.dibujo # busco los nodos que quedan por posicionar q1 = [x for x in g.p1 if not x in self.dibujo.l1] q2 = [x for x in g.p2 if not x in self.dibujo.l2] # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + q1, d.l2 + q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self._mejor(d.l1, d.l2, q1, q2) print "Listo! (cruces: %s)" % self.mejorDibujo.contarCruces() return self.mejorDibujo def _mejor(self, fijo1, fijo2, movil1, movil2): if movil1 == [] and movil2 == []: d = Dibujo(self.dibujo.g, fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self.mejorDibujo = d return # valores misc nf1 = len(fijo1) nf2 = len(fijo2) if movil1 == []: cab = movil2[0] cola = movil2[1:] for i in range(nf2+1): nuevo_fijo2 = fijo2[:] nuevo_fijo2.insert(i, cab) self._mejor(fijo1, nuevo_fijo2, movil1, cola) return else: cab = movil1[0] cola = movil1[1:] for i in range(nf1+1): nuevo_fijo1 = fijo1[:] nuevo_fijo1.insert(i, cab) self._mejor(nuevo_fijo1, fijo2, cola, movil2) return def test_resolvedorBasico(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=7, n2=7, m=15) d = generarDibujoAleatorio(g, n1=5, n2=5) r1 = ResolvedorFuerzaBruta(d) s1 = r1.resolver() r2 = ResolvedorBasico(d) s2 = r2.resolver() assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorBasico()
[ [ 1, 0, 0.0526, 0.0132, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.1184, 0.0132, 0, 0.66, 0.25, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 3, 0, 0.4605, 0.6447, 0, 0.66...
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "class ResolvedorBasico(ResolvedorConstructivo):\n def resolver(self):\n g = self.dibujo.g\n d = self.dibujo\n\n # busco los nodos que quedan por posicionar\n q1 = [x for x in g.p1 if not x in self.dibujo.l...
# Heuristica de agregar nodos de a uno y a acomodarlos from GrafoBipartito import ResolvedorConstructivo, Dibujo from Dibujador import DibujadorGrafoBipartito from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio class HeuristicaInsercionNodosPrimero(ResolvedorConstructivo): def resolver(self): d = self.dibujo g = self.dibujo.g res1 = d.l1[:] res2 = d.l2[:] movilesEnV1 = [x for x in g.p1 if not x in d.l1] # los moviles de V1 movilesEnV2 = [x for x in g.p2 if not x in d.l2] # los moviles de V2 dibujo = Dibujo(g,res1[:],res2[:]) while(movilesEnV1 != [] or movilesEnV2 != []): if movilesEnV1 != [] : v = movilesEnV1.pop(0) dibujo = self._insertarNodo(v, res1, True, dibujo) res1 = dibujo.l1[:] if movilesEnV2 != [] : v = movilesEnV2.pop(0) dibujo = self._insertarNodo(v, res2, False, dibujo) res2 = dibujo.l2[:] # ahora intento mejorar el resultado con un sort loco por cruces entre pares de nodos for i in range(len(res1)-1): ejesDe = {} v1 = res1[i] v2 = res1[i+1] if v1 not in d.l1 or v2 not in d.l1: # verifico que v1 y v2 se puedan mover ejesDe[v1] = [x[1] for x in dibujo.g.ejes if x[0] == v1] ejesDe[v2] = [x[1] for x in dibujo.g.ejes if x[0] == v2] if self._crucesEntre(v1, v2, res1, res2, ejesDe) > self._crucesEntre(v2, v1, res1, res2, ejesDe): res1[i] = v2 res1[i+1] = v1 dibujo = Dibujo(g, res1, res2) return dibujo def _insertarNodo(self, v, Vi, agregoEnV1, dibujo): g = self.dibujo.g aux = Vi[:] aux.insert(0, v) if agregoEnV1: mejorDibujo = Dibujo(g, aux[:], dibujo.l2) else: mejorDibujo = Dibujo(g, dibujo.l1, aux[:]) crucesMejorDibujo = mejorDibujo.contarCruces() for i in range(len(Vi)): aux.remove(v) aux.insert(i + 1, v) if(agregoEnV1): dibujoCandidato = Dibujo(g, aux[:], dibujo.l2) else: dibujoCandidato = Dibujo(g, dibujo.l1, aux[:]) crucesCandidato = dibujoCandidato.contarCruces() #print 'crucesCandidato', crucesCandidato #print 'crucesMejorDibujo', crucesMejorDibujo if crucesCandidato < crucesMejorDibujo : mejorDibujo = dibujoCandidato crucesMejorDibujo = crucesCandidato #print 'mejorDibujo', mejorDibujo #print 'cruces posta', mejorDibujo._contarCruces() return mejorDibujo def _crucesEntre(self,x,y,p1,p2,losEjesDe): indiceX = p1.index(x) indiceY = p1.index(y) acum = 0 for each in losEjesDe[x]: indiceEach = p2.index(each) for each2 in losEjesDe[y]: if indiceEach > p2.index(each2): acum += 1 return acum if __name__ == '__main__': g = generarGrafoBipartitoAleatorio(10,10,30) print 'nodos =', g.p1 print 'nodos =', g.p2 print 'ejes =', g.ejes dib = generarDibujoAleatorio(g,2,4) resultado = HeuristicaInsercionNodosPrimero(dib).resolver() DibujadorGrafoBipartito(resultado).grabar('dibujo.svg')
[ [ 1, 0, 0.0215, 0.0108, 0, 0.66, 0, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0323, 0.0108, 0, 0.66, 0.25, 851, 0, 1, 0, 0, 851, 0, 0 ], [ 1, 0, 0.043, 0.0108, 0, 0.66,...
[ "from GrafoBipartito import ResolvedorConstructivo, Dibujo", "from Dibujador import DibujadorGrafoBipartito", "from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio", "class HeuristicaInsercionNodosPrimero(ResolvedorConstructivo):\n def resolver(self):\n d = self.dibujo\...
import random from HeuristicaInsercionEjes import * import psyco from psyco import * class BusquedaLocalReInsercion(BusquedaLocal): def _rango(self,x,pi,marcados): if x not in marcados: return range(len(pi)+1) else: posxMarcado = marcados.index(x) anterior=0 siguiente=len(pi)+1 if posxMarcado != 0: anterior= pi.index(marcados[posxMarcado-1])+1 if posxMarcado != len(marcados)-1: siguiente = pi.index(marcados[posxMarcado+1])+1 z=range(anterior,siguiente) if z == []: print "error", z,pi,marcados assert z != [] return z def hallarMinimoLocal(self,dibujo,marcados1,marcados2,losEjesDe): crucesInicial = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) cambio = True while cambio: cambio = False self.mejorar(dibujo,marcados1,marcados2,losEjesDe) crucesActual = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) if crucesActual < crucesInicial: crucesInicial = crucesActual cambio = True def mejorar(self,dibujo,marcados1,marcados2,losEjesDe): p1 = dibujo.l1 p2=dibujo.l2 indice2={} for i in range(len(p2)): indice2[p2[i]] = i #tomamos cada tipito de p1 y vemos si lo podemos reubicar for each in p1: p1.remove(each) #rangoi es el rango donde puedo insertar al nodo sin violar el orden parcial entre los moviles rangoi = self._rango(each,p1,marcados1) p1.insert(rangoi[0],each) indice1={} crucesInicial = contadorDeCruces(p1,p2,losEjesDe,None,indice2) posMinima = rangoi[0] crucesAhora = crucesInicial crucesMin = crucesInicial for i in rangoi: if i < rangoi[len(rangoi)-1]: crucesPreSwap = contadorDeCruces(p2,[p1[i],p1[i+1]],losEjesDe,indice2,None) crucesPostSwap = contadorDeCruces(p2,[p1[i+1],p1[i]],losEjesDe,indice2,None) crucesAhora = crucesAhora - crucesPreSwap + crucesPostSwap aux = p1[i] p1[i] = p1[i+1] p1[i+1] = aux if crucesAhora < crucesMin: crucesMin = crucesAhora posMinima = i+1 p1.remove(each) p1.insert(posMinima,each) indice1={} for i in range(len(p1)): indice1[p1[i]] = i for each in p2: p2.remove(each) rangoi = self._rango(each,p2,marcados2) p2.insert(rangoi[0],each) indice2={} for i in range(len(p2)): indice2[p2[i]] = i crucesInicial = contadorDeCruces(p2,p1,losEjesDe,None,indice1) posMinima = rangoi[0] crucesAhora = crucesInicial crucesMin = crucesInicial for i in rangoi: if i < rangoi[len(rangoi)-1]: crucesPreSwap = contadorDeCruces(p1,[p2[i],p2[i+1]],losEjesDe,indice1,None) crucesPostSwap = contadorDeCruces(p1,[p2[i+1],p2[i]],losEjesDe,indice1,None) crucesAhora = crucesAhora - crucesPreSwap + crucesPostSwap aux = p2[i] p2[i] = p2[i+1] p2[i+1] = aux if crucesAhora < crucesMin: crucesMin = crucesAhora posMinima = i+1 p2.remove(each) p2.insert(posMinima,each) resultado = Dibujo(dibujo.g,p1,p2) return resultado if __name__ == '__main__': g = generarGrafoBipartitoAleatorio(12, 12, 60) d = generarDibujoAleatorio(g,3, 3) marcados1 = d.l1[:] print marcados1 marcados2 = d.l2[:] print marcados2 losEjesDe = {} for each in g.p1 : losEjesDe[each] = [] for each in g.p2 : losEjesDe[each] = [] for each in g.ejes: losEjesDe[each[0]].append(each[1]) losEjesDe[each[1]].append(each[0]) res=HeuristicaInsercionEjes(d).resolver() blIG=BusquedaLocalReInsercion() print "antes de la busqueda",res.contarCruces() blIG.hallarMinimoLocal(res,marcados1,marcados2,losEjesDe) print "despues de la misma", contadorDeCruces(res.l1,res.l2,losEjesDe) DibujadorGrafoBipartito(res,marcados1=marcados1,marcados2=marcados2).grabar('localMediana.svg')
[ [ 1, 0, 0.0083, 0.0083, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0165, 0.0083, 0, 0.66, 0.2, 287, 0, 1, 0, 0, 287, 0, 0 ], [ 1, 0, 0.0248, 0.0083, 0, 0.6...
[ "import random", "from HeuristicaInsercionEjes import *", "import psyco", "from psyco import *", "class BusquedaLocalReInsercion(BusquedaLocal):\n def _rango(self,x,pi,marcados):\n if x not in marcados:\n return range(len(pi)+1)\n else:\n posxMarcado = marcados.index...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from HeuristicaInsercionEjes import * #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo from SolucionFuerzaBruta import cuantasCombinaciones class ResolvedorSwapperConPoda(ResolvedorConstructivo): def resolver(self): g = self.dibujo.g d = self.dibujo # busco los nodos que quedan por posicionar q1 = [x for x in g.p1 if not x in self.dibujo.l1] q2 = [x for x in g.p2 if not x in self.dibujo.l2] # cargo un candidato inicial self.mejorDibujo = HeuristicaInsercionEjes(d).resolver()#Dibujo(g, d.l1 + q1, d.l2 + q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self.podas = 0 # estos son los buffers que usa el algoritmo recursivo # (todas las llamadas operan sobre los mismos para evitar copias) self.fijo1 = d.l1[:] self.fijo2 = d.l2[:] self.movil1 = q1 self.movil2 = q2 self._mejor() combinaciones = cuantasCombinaciones(d.l1, d.l2, q1, q2) porcent_podas = self.podas * 100.0 / combinaciones print "Listo! (cruces: %s, podas: %.1f%%)" % \ (self.mejorDibujo.contarCruces(), porcent_podas) return self.mejorDibujo def _mejor(self, cruces=None): # valores misc fijo1 = self.fijo1 fijo2 = self.fijo2 movil1 = self.movil1 movil2 = self.movil2 nf1 = len(fijo1) nf2 = len(fijo2) if movil1 == [] and movil2 == []: if cruces < self.mejorDibujo.contarCruces(): # creo un dibujo (copiando las listas!), y guardo la cantidad # de cruces que ya calculé en la guarda del if (evito repetir el calculo) self.mejorDibujo = Dibujo(self.dibujo.g, fijo1[:], fijo2[:]) self.mejorDibujo.cruces = cruces elif movil1 == []: cab = movil2.pop(0) fijo2.append(cab) for i in range(-1, nf2): if i != -1: # swap a = nf2-i fijo2[a], fijo2[a-1] = fijo2[a-1], fijo2[a] d = Dibujo(self.dibujo.g, fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self._mejor(cruces=d.contarCruces()) else: self.podas += cuantasCombinaciones(fijo1, fijo2, movil1, movil2) - 1 movil2.append(fijo2.pop(0)) else: cab = movil1.pop(0) fijo1.append(cab) for i in range(-1, nf1): if i != -1: # swap a = nf1-i fijo1[a], fijo1[a-1] = fijo1[a-1], fijo1[a] d = Dibujo(self.dibujo.g, fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self._mejor(cruces=d.contarCruces()) else: self.podas += cuantasCombinaciones(fijo1, fijo2, movil1, movil2) - 1 movil1.append(fijo1.pop(0)) def test_resolvedorSwapperConPoda(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=8, n2=8, m=64) d = generarDibujoAleatorio(g, n1=2, n2=2) #r1 = ResolvedorFuerzaBruta(d) #s1 = r1.resolver() r2 = ResolvedorSwapperConPoda(d) s2 = r2.resolver() #assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorSwapperConPoda()
[ [ 1, 0, 0.0357, 0.0089, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0446, 0.0089, 0, 0.66, 0.1667, 287, 0, 1, 0, 0, 287, 0, 0 ], [ 1, 0, 0.0804, 0.0089, 0, ...
[ "import sys", "from HeuristicaInsercionEjes import *", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "from SolucionFuerzaBruta import cuantasCombinaciones", "class ResolvedorSwapperConPoda(ResolvedorConstructivo):\n def resolver(self):\n g = self.dibujo.g\n d = self.dibujo\n\...
import random from HeuristicaInsercionEjes import * from HeuristicaInsercionNodosMayorGrado import * import psyco psyco.full() class BusquedaLocalIntercambioGreedy(BusquedaLocal): def swapValido(self,i,j,l,marcados): if i in marcados: if j in marcados: return False else: k = marcados.index(i) indAnterior = -1 indSiguiente = len(l)+1 if k != 0: indAnterior = l.index(marcados[k-1]) if k != len(marcados)-1: indSiguiente = l.index(marcados[k+1]) return indAnterior < l.index(j) and l.index(j) < indSiguiente elif j not in marcados: return True else: return self.swapValido(j,i,l,marcados) def hallarMinimoLocal(self,dibujo,marcados1,marcados2,losEjesDe): crucesInicial = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) cambio = True while cambio: cambio = False self.mejorar(dibujo,marcados1,marcados2,losEjesDe) crucesActual = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) if crucesActual < crucesInicial: crucesInicial = crucesActual cambio = True def mejorar(self,dibujo,marcados1,marcados2,losEjesDe): #buscamos la vecindad vecindad = [] ejes = list(dibujo.g.ejes) for i in range(len(dibujo.l1)): each = dibujo.l1[i] for j in range(i+1,len(dibujo.l1)): each2=dibujo.l1[j] if self.swapValido(each,each2,dibujo.l1,marcados1): vecindad.append((each,each2)) for i in range(len(dibujo.l2)): each = dibujo.l2[i] for j in range(i+1,len(dibujo.l2)): each2=dibujo.l2[j] if self.swapValido(each,each2,dibujo.l2,marcados2): vecindad.append((each,each2)) cruces = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) pos = None for each in vecindad: #esto se puede saber por el valor de each[0] #determino en q li eesta y hago switch if each[0] in dibujo.l1: donde = 0 i = dibujo.l1.index(each[0]) j = dibujo.l1.index(each[1]) dibujo.l1[i]=each[1] dibujo.l1[j] = each[0] else: donde = 1 i = dibujo.l2.index(each[0]) j = dibujo.l2.index(each[1]) dibujo.l2[i]=each[1] dibujo.l2[j] = each[0] #me fijo la cantidad de cruces actual, luego de switchear actual = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) #si mejora me la guardo if actual < cruces: cruces = actual pos = (i,j,each[0],each[1],donde) #pos tiene indices, valores, y q particion if donde == 0: dibujo.l1[i]=each[0] dibujo.l1[j] = each[1] else: dibujo.l2[i]=each[0] dibujo.l2[j] = each[1] if pos != None: if pos[4] == 0: dibujo.l1[pos[0]] = pos[3] dibujo.l1[pos[1]] = pos[2] else: dibujo.l2[pos[0]] = pos[3] dibujo.l2[pos[1]] = pos[2] #se hace return del nuevo dibujo y True si es que hubo cambios if __name__ == '__main__': g = generarGrafoBipartitoAleatorio(50, 50, 108) d = generarDibujoAleatorio(g,13, 21) marcados1 = d.l1[:] print marcados1 marcados2 = d.l2[:] print marcados2 losEjesDe = {} for each in g.p1 : losEjesDe[each] = [] for each in g.p2 : losEjesDe[each] = [] for each in g.ejes: losEjesDe[each[0]].append(each[1]) losEjesDe[each[1]].append(each[0]) res=HeuristicaInsercionNodosMayorGrado(d).resolver() blIG=BusquedaLocalIntercambioGreedy() print "antes de la busqueda",res.contarCruces() blIG.hallarMinimoLocal(res,marcados1,marcados2,losEjesDe) print "despues de la misma", contadorDeCruces(res.l1,res.l2,losEjesDe) DibujadorGrafoBipartito(res,marcados1=marcados1,marcados2=marcados2).grabar('localMediana.svg')
[ [ 1, 0, 0.0082, 0.0082, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0246, 0.0082, 0, 0.66, 0.1667, 287, 0, 1, 0, 0, 287, 0, 0 ], [ 1, 0, 0.0328, 0.0082, 0, ...
[ "import random", "from HeuristicaInsercionEjes import *", "from HeuristicaInsercionNodosMayorGrado import *", "import psyco", "psyco.full()", "class BusquedaLocalIntercambioGreedy(BusquedaLocal):\n \n def swapValido(self,i,j,l,marcados):\n if i in marcados:\n if j in marcados:\n ...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo class ResolvedorSwapper(ResolvedorConstructivo): def resolver(self): g = self.dibujo.g d = self.dibujo # busco los nodos que quedan por posicionar q1 = [x for x in g.p1 if not x in self.dibujo.l1] q2 = [x for x in g.p2 if not x in self.dibujo.l2] # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + q1, d.l2 + q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() # estos son los buffers que usa el algoritmo recursivo # (todas las llamadas operan sobre los mismos para evitar copias) self.fijo1 = d.l1[:] self.fijo2 = d.l2[:] self.movil1 = q1 self.movil2 = q2 self._mejor() print "Listo! (cruces: %s)" % self.mejorDibujo.contarCruces() return self.mejorDibujo def _mejor(self): # valores misc fijo1 = self.fijo1 fijo2 = self.fijo2 movil1 = self.movil1 movil2 = self.movil2 nf1 = len(fijo1) nf2 = len(fijo2) if movil1 == [] and movil2 == []: d = Dibujo(self.dibujo.g, fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): # creo un dibujo (copiando las listas!), y guardo la cantidad # de cruces que ya calculé en la guarda del if (evito repetir el calculo) self.mejorDibujo = Dibujo(self.dibujo.g, fijo1[:], fijo2[:]) self.mejorDibujo.cruces = d.contarCruces() elif movil1 == []: cab = movil2.pop(0) fijo2.append(cab) for i in range(-1, nf2): if i != -1: # swap a = nf2-i fijo2[a], fijo2[a-1] = fijo2[a-1], fijo2[a] self._mejor() movil2.append(fijo2.pop(0)) else: cab = movil1.pop(0) fijo1.append(cab) for i in range(-1, nf1): if i != -1: # swap a = nf1-i fijo1[a], fijo1[a-1] = fijo1[a-1], fijo1[a] self._mejor() movil1.append(fijo1.pop(0)) def test_resolvedorSwapper(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=7, n2=7, m=15) d = generarDibujoAleatorio(g, n1=5, n2=5) r1 = ResolvedorFuerzaBruta(d) s1 = r1.resolver() r2 = ResolvedorSwapper(d) s2 = r2.resolver() assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorSwapper()
[ [ 1, 0, 0.0396, 0.0099, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0891, 0.0099, 0, 0.66, 0.25, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 3, 0, 0.4653, 0.7228, 0, 0.66...
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "class ResolvedorSwapper(ResolvedorConstructivo):\n def resolver(self):\n g = self.dibujo.g\n d = self.dibujo\n\n # busco los nodos que quedan por posicionar\n q1 = [x for x in g.p1 if not x in self.dibujo....
#!/usr/bin/python # -*- coding: utf-8 -*- from sets import Set import svg from GrafoBipartito import GrafoBipartito, Dibujo class DibujadorGrafoBipartito: def __init__(self, dibujo, nombre="GrafoBipartito", height=800,marcados1=None,marcados2=None): self.dibujo = dibujo # calculo las dimensiones self.alto_nodos = max(len(dibujo.l1), len(dibujo.l2)) self.alto = height # radio del nodo self.rn = int(self.alto * 0.90 * 0.5 / self.alto_nodos) self.ancho = int(height/1.3) self.scene = svg.Scene(nombre, height=height, width=self.ancho) if marcados1 == None: self._dibujar() else: self._dibujarConMarcados(marcados1,marcados2) def _dibujar(self): l1 = self.dibujo.l1 l2 = self.dibujo.l2 c1 = 0.2 * self.ancho c2 = 0.8 * self.ancho m_sup = 0.13 * self.alto colorCirculo = (200,255,200) # filtro los ejes que me interesan ejes = [] for a,b in self.dibujo.g.ejes: # if ((a in l1 and b in l2) or (b in l1 and a in l2)): # if a in l2: # a,b = b,a ejes.append((a,b)) # dibujo los ejes for a,b in ejes: self.scene.add(svg.Line((c1, m_sup + l1.index(a) * 2 * self.rn), (c2, m_sup + l2.index(b) * 2 * self.rn))) # dibujo los nodos for n in l1: centro = (c1, m_sup + l1.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculo)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) for n in l2: centro = (c2, m_sup + l2.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculo)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) def _dibujarConMarcados(self,marcados1,marcados2): l1 = self.dibujo.l1 l2 = self.dibujo.l2 c1 = 0.2 * self.ancho c2 = 0.8 * self.ancho m_sup = 0.13 * self.alto colorCirculo = (200,255,200) colorCirculoMarcado = (255,200,200) # filtro los ejes que me interesan ejes = [] for a,b in self.dibujo.g.ejes: if ((a in l1 and b in l2) or (b in l1 and a in l2)): if a in l2: a,b = b,a ejes.append((a,b)) # dibujo los ejes for a,b in ejes: self.scene.add(svg.Line((c1, m_sup + l1.index(a) * 2 * self.rn), (c2, m_sup + l2.index(b) * 2 * self.rn))) # dibujo los nodos for n in l1: if n in marcados1: centro = (c1, m_sup + l1.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculoMarcado)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) else: centro = (c1, m_sup + l1.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculo)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) for n in l2: if n in marcados2: centro = (c2, m_sup + l2.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculoMarcado)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) else: centro = (c2, m_sup + l2.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculo)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) def grabar(self, filename=None): self.scene.write_svg(filename=filename) def grabarYMostrar(self): self.scene.write_svg() self.scene.display(prog="display") def test_Dibujador(): g = GrafoBipartito(Set([1,2,3,4]), Set([5,6,7,8,9]), Set([(4,6),(4,5),(3,5),(3,7),(2,6),(1,7),(3,8),(2,9),(4,8)])) d = Dibujo(g,[1,2,3,4],[5,6,7,8,9]) dib = DibujadorGrafoBipartito(d) dib.grabarYMostrar() dib.grabar('test.svg') if __name__ == '__main__': test_Dibujador()
[ [ 1, 0, 0.0312, 0.0078, 0, 0.66, 0, 842, 0, 1, 0, 0, 842, 0, 0 ], [ 1, 0, 0.0469, 0.0078, 0, 0.66, 0.2, 873, 0, 1, 0, 0, 873, 0, 0 ], [ 1, 0, 0.0547, 0.0078, 0, 0.6...
[ "from sets import Set", "import svg", "from GrafoBipartito import GrafoBipartito, Dibujo", "class DibujadorGrafoBipartito:\n def __init__(self, dibujo, nombre=\"GrafoBipartito\", height=800,marcados1=None,marcados2=None):\n self.dibujo = dibujo\n\n # calculo las dimensiones\n self.alto...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo from SolucionFuerzaBruta import cuantasCombinaciones class ResolvedorBasicoConPoda(ResolvedorConstructivo): def resolver(self): g = self.dibujo.g d = self.dibujo # busco los nodos que quedan por posicionar q1 = [x for x in g.p1 if not x in self.dibujo.l1] q2 = [x for x in g.p2 if not x in self.dibujo.l2] # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + q1, d.l2 + q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self.podas = 0 self._mejor(d.l1, d.l2, q1, q2) combinaciones = cuantasCombinaciones(d.l1, d.l2, q1, q2) porcent_podas = self.podas * 100.0 / combinaciones print "Listo! (cruces: %s, podas: %.1f%%)" % \ (self.mejorDibujo.contarCruces(), porcent_podas) return self.mejorDibujo def _mejor(self, fijo1, fijo2, movil1, movil2, cruces=None): if movil1 == [] and movil2 == []: if cruces < self.mejorDibujo.contarCruces(): d = Dibujo(self.dibujo.g, fijo1, fijo2) self.mejorDibujo = d return # valores misc nf1 = len(fijo1) nf2 = len(fijo2) if movil1 == []: cab = movil2[0] cola = movil2[1:] for i in range(nf2+1): nuevo_fijo2 = fijo2[:] nuevo_fijo2.insert(i, cab) d = Dibujo(self.dibujo.g, fijo1, nuevo_fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self._mejor(fijo1, nuevo_fijo2, movil1, cola, cruces=d.contarCruces()) else: self.podas += cuantasCombinaciones(fijo1, nuevo_fijo2, movil1, cola) - 1 return else: cab = movil1[0] cola = movil1[1:] for i in range(nf1+1): nuevo_fijo1 = fijo1[:] nuevo_fijo1.insert(i, cab) d = Dibujo(self.dibujo.g, nuevo_fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self._mejor(nuevo_fijo1, fijo2, cola, movil2, cruces=d.contarCruces()) else: self.podas += cuantasCombinaciones(nuevo_fijo1, fijo2, cola, movil2) - 1 return def test_resolvedorBasicoConPoda(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=7, n2=7, m=15) d = generarDibujoAleatorio(g, n1=5, n2=5) r1 = ResolvedorFuerzaBruta(d) s1 = r1.resolver() r2 = ResolvedorBasicoConPoda(d) s2 = r2.resolver() assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorBasicoConPoda()
[ [ 1, 0, 0.0444, 0.0111, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.1, 0.0111, 0, 0.66, 0.2, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.1111, 0.0111, 0, 0.66, ...
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "from SolucionFuerzaBruta import cuantasCombinaciones", "class ResolvedorBasicoConPoda(ResolvedorConstructivo):\n def resolver(self):\n g = self.dibujo.g\n d = self.dibujo\n\n # busco los nodos que quedan por po...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo class ResolvedorSwapper(ResolvedorConstructivo): def resolver(self): g = self.dibujo.g d = self.dibujo # busco los nodos que quedan por posicionar q1 = [x for x in g.p1 if not x in self.dibujo.l1] q2 = [x for x in g.p2 if not x in self.dibujo.l2] # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + q1, d.l2 + q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() # estos son los buffers que usa el algoritmo recursivo # (todas las llamadas operan sobre los mismos para evitar copias) self.fijo1 = d.l1[:] self.fijo2 = d.l2[:] self.movil1 = q1 self.movil2 = q2 self._mejor() print "Listo! (cruces: %s)" % self.mejorDibujo.contarCruces() return self.mejorDibujo def _mejor(self): # valores misc fijo1 = self.fijo1 fijo2 = self.fijo2 movil1 = self.movil1 movil2 = self.movil2 nf1 = len(fijo1) nf2 = len(fijo2) if movil1 == [] and movil2 == []: d = Dibujo(self.dibujo.g, fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): # creo un dibujo (copiando las listas!), y guardo la cantidad # de cruces que ya calculé en la guarda del if (evito repetir el calculo) self.mejorDibujo = Dibujo(self.dibujo.g, fijo1[:], fijo2[:]) self.mejorDibujo.cruces = d.contarCruces() elif movil1 == []: cab = movil2.pop(0) fijo2.append(cab) for i in range(-1, nf2): if i != -1: # swap a = nf2-i fijo2[a], fijo2[a-1] = fijo2[a-1], fijo2[a] self._mejor() movil2.append(fijo2.pop(0)) else: cab = movil1.pop(0) fijo1.append(cab) for i in range(-1, nf1): if i != -1: # swap a = nf1-i fijo1[a], fijo1[a-1] = fijo1[a-1], fijo1[a] self._mejor() movil1.append(fijo1.pop(0)) def test_resolvedorSwapper(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=7, n2=7, m=15) d = generarDibujoAleatorio(g, n1=5, n2=5) r1 = ResolvedorFuerzaBruta(d) s1 = r1.resolver() r2 = ResolvedorSwapper(d) s2 = r2.resolver() assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorSwapper()
[ [ 1, 0, 0.0396, 0.0099, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0891, 0.0099, 0, 0.66, 0.25, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 3, 0, 0.4653, 0.7228, 0, 0.66...
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "class ResolvedorSwapper(ResolvedorConstructivo):\n def resolver(self):\n g = self.dibujo.g\n d = self.dibujo\n\n # busco los nodos que quedan por posicionar\n q1 = [x for x in g.p1 if not x in self.dibujo....
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from HeuristicaInsercionEjes import * #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo from SolucionFuerzaBruta import cuantasCombinaciones class ResolvedorSwapperConPoda(ResolvedorConstructivo): def resolver(self): g = self.dibujo.g d = self.dibujo # busco los nodos que quedan por posicionar q1 = [x for x in g.p1 if not x in self.dibujo.l1] q2 = [x for x in g.p2 if not x in self.dibujo.l2] # cargo un candidato inicial self.mejorDibujo = HeuristicaInsercionEjes(d).resolver()#Dibujo(g, d.l1 + q1, d.l2 + q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self.podas = 0 # estos son los buffers que usa el algoritmo recursivo # (todas las llamadas operan sobre los mismos para evitar copias) self.fijo1 = d.l1[:] self.fijo2 = d.l2[:] self.movil1 = q1 self.movil2 = q2 self._mejor() combinaciones = cuantasCombinaciones(d.l1, d.l2, q1, q2) porcent_podas = self.podas * 100.0 / combinaciones print "Listo! (cruces: %s, podas: %.1f%%)" % \ (self.mejorDibujo.contarCruces(), porcent_podas) return self.mejorDibujo def _mejor(self, cruces=None): # valores misc fijo1 = self.fijo1 fijo2 = self.fijo2 movil1 = self.movil1 movil2 = self.movil2 nf1 = len(fijo1) nf2 = len(fijo2) if movil1 == [] and movil2 == []: if cruces < self.mejorDibujo.contarCruces(): # creo un dibujo (copiando las listas!), y guardo la cantidad # de cruces que ya calculé en la guarda del if (evito repetir el calculo) self.mejorDibujo = Dibujo(self.dibujo.g, fijo1[:], fijo2[:]) self.mejorDibujo.cruces = cruces elif movil1 == []: cab = movil2.pop(0) fijo2.append(cab) for i in range(-1, nf2): if i != -1: # swap a = nf2-i fijo2[a], fijo2[a-1] = fijo2[a-1], fijo2[a] d = Dibujo(self.dibujo.g, fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self._mejor(cruces=d.contarCruces()) else: self.podas += cuantasCombinaciones(fijo1, fijo2, movil1, movil2) - 1 movil2.append(fijo2.pop(0)) else: cab = movil1.pop(0) fijo1.append(cab) for i in range(-1, nf1): if i != -1: # swap a = nf1-i fijo1[a], fijo1[a-1] = fijo1[a-1], fijo1[a] d = Dibujo(self.dibujo.g, fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self._mejor(cruces=d.contarCruces()) else: self.podas += cuantasCombinaciones(fijo1, fijo2, movil1, movil2) - 1 movil1.append(fijo1.pop(0)) def test_resolvedorSwapperConPoda(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=8, n2=8, m=64) d = generarDibujoAleatorio(g, n1=2, n2=2) #r1 = ResolvedorFuerzaBruta(d) #s1 = r1.resolver() r2 = ResolvedorSwapperConPoda(d) s2 = r2.resolver() #assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorSwapperConPoda()
[ [ 1, 0, 0.0357, 0.0089, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0446, 0.0089, 0, 0.66, 0.1667, 287, 0, 1, 0, 0, 287, 0, 0 ], [ 1, 0, 0.0804, 0.0089, 0, ...
[ "import sys", "from HeuristicaInsercionEjes import *", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "from SolucionFuerzaBruta import cuantasCombinaciones", "class ResolvedorSwapperConPoda(ResolvedorConstructivo):\n def resolver(self):\n g = self.dibujo.g\n d = self.dibujo\n\...
#!/usr/bin/python # -*- coding: utf-8 -*- from GrafoBipartito import Dibujo, ResolvedorConstructivo import sys #import psyco #psyco.full() class ResolvedorFuerzaBruta(ResolvedorConstructivo): def resolver(self): # busco los nodos que quedan por posicionar q1 = [x for x in self.dibujo.g.p1 if not x in self.dibujo.l1] q2 = [x for x in self.dibujo.g.p2 if not x in self.dibujo.l2] # genero todos los posibles dibujos print "Generando soluciones posibles... ", sys.stdout.flush() combs = combinaciones(self.dibujo.l1, self.dibujo.l2, q1, q2) print "Listo! (total: %s)" % len(combs) # elijo el mejor print "Eligiendo solución óptima... ", sys.stdout.flush() l1, l2 = combs.pop() mejor = Dibujo(self.dibujo.g, l1, l2) cruces = mejor.contarCruces() for c in combs: d = Dibujo(self.dibujo.g, c[0], c[1]) if d.contarCruces() < cruces: mejor = d cruces = d.contarCruces() print "Listo! (cruces: %s)" % cruces return mejor def combinaciones(fijo1, fijo2, movil1, movil2): '''Construye todos los dibujos incrementales sobre fijo1, fijo2''' if movil1 == [] and movil2 == []: return [(fijo1, fijo2)] # algunos valores misc nf1 = len(fijo1) nf2 = len(fijo2) # posiciono los moviles 2 if movil1 == []: cab = movil2[0] cola = movil2[1:] ops = [] for i in range(nf2+1): nuevo_fijo2 = fijo2[:] nuevo_fijo2.insert(i, cab) ops += combinaciones(fijo1, nuevo_fijo2, movil1, cola) return ops # posiciono los moviles 1 else: cab = movil1[0] cola = movil1[1:] ops = [] for i in range(nf1+1): nuevo_fijo1 = fijo1[:] nuevo_fijo1.insert(i, cab) ops += combinaciones(nuevo_fijo1, fijo2, cola, movil2) return ops def cuantasCombinaciones(fijo1, fijo2, movil1, movil2): '''Calcula el cardinal del universo de soluciones posibles de esta instancia''' if isinstance(fijo1, list) and \ isinstance(fijo2, list) and \ isinstance(movil1, list) and \ isinstance(movil2, list): f1, f2, m1, m2 = map(len, [fijo1, fijo2, movil1, movil2]) else: f1, f2, m1, m2 = fijo1, fijo2, movil1, movil2 c = 1 for i in range(m1): c *= f1 + i + 1 for i in range(m2): c *= f2 + i + 1 return c def tamTree(fijo1, fijo2, movil1, movil2): if isinstance(fijo1, list) and \ isinstance(fijo2, list) and \ isinstance(movil1, list) and \ isinstance(movil2, list): f1, f2, m1, m2 = map(len, [fijo1, fijo2, movil1, movil2]) else: f1, f2, m1, m2 = fijo1, fijo2, movil1, movil2 if m1 == 0 and m2 == 0: return 1 elif m2 != 0: return (f2+1)*tamTree(f1, f2+1, m1, m2-1) + 1 elif m1 != 0: return (f1+1)*tamTree(f1+1, f2, m1-1, m2) + 1 def tamArbol(fijo1,fijo2,movil1,movil2): if isinstance(fijo1, list) and \ isinstance(fijo2, list) and \ isinstance(movil1, list) and \ isinstance(movil2, list): f1, f2, m1, m2 = map(len, [fijo1, fijo2, movil1, movil2]) else: f1, f2, m1, m2 = fijo1, fijo2, movil1, movil2 arbol1 = tamTree(f1,0,m1,0) arbol2 = tamTree(0,f2,0,m2) return arbol1 + cuantasCombinaciones(f1, 0, m1, 0)*(arbol2 -1) def test_resolvedorFuerzaBruta(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio g = generarGrafoBipartitoAleatorio(n1=8, n2=8, m=15) d = generarDibujoAleatorio(g,n1=5, n2=5) r = ResolvedorFuerzaBruta(d) s = r.resolver() if __name__ == '__main__': test_resolvedorFuerzaBruta()
[ [ 1, 0, 0.0301, 0.0075, 0, 0.66, 0, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0451, 0.0075, 0, 0.66, 0.125, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 3, 0, 0.188, 0.218, 0, 0.66,...
[ "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "import sys", "class ResolvedorFuerzaBruta(ResolvedorConstructivo):\n def resolver(self):\n # busco los nodos que quedan por posicionar\n q1 = [x for x in self.dibujo.g.p1 if not x in self.dibujo.l1]\n q2 = [x for x in self.dib...
#!/usr/bin/python # -*- coding: utf-8 -*- from GrafoBipartito import ResolvedorConstructivo, Dibujo from GrafoBipartito import crucesEntre, crucesPorAgregarAtras from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio import random class HeuristicaInsercionNodos(ResolvedorConstructivo): ########################################################### # Funcion global de aplicación de la heurística # ########################################################### def resolver(self, alfa=1, randomPos=False): assert 0 < alfa <= 1 self.alfa = alfa self.randomPos = randomPos self._inicializar() # Ejecuto la heuristica constructiva greedy while self.movil1 != [] or self.movil2 != []: if self.movil1 != []: sig = self._tomarSiguiente1() self._insertarEn1(sig) if self.movil2 != []: sig = self._tomarSiguiente2() self._insertarEn2(sig) d = Dibujo(self.dibujo.g, self.fijo1, self.fijo2) assert self.cruces == d.contarCruces() return d ########################################################### # Función auxiliar de inicialización # ########################################################### def _inicializar(self): d = self.dibujo g = self.dibujo.g self.fijo1 = d.l1[:] self.fijo2 = d.l2[:] # FIXME: esto es O(n^2) y se puede mejorar en la version definitiva self.movil1 = [x for x in g.p1 if not x in d.l1] self.movil2 = [x for x in g.p2 if not x in d.l2] # Guardo en un diccionario quien es movil y quien no # (este diccionario se ira modificando a medida que voy "fijando" nodos) self.esMovil = {} for each in self.fijo1: self.esMovil[each] = False for each in self.fijo2: self.esMovil[each] = False for each in self.movil1: self.esMovil[each] = True for each in self.movil2: self.esMovil[each] = True esMovil = self.esMovil # Construyo 3 diccionarios que voy a necesitar: self.ady = {} # listas de adyacencia del grafo completo self.adyParcial = {} # listas de adyacencia del subgrafo ya fijado self.gradoParcial = {} # grados de los nodos (moviles) contando solo los ejes # que van a los nodos ya fijados for each in g.p1: self.ady[each] = [] self.gradoParcial[each] = 0 if not esMovil[each]: self.adyParcial[each] = [] for each in g.p2: self.ady[each] = [] self.gradoParcial[each] = 0 if not esMovil[each]: self.adyParcial[each] = [] for a,b in g.ejes: self.ady[a].append(b) self.ady[b].append(a) if not esMovil[a] and not esMovil[b]: self.adyParcial[a].append(b) self.adyParcial[b].append(a) if not esMovil[a] or not esMovil[b]: self.gradoParcial[a] += 1 self.gradoParcial[b] += 1 # Almaceno para los nodos fijos su posicion en la particion # que les corresponde - esto permite agilizar los conteos de cruces. self.posiciones = {} for i in range(len(self.fijo1)): self.posiciones[self.fijo1[i]] = i for i in range(len(self.fijo2)): self.posiciones[self.fijo2[i]] = i # Guardo los cruces del dibujo fijo como punto de partida # para ir incrementando sobre este valor a medida que agrego nodos. self.cruces = d.contarCruces() ########################################################### # Funciones auxiliares de selección de nodos # ########################################################### def _tomarSiguiente(self, moviles): # Ordeno los moviles por grado self._ordenarPorGradoParcial(moviles) maximoGrado = self.gradoParcial[moviles[0]] alfaMaximoGrado = maximoGrado * self.alfa # Elijo al azar alguno de los que superan el grado alfa-maximo ultimoQueSupera = 0 while ultimoQueSupera + 1 < len(moviles) and \ self.gradoParcial[moviles[ultimoQueSupera + 1]] >= alfaMaximoGrado: ultimoQueSupera += 1 elegido = random.randint(0,ultimoQueSupera) e = moviles.pop(elegido) del self.gradoParcial[e] return e def _tomarSiguiente1(self): return self._tomarSiguiente(self.movil1) def _tomarSiguiente2(self): return self._tomarSiguiente(self.movil2) def _ordenarPorGradoParcial(self, moviles): # FIXME: ordena por grado en orden decreciente, implementado con alto orden :P moviles.sort(lambda x,y: -cmp(self.gradoParcial[x], self.gradoParcial[y])) ########################################################### # Funciones auxiliares de inserción de nodos # ########################################################### def _insertar(self, nodo, fijos, otrosFijos): self.esMovil[nodo] = False # Actualizo la lista de adyacencias parcial para incorporar las adyacencias # del nodo que voy a agregar - esto es necesario puesto que las funciones de conteo # de cruces se usan dentro del subgrafo fijo y por tanto para que tengan en cuenta # al nodo a agregar, es necesario completarlas con sus ejes. self.adyParcial[nodo] = [] for vecino in self.ady[nodo]: if not self.esMovil[vecino]: self.adyParcial[vecino].append(nodo) self.adyParcial[nodo].append(vecino) # Busco las mejores posiciones en la particion para insertar este nodo, comenzando # por el final y swapeando hacia atrás hasta obtener las mejores. fijos.append(nodo) cruces = self.cruces + crucesPorAgregarAtras(fijos, otrosFijos, self.adyParcial, indice2=self.posiciones) pos = len(fijos) - 1 mejorCruces = cruces posValidas = [pos] while pos > 0: pos = pos - 1 cruces = (cruces - crucesEntre(fijos[pos], fijos[pos+1], otrosFijos, self.adyParcial, indice2=self.posiciones) + crucesEntre(fijos[pos+1], fijos[pos], otrosFijos, self.adyParcial, indice2=self.posiciones)) fijos[pos], fijos[pos+1] = fijos[pos+1], fijos[pos] if cruces == mejorCruces: posValidas.append(pos) if cruces < mejorCruces: mejorCruces = cruces posValidas = [pos] # Inserto el nodo en alguna de las mejores posiciones if self.randomPos: mejorPos = random.choice(posValidas) else: mejorPos = posValidas[0] fijos.pop(0) fijos.insert(mejorPos, nodo) self.cruces = mejorCruces # Actualizo los grados parciales for a in self.ady[nodo]: if self.esMovil[a]: self.gradoParcial[a] += 1 # Actualizo las posiciones for i in range(len(fijos)): self.posiciones[fijos[i]] = i def _insertarEn1(self, nodo): return self._insertar(nodo, self.fijo1, self.fijo2) def _insertarEn2(self, nodo): return self._insertar(nodo, self.fijo2, self.fijo1) def test_HeuristicaInsercionNodos(): g = generarGrafoBipartitoAleatorio(n1=25,n2=25,m=500) d = generarDibujoAleatorio(g,n1=5,n2=5) h = HeuristicaInsercionNodos(d) s = h.resolver(alfa=1) print s s2 = h.resolver(alfa=1,randomPos=True) print s2 s3 = h.resolver(alfa=0.6) print s3 s4 = h.resolver(alfa=0.6, randomPos=True) print s4 if __name__ == '__main__': test_HeuristicaInsercionNodos()
[ [ 1, 0, 0.0174, 0.0043, 0, 0.66, 0, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0217, 0.0043, 0, 0.66, 0.1667, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0261, 0.0043, 0, 0.66...
[ "from GrafoBipartito import ResolvedorConstructivo, Dibujo", "from GrafoBipartito import crucesEntre, crucesPorAgregarAtras", "from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio", "import random", "class HeuristicaInsercionNodos(ResolvedorConstructivo):\n\n ###############...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo from GrafoBipartito import crucesEntre, crucesPorAgregarAdelante, crucesPorAgregarAtras from SolucionFuerzaBruta import cuantasCombinaciones, tamArbol class ResolvedorSwapperTablaConPoda(ResolvedorConstructivo): ########################################################### # Funcion global de resolución exacta # ########################################################### def resolver(self, invertir=True): self.invertir = invertir g = self.dibujo.g d = self.dibujo self._inicializar() # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + self.q1, d.l2 + self.q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self.podasHojas = 0 self.podasArbol = 0 self.casosBase = 0 self.llamadas = 0 combinaciones = cuantasCombinaciones(self.fijo1, self.fijo2, self.movil1, self.movil2) tamanioArbol = tamArbol(self.fijo1, self.fijo2, self.movil1, self.movil2) self._mejor() assert tamanioArbol == self.llamadas + self.podasArbol assert combinaciones == self.casosBase + self.podasHojas porcent_podasArbol = (self.podasArbol * 100.0) / tamanioArbol porcent_podasHojas = (self.podasHojas * 100.0) / combinaciones print "Listo! (cruces: %s, podas: %.6f%% de nodos, %.6f%% de hojas)" % \ (self.mejorDibujo.contarCruces(), porcent_podasArbol, porcent_podasHojas) return self.mejorDibujo ########################################################### # Función auxiliar de inicialización # ########################################################### def _inicializar(self): g = self.dibujo.g d = self.dibujo # armo las listas de adyacencia del grafo completo ady = {} for n in g.p1: ady[n] = [] for n in g.p2: ady[n] = [] for a,b in g.ejes: ady[a].append(b) ady[b].append(a) self.ady = ady # busco los nodos que quedan por posicionar self.q1 = [x for x in g.p1 if not x in self.dibujo.l1] self.q2 = [x for x in g.p2 if not x in self.dibujo.l2] # elijo cual de las 2 mitades tiene menos permutaciones # para llenarla primero en el arbol de combinaciones # (esto puede mejorar el rendimiento del algoritmo) combs1 = cuantasCombinaciones(len(d.l1),0,len(self.q1),0) combs2 = cuantasCombinaciones(len(d.l2),0,len(self.q2),0) if combs1 > combs2: invertirLados = True else: invertirLados = False if not self.invertir: invertirLados = False self.invertirLados = invertirLados # estos son los buffers que usa el algoritmo recursivo # (todas las llamadas operan sobre los mismos para evitar copias) if invertirLados: self.fijo1 = d.l2[:] self.fijo2 = d.l1[:] self.movil1 = self.q2 self.movil2 = self.q1 self.l1 = list(g.p2) self.l2 = list(g.p1) else: self.fijo1 = d.l1[:] self.fijo2 = d.l2[:] self.movil1 = self.q1 self.movil2 = self.q2 self.l1 = list(g.p1) self.l2 = list(g.p2) # armo las listas de adyacencia de p1 con los de d.l1 # (esto me permite calcular de forma eficiente los cruces # de una cierta permutacion de p1) adyp1 = {} if invertirLados: p1 = g.p2 else: p1 = g.p1 for n in p1: adyp1[n] = [] if not invertirLados: for a,b in g.ejes: if a in adyp1 and b in self.fijo2: adyp1[a].append(b) elif b in adyp1 and a in self.fijo2: adyp1[b].append(a) else: for b,a in g.ejes: if a in adyp1 and b in self.fijo2: adyp1[a].append(b) elif b in adyp1 and a in self.fijo2: adyp1[b].append(a) self.adyp1 = adyp1 # cache de posiciones para evitar busquedas self.posiciones1 = {} for i in range(len(self.fijo1)): self.posiciones1[self.fijo1[i]] = i self.posiciones2 = {} for i in range(len(self.fijo2)): self.posiciones2[self.fijo2[i]] = i # Cache de cruces para reutilizar calculos # tablaN[(i,j)] es la cantidad de cruces que hay entre # los nodos i,j si son contiguos en el candidato actual de pN self._tabular1() if self.movil1 == []: self._tabular2() # cargo los cruces del dibujo original self.cruces = d.contarCruces() def _tabular1(self): # Inicializa la tabla de valores precalculados para p1 (vs. fijo2) # FIXME: hay calculos innecesarios self.tabla1 = {} for i in self.l1: for j in self.l1: if i < j: c = crucesEntre(i, j, self.fijo2, self.adyp1,indice2=self.posiciones2) self.tabla1[(i,j)] = c c = crucesEntre(j, i, self.fijo2, self.adyp1,indice2=self.posiciones2) self.tabla1[(j,i)] = c def _tabular2(self): # Reinicia la tabla de valores precalculados para p2 cuando cambia p1 # FIXME: hay calculos innecesarios self.tabla2 = {} for i in self.l2: for j in self.l2: if i < j: c = crucesEntre(i,j, self.fijo1, self.ady,indice2=self.posiciones1) self.tabla2[(i,j)] = c c = crucesEntre(j,i, self.fijo1, self.ady,indice2=self.posiciones1) self.tabla2[(j,i)] = c def _minimosCrucesRestantes2(self): c = 0 for i in self.movil2: for j in self.movil2: if i < j: c += min(self.tabla2[(i,j)], self.tabla2[(j,i)]) for j in self.fijo2: c += min(self.tabla2[(i,j)], self.tabla2[(j,i)]) return c def _minimosCrucesRestantes1(self): c = 0 for i in self.movil1: for j in self.movil1: if i < j: c += min(self.tabla1[(i,j)], self.tabla1[(j,i)]) for j in self.fijo1: c += min(self.tabla1[(i,j)], self.tabla1[(j,i)]) return c ########################################################### # Funciones auxiliares para modificacion de candidatos # ########################################################### # mueve movil1[0] a fijo1[n] def _agregarAtras1(self): cab = self.movil1.pop(0) self.fijo1.append(cab) self.posiciones1[cab] = len(self.fijo1) - 1 self.cruces += crucesPorAgregarAtras(self.fijo1, self.fijo2, self.adyp1, indice2=self.posiciones2) # analogo para p1 def _agregarAtras2(self): cab = self.movil2.pop(0) self.fijo2.append(cab) self.cruces += crucesPorAgregarAtras(self.fijo2, self.fijo1, self.ady, indice2=self.posiciones1) # mueve fijo1[0] a movil1[n] def _sacarPrincipio1(self): self.cruces -= crucesPorAgregarAdelante(self.fijo1, self.fijo2, self.adyp1, indice2=self.posiciones2) self.movil1.append(self.fijo1.pop(0)) # FIXME: esta operacion se puede ahorrar con un # offset entero que se resta a todas las posiciones for i in range(len(self.fijo1)): self.posiciones1[self.fijo1[i]] = i # analogo para p2 def _sacarPrincipio2(self): self.cruces -= crucesPorAgregarAdelante(self.fijo2, self.fijo1, self.ady, indice2=self.posiciones1) self.movil2.append(self.fijo2.pop(0)) # swapea fijo1[i] con fijo1[i-1] def _retrasar1(self, i): fijo1 = self.fijo1 a = len(fijo1) - 1 - i cAntes = self.tabla1[(fijo1[a-1],fijo1[a])] # swapeo y actualizo fijo1[a], fijo1[a-1] = fijo1[a-1], fijo1[a] self.posiciones1[fijo1[a]] = a self.posiciones1[fijo1[a-1]] = a-1 # actualizo la cuenta de cruces cDespues = self.tabla1[(fijo1[a-1],fijo1[a])] self.cruces = self.cruces - cAntes + cDespues # analogo para p2 def _retrasar2(self, i): fijo2 = self.fijo2 a = len(fijo2) - 1 - i cAntes = self.tabla2[(fijo2[a-1],fijo2[a])] # swapeo (no hay nada que actualizar) fijo2[a], fijo2[a-1] = fijo2[a-1], fijo2[a] # actualizo la cuenta de cruces cDespues = self.tabla2[(fijo2[a-1],fijo2[a])] self.cruces = self.cruces - cAntes + cDespues ########################################################### # Funcion auxiliar de busqueda del mejor candidato # ########################################################### def _mejor(self): self.llamadas += 1 # valores misc fijo1 = self.fijo1 fijo2 = self.fijo2 movil1 = self.movil1 movil2 = self.movil2 nf1 = len(fijo1) nf2 = len(fijo2) # esto corresponde al caso base, donde chequeo si obtuve una # solución mejor a la previamente máxima, y de ser así la # actualizo con el nuevo valor if movil1 == [] and movil2 == []: self.casosBase += 1 if self.cruces < self.mejorDibujo.contarCruces(): # creo un dibujo (copiando las listas!), y guardo la cantidad # de cruces que ya tengo calculada en el atributo cruces (para # evitar que se recalcule) if self.invertirLados: self.mejorDibujo = Dibujo(self.dibujo.g, fijo2[:], fijo1[:]) else: self.mejorDibujo = Dibujo(self.dibujo.g, fijo1[:], fijo2[:]) self.mejorDibujo.cruces = self.cruces # entro en este caso cuando ya complete una permutacion # de fijo1, y ahora tengo que elegir la mejor permutacion # para la particion 2 elif movil1 == []: self._agregarAtras2() for i in range(-1, nf2): if i != -1: self._retrasar2(i) if self._minimosCrucesRestantes2() + self.cruces < self.mejorDibujo.contarCruces(): self._mejor() else: self.podasHojas += cuantasCombinaciones(fijo1, fijo2, movil1, movil2) self.podasArbol += tamArbol(fijo1, fijo2, movil1, movil2) self._sacarPrincipio2() # entro en este caso cuando lleno la permutacion de fijo1 # (siempre se hace esto antes de verificar la otra particion, # ya que elegimos fijo1 para que tenga menos permutaciones) else: self._agregarAtras1() for i in range(-1, nf1): if i != -1: self._retrasar1(i) if movil1 == []: self._tabular2() if self._minimosCrucesRestantes1() + self.cruces < self.mejorDibujo.contarCruces(): self._mejor() else: self.podasHojas += cuantasCombinaciones(fijo1, fijo2, movil1, movil2) self.podasArbol += tamArbol(fijo1, fijo2, movil1, movil2) self._sacarPrincipio1() def test_resolvedorSwapperTablaConPoda(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=6, n2=6, m=30) d = generarDibujoAleatorio(g, n1=4, n2=5) #r1 = ResolvedorFuerzaBruta(d) #s1 = r1.resolver() r2 = ResolvedorSwapperTablaConPoda(d) s2 = r2.resolver() #assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorSwapperTablaConPoda()
[ [ 1, 0, 0.0109, 0.0027, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0245, 0.0027, 0, 0.66, 0.1667, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0272, 0.0027, 0, 0....
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "from GrafoBipartito import crucesEntre, crucesPorAgregarAdelante, crucesPorAgregarAtras", "from SolucionFuerzaBruta import cuantasCombinaciones, tamArbol", "class ResolvedorSwapperTablaConPoda(ResolvedorConstructivo):\n\n #######...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo from GrafoBipartito import crucesEntre, crucesPorAgregarAdelante, crucesPorAgregarAtras from SolucionFuerzaBruta import cuantasCombinaciones class ResolvedorSwapperTabla(ResolvedorConstructivo): ########################################################### # Funcion global de resolución exacta # ########################################################### def resolver(self): g = self.dibujo.g d = self.dibujo self._inicializar() # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + self.q1, d.l2 + self.q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self._mejor() print "Listo! (cruces: %s)" % self.mejorDibujo.contarCruces() return self.mejorDibujo ########################################################### # Función auxiliar de inicialización # ########################################################### def _inicializar(self): g = self.dibujo.g d = self.dibujo # armo las listas de adyacencia del grafo completo ady = {} for n in g.p1: ady[n] = [] for n in g.p2: ady[n] = [] for a,b in g.ejes: ady[a].append(b) ady[b].append(a) self.ady = ady # busco los nodos que quedan por posicionar self.q1 = [x for x in g.p1 if not x in self.dibujo.l1] self.q2 = [x for x in g.p2 if not x in self.dibujo.l2] # elijo cual de las 2 mitades tiene menos permutaciones # para llenarla primero en el arbol de combinaciones # (esto puede mejorar el rendimiento del algoritmo) combs1 = cuantasCombinaciones(len(d.l1),0,len(self.q1),0) combs2 = cuantasCombinaciones(len(d.l2),0,len(self.q2),0) if combs1 > combs2: invertirLados = True else: invertirLados = False self.invertirLados = invertirLados # estos son los buffers que usa el algoritmo recursivo # (todas las llamadas operan sobre los mismos para evitar copias) if invertirLados: self.fijo1 = d.l2[:] self.fijo2 = d.l1[:] self.movil1 = self.q2 self.movil2 = self.q1 else: self.fijo1 = d.l1[:] self.fijo2 = d.l2[:] self.movil1 = self.q1 self.movil2 = self.q2 # armo las listas de adyacencia de p1 con los de d.l1 # (esto me permite calcular de forma eficiente los cruces # de una cierta permutacion de p1) adyp1 = {} if invertirLados: p1 = g.p2 else: p1 = g.p1 for n in p1: adyp1[n] = [] for a,b in g.ejes: if a in adyp1 and b in self.fijo2: adyp1[a].append(b) elif b in adyp1 and a in self.fijo2: adyp1[b].append(a) self.adyp1 = adyp1 # cache de posiciones para evitar busquedas self.posiciones1 = {} for i in range(len(self.fijo1)): self.posiciones1[self.fijo1[i]] = i self.posiciones2 = {} for i in range(len(self.fijo2)): self.posiciones2[self.fijo2[i]] = i # Cache de cruces para reutilizar calculos # tablaN[(i,j)] es la cantidad de cruces que hay entre # los nodos i,j si son contiguos en el candidato actual de pN self.tabla1 = {} self._tabular2() # cargo los cruces del dibujo original self.cruces = d.contarCruces() def _tabular2(self): # Reinicia la tabla de valores precalculados para p2 cuando cambia p1 # (en la implementacion sobre diccionario equivale a borrarlo) self.tabla2 = {} ########################################################### # Funciones auxiliares para modificacion de candidatos # ########################################################### # mueve movil1[0] a fijo1[n] def _agregarAtras1(self): cab = self.movil1.pop(0) self.fijo1.append(cab) self.posiciones1[cab] = len(self.fijo1) - 1 self.cruces += crucesPorAgregarAtras(self.fijo1, self.dibujo.l2, self.adyp1, indice2=self.posiciones2) # analogo para p1 def _agregarAtras2(self): cab = self.movil2.pop(0) self.fijo2.append(cab) self.cruces += crucesPorAgregarAtras(self.fijo2, self.fijo1, self.ady, indice2=self.posiciones1) # mueve fijo1[0] a movil1[n] def _sacarPrincipio1(self): self.cruces -= crucesPorAgregarAdelante(self.fijo1, self.dibujo.l2, self.adyp1, indice2=self.posiciones2) self.movil1.append(self.fijo1.pop(0)) # FIXME: esta operacion se puede ahorrar con un # offset entero que se resta a todas las posiciones for i in range(len(self.fijo1)): self.posiciones1[self.fijo1[i]] = i # analogo para p2 def _sacarPrincipio2(self): self.cruces -= crucesPorAgregarAdelante(self.fijo2, self.fijo1, self.ady, indice2=self.posiciones1) self.movil2.append(self.fijo2.pop(0)) # swapea fijo1[i] con fijo1[i-1] def _retrasar1(self, i): fijo1 = self.fijo1 a = len(fijo1) - 1 - i # busco en tabla, sino calculo try: cAntes = self.tabla1[(fijo1[a-1],fijo1[a])] except KeyError: cAntes = crucesEntre(fijo1[a-1], fijo1[a], self.dibujo.l2, self.adyp1, indice2=self.posiciones2) self.tabla1[(fijo1[a-1],fijo1[a])] = cAntes # swapeo y actualizo fijo1[a], fijo1[a-1] = fijo1[a-1], fijo1[a] self.posiciones1[fijo1[a]] = a self.posiciones1[fijo1[a-1]] = a-1 # busco en tabla, sino calculo try: cDespues = self.tabla1[(fijo1[a-1],fijo1[a])] except KeyError: cDespues = crucesEntre(fijo1[a-1], fijo1[a], self.dibujo.l2, self.adyp1, indice2=self.posiciones2) self.tabla1[(fijo1[a-1],fijo1[a])] = cDespues # actualizo la cuenta de cruces self.cruces = self.cruces - cAntes + cDespues # analogo para p2 def _retrasar2(self, i): fijo2 = self.fijo2 a = len(fijo2) - 1 - i # busco en tabla, sino calculo try: cAntes = self.tabla2[(fijo2[a-1],fijo2[a])] except KeyError: cAntes = crucesEntre(fijo2[a-1], fijo2[a], self.fijo1, self.ady, indice2=self.posiciones1) self.tabla2[(fijo2[a-1],fijo2[a])] = cAntes # swapeo (no hay nada que actualizar) fijo2[a], fijo2[a-1] = fijo2[a-1], fijo2[a] # busco en tabla, sino calculo try: cDespues = self.tabla2[(fijo2[a-1],fijo2[a])] except KeyError: cDespues = crucesEntre(fijo2[a-1], fijo2[a], self.fijo1, self.ady, indice2=self.posiciones1) self.tabla2[(fijo2[a-1],fijo2[a])] = cDespues # actualizo la cuenta de cruces self.cruces = self.cruces - cAntes + cDespues ########################################################### # Funcion auxiliar de busqueda del mejor candidato # ########################################################### def _mejor(self): # valores misc fijo1 = self.fijo1 fijo2 = self.fijo2 movil1 = self.movil1 movil2 = self.movil2 nf1 = len(fijo1) nf2 = len(fijo2) # esto corresponde al caso base, donde chequeo si obtuve una # solución mejor a la previamente máxima, y de ser así la # actualizo con el nuevo valor if movil1 == [] and movil2 == []: if self.cruces < self.mejorDibujo.contarCruces(): # creo un dibujo (copiando las listas!), y guardo la cantidad # de cruces que ya tengo calculada en el atributo cruces (para # evitar que se recalcule) if self.invertirLados: self.mejorDibujo = Dibujo(self.dibujo.g, fijo2[:], fijo1[:]) else: self.mejorDibujo = Dibujo(self.dibujo.g, fijo1[:], fijo2[:]) self.mejorDibujo.cruces = self.cruces # entro en este caso cuando ya complete una permutacion # de fijo1, y ahora tengo que elegir la mejor permutacion # para la particion 2 elif movil1 == []: self._agregarAtras2() for i in range(-1, nf2): if i != -1: self._retrasar2(i) self._mejor() self._sacarPrincipio2() # entro en este caso cuando lleno la permutacion de fijo1 # (siempre se hace esto antes de verificar la otra particion, # ya que elegimos fijo1 para que tenga menos permutaciones) else: self._agregarAtras1() for i in range(-1, nf1): if i != -1: self._retrasar1(i) if movil1 == []: self._tabular2() self._mejor() self._sacarPrincipio1() def test_resolvedorSwapperTabla(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=7, n2=7, m=15) d = generarDibujoAleatorio(g, n1=4, n2=4) r1 = ResolvedorFuerzaBruta(d) s1 = r1.resolver() r2 = ResolvedorSwapperTabla(d) s2 = r2.resolver() assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorSwapperTabla()
[ [ 1, 0, 0.0129, 0.0032, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.029, 0.0032, 0, 0.66, 0.1667, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0323, 0.0032, 0, 0.6...
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "from GrafoBipartito import crucesEntre, crucesPorAgregarAdelante, crucesPorAgregarAtras", "from SolucionFuerzaBruta import cuantasCombinaciones", "class ResolvedorSwapperTabla(ResolvedorConstructivo):\n\n ########################...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo class ResolvedorBasico(ResolvedorConstructivo): def resolver(self): g = self.dibujo.g d = self.dibujo # busco los nodos que quedan por posicionar q1 = [x for x in g.p1 if not x in self.dibujo.l1] q2 = [x for x in g.p2 if not x in self.dibujo.l2] # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + q1, d.l2 + q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self._mejor(d.l1, d.l2, q1, q2) print "Listo! (cruces: %s)" % self.mejorDibujo.contarCruces() return self.mejorDibujo def _mejor(self, fijo1, fijo2, movil1, movil2): if movil1 == [] and movil2 == []: d = Dibujo(self.dibujo.g, fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self.mejorDibujo = d return # valores misc nf1 = len(fijo1) nf2 = len(fijo2) if movil1 == []: cab = movil2[0] cola = movil2[1:] for i in range(nf2+1): nuevo_fijo2 = fijo2[:] nuevo_fijo2.insert(i, cab) self._mejor(fijo1, nuevo_fijo2, movil1, cola) return else: cab = movil1[0] cola = movil1[1:] for i in range(nf1+1): nuevo_fijo1 = fijo1[:] nuevo_fijo1.insert(i, cab) self._mejor(nuevo_fijo1, fijo2, cola, movil2) return def test_resolvedorBasico(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=7, n2=7, m=15) d = generarDibujoAleatorio(g, n1=5, n2=5) r1 = ResolvedorFuerzaBruta(d) s1 = r1.resolver() r2 = ResolvedorBasico(d) s2 = r2.resolver() assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorBasico()
[ [ 1, 0, 0.0526, 0.0132, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.1184, 0.0132, 0, 0.66, 0.25, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 3, 0, 0.4605, 0.6447, 0, 0.66...
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "class ResolvedorBasico(ResolvedorConstructivo):\n def resolver(self):\n g = self.dibujo.g\n d = self.dibujo\n\n # busco los nodos que quedan por posicionar\n q1 = [x for x in g.p1 if not x in self.dibujo.l...
#!/usr/bin/env python """ svg.py - Construct/display SVG scenes. The following code is a lightweight wrapper around SVG files. The metaphor is to construct a scene, add objects to it, and then write it to a file to display it. This program uses ImageMagick to display the SVG files. ImageMagick also does a remarkable job of converting SVG files into other formats. """ import os display_prog = 'display' # Command to execute to display images. class Scene: def __init__(self,name="svg",height=400,width=400): self.name = name self.items = [] self.height = height self.width = width return def add(self,item): self.items.append(item) def strarray(self): var = ["<?xml version=\"1.0\"?>\n", "<svg height=\"%d\" width=\"%d\" >\n" % (self.height,self.width), " <g style=\"fill-opacity:1.0; stroke:black;\n", " stroke-width:1;\">\n"] for item in self.items: var += item.strarray() var += [" </g>\n</svg>\n"] return var def write_svg(self,filename=None): if filename: self.svgname = filename else: self.svgname = self.name + ".svg" file = open(self.svgname,'w') file.writelines(self.strarray()) file.close() return def display(self,prog=display_prog): os.system("%s %s" % (prog,self.svgname)) return class Line: def __init__(self,start,end): self.start = start #xy tuple self.end = end #xy tuple return def strarray(self): return [" <line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n" %\ (self.start[0],self.start[1],self.end[0],self.end[1])] class Circle: def __init__(self,center,radius,color): self.center = center #xy tuple self.radius = radius #xy tuple self.color = color #rgb tuple in range(0,256) return def strarray(self): return [" <circle cx=\"%d\" cy=\"%d\" r=\"%d\"\n" %\ (self.center[0],self.center[1],self.radius), " style=\"fill:%s;\" />\n" % colorstr(self.color)] class Rectangle: def __init__(self,origin,height,width,color): self.origin = origin self.height = height self.width = width self.color = color return def strarray(self): return [" <rect x=\"%d\" y=\"%d\" height=\"%d\"\n" %\ (self.origin[0],self.origin[1],self.height), " width=\"%d\" style=\"fill:%s;\" />\n" %\ (self.width,colorstr(self.color))] class Text: def __init__(self,origin,text,size=24): self.origin = origin self.text = text self.size = size return def strarray(self): return [" <text x=\"%d\" y=\"%d\" font-size=\"%d\">\n" %\ (self.origin[0],self.origin[1],self.size), " %s\n" % self.text, " </text>\n"] def colorstr(rgb): return "#%x%x%x" % (rgb[0]/16,rgb[1]/16,rgb[2]/16) def test(): scene = Scene('test') scene.add(Rectangle((100,100),200,200,(0,255,255))) scene.add(Line((200,200),(200,300))) scene.add(Line((200,200),(300,200))) scene.add(Line((200,200),(100,200))) scene.add(Line((200,200),(200,100))) scene.add(Circle((200,200),30,(0,0,255))) scene.add(Circle((200,300),30,(0,255,0))) scene.add(Circle((300,200),30,(255,0,0))) scene.add(Circle((100,200),30,(255,255,0))) scene.add(Circle((200,100),30,(255,0,255))) scene.add(Text((50,50),"Testing SVG")) scene.write_svg() scene.display() return if __name__ == '__main__': test()
[ [ 8, 0, 0.0542, 0.0833, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1083, 0.0083, 0, 0.66, 0.1, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 14, 0, 0.1167, 0.0083, 0, 0.66, ...
[ "\"\"\"\nsvg.py - Construct/display SVG scenes.\n\nThe following code is a lightweight wrapper around SVG files. The metaphor\nis to construct a scene, add objects to it, and then write it to a file\nto display it.\n\nThis program uses ImageMagick to display the SVG files. ImageMagick also", "import os", "displ...
from GrafoBipartito import * from GeneradorGrafos import * from Dibujador import * from SolucionBasicaPoda import * from HeuristicaInsercionEjes import * import random # grafo: todos los nodos y ejes, p1 p2 estaRel(v,u) #dibujo: l1, l2 los nodos que no se pueden mover class HeuristicaDeLaMediana (ResolvedorConstructivo): #no es la version del paper pero para la mediana, aca parto de los q ya estan, calculo la mediana para # cada uno q tengo q agregar def resolver(self,alfa=1): sinMarcar1 = [x for x in self.dibujo.g.p1 if x not in self.dibujo.l1] sinMarcar2 = [x for x in self.dibujo.g.p2 if x not in self.dibujo.l2] #nodos marcados (posicion relativa fija) marcados1 = self.dibujo.l1 marcados2 = self.dibujo.l2 marcadosl1=marcados1 marcadosl2=marcados2 print marcados1 print marcados2 #nodos totales v1 = sinMarcar1 v2 = sinMarcar2 #inicializa arreglo de medianas para los nodos de v1 p1 = marcados1[:] p2 = marcados2[:] #ejesDe: listas de adyacencias ejesDe = {} losEjesEntreLosPuestos = {} medianas={} #lo inicializo for each in v1 + v2+marcados1+marcados2: losEjesEntreLosPuestos[each] = [] for each in v1+v2+marcados1+marcados2: ejesDe[each] = [] medianas[each]=0 #la completo for each in self.dibujo.g.ejes: ejesDe[each[0]].append(each[1]) ejesDe[each[1]].append(each[0]) if each[1] in p2: losEjesEntreLosPuestos[each[0]].append(each[1]) if each[0] in p1: losEjesEntreLosPuestos[each[1]].append(each[0]) while (v1 != [] or v2 != []): #toma uno con grado >= alfa*max (lo saca ademas) (x,donde)=self.tomarUnoDeMayorGrado(v1,v2,losEjesEntreLosPuestos,alfa=1) if donde == 1: #va en p1 med=self.calcularMediana(x,p2,losEjesEntreLosPuestos) medianas[x] = med if med > len(p1): med = len(p1) for each in ejesDe[x]: losEjesEntreLosPuestos[each].append(x) medMenos1 = med - 1 medMas1 = med + 1 p1.insert(med,x) crucesInicial = contadorDeCruces(p1,p2,losEjesEntreLosPuestos) crucesMejor = crucesInicial indiceMejor = med if medMenos1 >= 0: crucesPreSwap = crucesEntre(p1[med-1],p1[med],p2,losEjesEntreLosPuestos) crucesPostSwap = crucesEntre(p1[med],p1[med-1],p2,losEjesEntreLosPuestos) if crucesPostSwap > crucesPreSwap: indiceMejor = med - 1 crucesMejor = crucesInicial - crucesPreSwap + crucesPostSwap if medMas1 < len(p1): crucesPreSwap = crucesEntre(p1[med],p1[med+1],p2,losEjesEntreLosPuestos) crucesPostSwap = crucesEntre(p1[med+1],p1[med],p2,losEjesEntreLosPuestos) if crucesMejor > (crucesInicial - crucesPreSwap + crucesPostSwap): indiceMejor = med + 1 if indiceMejor == medMenos1: aux = p1[med] p1[med] = p1[med - 1] p1[med - 1] = aux if indiceMejor == medMas1: aux = p1[med] p1[med] = p1[med + 1] p1[med + 1] = aux else: med=self.calcularMediana(x,p1,losEjesEntreLosPuestos) medianas[x] = med if med > len(p2): med = len(p2) for each in ejesDe[x]: losEjesEntreLosPuestos[each].append(x) medMenos1 = med - 1 medMas1 = med + 1 p2.insert(med,x) crucesInicial = contadorDeCruces(p2,p1,losEjesEntreLosPuestos) crucesMejor = crucesInicial indiceMejor = med if medMenos1 >= 0: crucesPreSwap = crucesEntre(p2[med-1],p2[med],p1,losEjesEntreLosPuestos) crucesPostSwap = crucesEntre(p2[med],p2[med-1],p1,losEjesEntreLosPuestos) if crucesPostSwap > crucesPreSwap: indiceMejor = med - 1 crucesMejor = crucesInicial - crucesPreSwap + crucesPostSwap if medMas1 < len(p2): crucesPreSwap = crucesEntre(p2[med],p2[med+1],p1,losEjesEntreLosPuestos) crucesPostSwap = crucesEntre(p2[med+1],p2[med],p1,losEjesEntreLosPuestos) if crucesMejor > (crucesInicial - crucesPreSwap + crucesPostSwap): indiceMejor = med + 1 if indiceMejor == medMenos1: aux = p2[med] p2[med] = p2[med - 1] p2[med - 1] = aux if indiceMejor == medMas1: aux = p2[med] p2[med] = p2[med + 1] p2[med + 1] = aux #tratamos de arreglar los corrimientos por empate, hacemos para eso unos swaps p1 = self.corregirDesvios(p1,p2,marcadosl1,ejesDe) p2 = self.corregirDesvios(p2,p1,marcadosl2,ejesDe) return Dibujo(self.dibujo.g,p1,p2) def corregirDesvios(self,v1Aux,v2,marcados,ejesDe): for fede in range(2): #primero hacemos swap desde arriba hacia abajo for i in range(len(v1Aux)-1): if v1Aux[i] not in marcados or v1Aux[i+1] not in marcados: if contadorDeCruces([v1Aux[i],v1Aux[i+1]],v2,ejesDe) > contadorDeCruces([v1Aux[i+1],v1Aux[i]],v2,ejesDe): aux = v1Aux[i] v1Aux[i] = v1Aux[i+1] v1Aux[i+1] = aux for i in range(1,len(v1Aux)): if v1Aux[len(v1Aux)-i] not in marcados or v1Aux[len(v1Aux)-i -1] not in marcados: if contadorDeCruces([ v1Aux[len(v1Aux)-i -1],v1Aux[len(v1Aux)-i]],v2,ejesDe) > contadorDeCruces([v1Aux[len(v1Aux)-i], v1Aux[len(v1Aux)-i -1]],v2,ejesDe): aux = v1Aux[len(v1Aux)-i] v1Aux[len(v1Aux)-i] = v1Aux[len(v1Aux)-i -1] v1Aux[len(v1Aux)-i -1] = aux return v1Aux def tomarUnoDeMayorGrado(self,v1,v2,losEjesDe,alfa=1): maxGrado = 0 for each in v1: if len(losEjesDe[each]) > maxGrado: maxGrado=len(losEjesDe[each]) for each in v2: if len(losEjesDe[each]) > maxGrado: maxGrado=len(losEjesDe[each]) assert alfa <= 1 gradoAlfa = maxGrado*alfa candidatos = [] for each in v1: if len(losEjesDe[each]) >= gradoAlfa: candidatos.append(each) for each in v2: if len(losEjesDe[each]) >= gradoAlfa: candidatos.append(each) winner=random.sample(candidatos,1) ganador = winner[0] if ganador in v1: v1.remove(ganador) return (ganador,1) else: v2.remove(ganador) return (ganador,2) def calcularMediana(self,x,pi,losEjesDe): indice = {} for i in range(len(pi)): indice[pi[i]] = i med = [] for each in losEjesDe[x]: med.append(indice[each]) med.sort() if med == []: return 0 if len(med) % 2 == 0: return int(round(float((med[len(med)/2] + med[(len(med)-1)/2]))/2)) else: return med[len(med)/2] if __name__ == '__main__': g = generarGrafoBipartitoAleatorio(6,6,10) print 'nodos =', g.p1 print 'nodos =', g.p2 print 'ejes =', g.ejes dib = generarDibujoAleatorio(g,2,2) resultado = HeuristicaDeLaMediana(dib).resolver() print "ahora dio", resultado.contarCruces() DibujadorGrafoBipartito(resultado).grabar('dibujo.svg')
[ [ 1, 0, 0.0051, 0.0051, 0, 0.66, 0, 16, 0, 1, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0101, 0.0051, 0, 0.66, 0.1429, 590, 0, 1, 0, 0, 590, 0, 0 ], [ 1, 0, 0.0152, 0.0051, 0, 0....
[ "from GrafoBipartito import *", "from GeneradorGrafos import *", "from Dibujador import *", "from SolucionBasicaPoda import *", "from HeuristicaInsercionEjes import *", "import random", "class HeuristicaDeLaMediana (ResolvedorConstructivo):\n #no es la version del paper pero para la mediana, aca part...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo from SolucionFuerzaBruta import cuantasCombinaciones class ResolvedorBasicoConPoda(ResolvedorConstructivo): def resolver(self): g = self.dibujo.g d = self.dibujo # busco los nodos que quedan por posicionar q1 = [x for x in g.p1 if not x in self.dibujo.l1] q2 = [x for x in g.p2 if not x in self.dibujo.l2] # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + q1, d.l2 + q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self.podas = 0 self._mejor(d.l1, d.l2, q1, q2) combinaciones = cuantasCombinaciones(d.l1, d.l2, q1, q2) porcent_podas = self.podas * 100.0 / combinaciones print "Listo! (cruces: %s, podas: %.1f%%)" % \ (self.mejorDibujo.contarCruces(), porcent_podas) return self.mejorDibujo def _mejor(self, fijo1, fijo2, movil1, movil2, cruces=None): if movil1 == [] and movil2 == []: if cruces < self.mejorDibujo.contarCruces(): d = Dibujo(self.dibujo.g, fijo1, fijo2) self.mejorDibujo = d return # valores misc nf1 = len(fijo1) nf2 = len(fijo2) if movil1 == []: cab = movil2[0] cola = movil2[1:] for i in range(nf2+1): nuevo_fijo2 = fijo2[:] nuevo_fijo2.insert(i, cab) d = Dibujo(self.dibujo.g, fijo1, nuevo_fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self._mejor(fijo1, nuevo_fijo2, movil1, cola, cruces=d.contarCruces()) else: self.podas += cuantasCombinaciones(fijo1, nuevo_fijo2, movil1, cola) - 1 return else: cab = movil1[0] cola = movil1[1:] for i in range(nf1+1): nuevo_fijo1 = fijo1[:] nuevo_fijo1.insert(i, cab) d = Dibujo(self.dibujo.g, nuevo_fijo1, fijo2) if d.contarCruces() < self.mejorDibujo.contarCruces(): self._mejor(nuevo_fijo1, fijo2, cola, movil2, cruces=d.contarCruces()) else: self.podas += cuantasCombinaciones(nuevo_fijo1, fijo2, cola, movil2) - 1 return def test_resolvedorBasicoConPoda(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=7, n2=7, m=15) d = generarDibujoAleatorio(g, n1=5, n2=5) r1 = ResolvedorFuerzaBruta(d) s1 = r1.resolver() r2 = ResolvedorBasicoConPoda(d) s2 = r2.resolver() assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorBasicoConPoda()
[ [ 1, 0, 0.0444, 0.0111, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.1, 0.0111, 0, 0.66, 0.2, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.1111, 0.0111, 0, 0.66, ...
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "from SolucionFuerzaBruta import cuantasCombinaciones", "class ResolvedorBasicoConPoda(ResolvedorConstructivo):\n def resolver(self):\n g = self.dibujo.g\n d = self.dibujo\n\n # busco los nodos que quedan por po...
from BusquedaLocalIntercambioGreedy import * from BusquedaLocalReInsercion import * from HeuristicaInsercionEjes import * class BusquedaLocalMix(BusquedaLocal): def hallarMinimoLocal(self,dibujo,marcados1,marcados2,losEjesDe): crucesInicial = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) cambio = True while cambio: cambio = False self.mejorar(dibujo,marcados1,marcados2,losEjesDe) crucesActual = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) if crucesActual < crucesInicial: crucesInicial = crucesActual cambio = True def mejorar(self,dibujo,marcados1,marcados2,losEjesDe): bli = BusquedaLocalIntercambioGreedy() blr = BusquedaLocalReInsercion() blr.mejorar(dibujo,marcados1,marcados2,losEjesDe) bli.mejorar(dibujo,marcados1,marcados2,losEjesDe) if __name__ == '__main__': g = generarGrafoBipartitoAleatorio(12, 12, 60) d = generarDibujoAleatorio(g,3, 3) marcados1 = d.l1[:] print marcados1 marcados2 = d.l2[:] print marcados2 losEjesDe = {} for each in g.p1 : losEjesDe[each] = [] for each in g.p2 : losEjesDe[each] = [] for each in g.ejes: losEjesDe[each[0]].append(each[1]) losEjesDe[each[1]].append(each[0]) res=HeuristicaInsercionEjes(d).resolver() blIG=BusquedaLocalMix() print "antes de la busqueda",res.contarCruces() blIG.hallarMinimoLocal(res,marcados1,marcados2,losEjesDe) print "despues de la misma", contadorDeCruces(res.l1,res.l2,losEjesDe) DibujadorGrafoBipartito(res,marcados1=marcados1,marcados2=marcados2).grabar('localMediana.svg')
[ [ 1, 0, 0.0222, 0.0222, 0, 0.66, 0, 170, 0, 1, 0, 0, 170, 0, 0 ], [ 1, 0, 0.0444, 0.0222, 0, 0.66, 0.25, 934, 0, 1, 0, 0, 934, 0, 0 ], [ 1, 0, 0.0667, 0.0222, 0, 0....
[ "from BusquedaLocalIntercambioGreedy import *", "from BusquedaLocalReInsercion import *", "from HeuristicaInsercionEjes import *", "class BusquedaLocalMix(BusquedaLocal):\n def hallarMinimoLocal(self,dibujo,marcados1,marcados2,losEjesDe):\n crucesInicial = contadorDeCruces(dibujo.l1,dibujo.l2,losEje...
#!/usr/bin/python # -*- coding: utf-8 -*- from GrafoBipartito import Dibujo, ResolvedorConstructivo import sys #import psyco #psyco.full() class ResolvedorFuerzaBruta(ResolvedorConstructivo): def resolver(self): # busco los nodos que quedan por posicionar q1 = [x for x in self.dibujo.g.p1 if not x in self.dibujo.l1] q2 = [x for x in self.dibujo.g.p2 if not x in self.dibujo.l2] # genero todos los posibles dibujos print "Generando soluciones posibles... ", sys.stdout.flush() combs = combinaciones(self.dibujo.l1, self.dibujo.l2, q1, q2) print "Listo! (total: %s)" % len(combs) # elijo el mejor print "Eligiendo solución óptima... ", sys.stdout.flush() l1, l2 = combs.pop() mejor = Dibujo(self.dibujo.g, l1, l2) cruces = mejor.contarCruces() for c in combs: d = Dibujo(self.dibujo.g, c[0], c[1]) if d.contarCruces() < cruces: mejor = d cruces = d.contarCruces() print "Listo! (cruces: %s)" % cruces return mejor def combinaciones(fijo1, fijo2, movil1, movil2): '''Construye todos los dibujos incrementales sobre fijo1, fijo2''' if movil1 == [] and movil2 == []: return [(fijo1, fijo2)] # algunos valores misc nf1 = len(fijo1) nf2 = len(fijo2) # posiciono los moviles 2 if movil1 == []: cab = movil2[0] cola = movil2[1:] ops = [] for i in range(nf2+1): nuevo_fijo2 = fijo2[:] nuevo_fijo2.insert(i, cab) ops += combinaciones(fijo1, nuevo_fijo2, movil1, cola) return ops # posiciono los moviles 1 else: cab = movil1[0] cola = movil1[1:] ops = [] for i in range(nf1+1): nuevo_fijo1 = fijo1[:] nuevo_fijo1.insert(i, cab) ops += combinaciones(nuevo_fijo1, fijo2, cola, movil2) return ops def cuantasCombinaciones(fijo1, fijo2, movil1, movil2): '''Calcula el cardinal del universo de soluciones posibles de esta instancia''' if isinstance(fijo1, list) and \ isinstance(fijo2, list) and \ isinstance(movil1, list) and \ isinstance(movil2, list): f1, f2, m1, m2 = map(len, [fijo1, fijo2, movil1, movil2]) else: f1, f2, m1, m2 = fijo1, fijo2, movil1, movil2 c = 1 for i in range(m1): c *= f1 + i + 1 for i in range(m2): c *= f2 + i + 1 return c def tamTree(fijo1, fijo2, movil1, movil2): if isinstance(fijo1, list) and \ isinstance(fijo2, list) and \ isinstance(movil1, list) and \ isinstance(movil2, list): f1, f2, m1, m2 = map(len, [fijo1, fijo2, movil1, movil2]) else: f1, f2, m1, m2 = fijo1, fijo2, movil1, movil2 if m1 == 0 and m2 == 0: return 1 elif m2 != 0: return (f2+1)*tamTree(f1, f2+1, m1, m2-1) + 1 elif m1 != 0: return (f1+1)*tamTree(f1+1, f2, m1-1, m2) + 1 def tamArbol(fijo1,fijo2,movil1,movil2): if isinstance(fijo1, list) and \ isinstance(fijo2, list) and \ isinstance(movil1, list) and \ isinstance(movil2, list): f1, f2, m1, m2 = map(len, [fijo1, fijo2, movil1, movil2]) else: f1, f2, m1, m2 = fijo1, fijo2, movil1, movil2 arbol1 = tamTree(f1,0,m1,0) arbol2 = tamTree(0,f2,0,m2) return arbol1 + cuantasCombinaciones(f1, 0, m1, 0)*(arbol2 -1) def test_resolvedorFuerzaBruta(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio g = generarGrafoBipartitoAleatorio(n1=8, n2=8, m=15) d = generarDibujoAleatorio(g,n1=5, n2=5) r = ResolvedorFuerzaBruta(d) s = r.resolver() if __name__ == '__main__': test_resolvedorFuerzaBruta()
[ [ 1, 0, 0.0301, 0.0075, 0, 0.66, 0, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0451, 0.0075, 0, 0.66, 0.125, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 3, 0, 0.188, 0.218, 0, 0.66,...
[ "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "import sys", "class ResolvedorFuerzaBruta(ResolvedorConstructivo):\n def resolver(self):\n # busco los nodos que quedan por posicionar\n q1 = [x for x in self.dibujo.g.p1 if not x in self.dibujo.l1]\n q2 = [x for x in self.dib...
import random from HeuristicaDeLaMediana import * import psyco psyco.full() class BusquedaLocalMediana(BusquedaLocal): def calcularMediana(self,each,indicesi,losEjesDe): med = [] for each1 in losEjesDe[each]: med.append(indicesi[each1]) med.sort() if med == []: return 0 if len(med) % 2: return int(round(float((med[len(med)/2] + med[(len(med)-1)/2]))/2)) else: return med[len(med)/2] def corregirDesvios(self,v1Aux,v2,marcados,ejesDe): for fede in range(2): #primero hacemos swap desde arriba hacia abajo for i in range(len(v1Aux)-1): if v1Aux[i] not in marcados or v1Aux[i+1] not in marcados: if contadorDeCruces([v1Aux[i],v1Aux[i+1]],v2,ejesDe) > contadorDeCruces([v1Aux[i+1],v1Aux[i]],v2,ejesDe): aux = v1Aux[i] v1Aux[i] = v1Aux[i+1] v1Aux[i+1] = aux for i in range(1,len(v1Aux)): if v1Aux[len(v1Aux)-i] not in marcados or v1Aux[len(v1Aux)-i -1] not in marcados: if contadorDeCruces([ v1Aux[len(v1Aux)-i -1],v1Aux[len(v1Aux)-i]],v2,ejesDe) > contadorDeCruces([v1Aux[len(v1Aux)-i], v1Aux[len(v1Aux)-i -1]],v2,ejesDe): aux = v1Aux[len(v1Aux)-i] v1Aux[len(v1Aux)-i] = v1Aux[len(v1Aux)-i -1] v1Aux[len(v1Aux)-i -1] = aux return v1Aux def puedoInsertar(self,each,pi,marcadosi,med): if each not in marcadosi: return True else: k = marcadosi.index(each) anterior = -1 siguiente = len(pi) if k != 0: anterior = pi.index(marcadosi[k-1]) if k != len(marcadosi)-1: siguiente = pi.index(marcadosi[k+1]) return anterior < med and med < siguiente def hallarMinimoLocal(self,dibujo,marcados1,marcados2,losEjesDe): crucesInicial = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) cambio = True while cambio: cambio = False self.mejorar(dibujo,marcados1,marcados2,losEjesDe) crucesActual = contadorDeCruces(dibujo.l1,dibujo.l2,losEjesDe) if crucesActual < crucesInicial: crucesInicial = crucesActual cambio = True def mejorar(self,dibujo,marcados1,marcados2,losEjesDe): p1 = dibujo.l1 p2 = dibujo.l2 indices2 = {} for i in range(len(p2)): indices2[p2[i]] = i p1Copia = p1[:] crucesActual = contadorDeCruces(p1,p2,losEjesDe,None,indices2) for each in p1Copia: med = self.calcularMediana(each,indices2,losEjesDe) if med >= len(p1): med = len(p1)-1 puedo = False if self.puedoInsertar(each,p1,marcados1,med): puedo = True elif med < len(p1)-1 and self.puedoInsertar(each,p1,marcados1,med+1): med = med + 1 puedo = True elif med > 0 and self.puedoInsertar(each,p1,marcados1,med-1): med = med -1 puedo = True if puedo: indiceEach = p1.index(each) p1.remove(each) p1.insert(med,each) nuevosCruces = contadorDeCruces(p1,p2,losEjesDe,None,indices2) if nuevosCruces > crucesActual: p1.remove(each) p1.insert(indiceEach,each) else: crucesActual = nuevosCruces indices1 = {} for i in range(len(p1)): indices1[p1[i]] = i p2Copia = p2[:] for each in p2Copia: med = self.calcularMediana(each,indices1,losEjesDe) if med >= len(p2): med = len(p2)-1 puedo = False if self.puedoInsertar(each,p2,marcados2,med): puedo = True elif med < len(p2)-1 and self.puedoInsertar(each,p2,marcados2,med+1): med = med + 1 puedo = True elif med > 0 and self.puedoInsertar(each,p2,marcados2,med-1): med = med -1 puedo = True if puedo: indiceEach = p2.index(each) p2.remove(each) p2.insert(med,each) nuevosCruces = contadorDeCruces(p2,p1,losEjesDe,None,indices1) if nuevosCruces > crucesActual: p2.remove(each) p2.insert(indiceEach,each) else: crucesActual = nuevosCruces crucesActual = contadorDeCruces(p1,p2,losEjesDe,None,indices2) cambio = True while cambio: cambio = False p1 =self.corregirDesvios(p1,p2,marcados1,losEjesDe) p2 =self.corregirDesvios(p2,p1,marcados2,losEjesDe) crucesMejor = contadorDeCruces(p1,p2,losEjesDe,None,indices2) if crucesMejor < crucesActual: crucesActual = crucesMejor cambio = True if __name__ == '__main__': g = generarGrafoBipartitoAleatorio(50, 50, 108) d = generarDibujoAleatorio(g,13, 21) marcados1 = d.l1[:] print marcados1 marcados2 = d.l2[:] print marcados2 losEjesDe = {} for each in g.p1 : losEjesDe[each] = [] for each in g.p2 : losEjesDe[each] = [] for each in g.ejes: losEjesDe[each[0]].append(each[1]) losEjesDe[each[1]].append(each[0]) res=HeuristicaDeLaMediana(d).resolver() blIG=BusquedaLocalMediana() print "antes de la busqueda",res.contarCruces() blIG.hallarMinimoLocal(res,marcados1,marcados2,losEjesDe) print "despues de la misma", contadorDeCruces(res.l1,res.l2,losEjesDe) DibujadorGrafoBipartito(res,marcados1=marcados1,marcados2=marcados2).grabar('localMediana.svg')
[ [ 1, 0, 0.0065, 0.0065, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0129, 0.0065, 0, 0.66, 0.2, 580, 0, 1, 0, 0, 580, 0, 0 ], [ 1, 0, 0.0194, 0.0065, 0, 0.6...
[ "import random", "from HeuristicaDeLaMediana import *", "import psyco", "psyco.full()", "class BusquedaLocalMediana(BusquedaLocal):\n def calcularMediana(self,each,indicesi,losEjesDe):\n med = []\n for each1 in losEjesDe[each]:\n med.append(indicesi[each1])\n med.sort()\n ...
#!/usr/bin/python # -*- coding: utf-8 -*- from sets import Set import svg from GrafoBipartito import GrafoBipartito, Dibujo class DibujadorGrafoBipartito: def __init__(self, dibujo, nombre="GrafoBipartito", height=800,marcados1=None,marcados2=None): self.dibujo = dibujo # calculo las dimensiones self.alto_nodos = max(len(dibujo.l1), len(dibujo.l2)) self.alto = height # radio del nodo self.rn = int(self.alto * 0.90 * 0.5 / self.alto_nodos) self.ancho = int(height/1.3) self.scene = svg.Scene(nombre, height=height, width=self.ancho) if marcados1 == None: self._dibujar() else: self._dibujarConMarcados(marcados1,marcados2) def _dibujar(self): l1 = self.dibujo.l1 l2 = self.dibujo.l2 c1 = 0.2 * self.ancho c2 = 0.8 * self.ancho m_sup = 0.13 * self.alto colorCirculo = (200,255,200) # filtro los ejes que me interesan ejes = [] for a,b in self.dibujo.g.ejes: # if ((a in l1 and b in l2) or (b in l1 and a in l2)): # if a in l2: # a,b = b,a ejes.append((a,b)) # dibujo los ejes for a,b in ejes: self.scene.add(svg.Line((c1, m_sup + l1.index(a) * 2 * self.rn), (c2, m_sup + l2.index(b) * 2 * self.rn))) # dibujo los nodos for n in l1: centro = (c1, m_sup + l1.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculo)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) for n in l2: centro = (c2, m_sup + l2.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculo)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) def _dibujarConMarcados(self,marcados1,marcados2): l1 = self.dibujo.l1 l2 = self.dibujo.l2 c1 = 0.2 * self.ancho c2 = 0.8 * self.ancho m_sup = 0.13 * self.alto colorCirculo = (200,255,200) colorCirculoMarcado = (255,200,200) # filtro los ejes que me interesan ejes = [] for a,b in self.dibujo.g.ejes: if ((a in l1 and b in l2) or (b in l1 and a in l2)): if a in l2: a,b = b,a ejes.append((a,b)) # dibujo los ejes for a,b in ejes: self.scene.add(svg.Line((c1, m_sup + l1.index(a) * 2 * self.rn), (c2, m_sup + l2.index(b) * 2 * self.rn))) # dibujo los nodos for n in l1: if n in marcados1: centro = (c1, m_sup + l1.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculoMarcado)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) else: centro = (c1, m_sup + l1.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculo)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) for n in l2: if n in marcados2: centro = (c2, m_sup + l2.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculoMarcado)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) else: centro = (c2, m_sup + l2.index(n) * 2 * self.rn) self.scene.add(svg.Circle(centro,self.rn / 2,colorCirculo)) centro = (centro[0] - self.rn / 7, centro[1] + self.rn / 6) self.scene.add(svg.Text(centro, n)) def grabar(self, filename=None): self.scene.write_svg(filename=filename) def grabarYMostrar(self): self.scene.write_svg() self.scene.display(prog="display") def test_Dibujador(): g = GrafoBipartito(Set([1,2,3,4]), Set([5,6,7,8,9]), Set([(4,6),(4,5),(3,5),(3,7),(2,6),(1,7),(3,8),(2,9),(4,8)])) d = Dibujo(g,[1,2,3,4],[5,6,7,8,9]) dib = DibujadorGrafoBipartito(d) dib.grabarYMostrar() dib.grabar('test.svg') if __name__ == '__main__': test_Dibujador()
[ [ 1, 0, 0.0312, 0.0078, 0, 0.66, 0, 842, 0, 1, 0, 0, 842, 0, 0 ], [ 1, 0, 0.0469, 0.0078, 0, 0.66, 0.2, 873, 0, 1, 0, 0, 873, 0, 0 ], [ 1, 0, 0.0547, 0.0078, 0, 0.6...
[ "from sets import Set", "import svg", "from GrafoBipartito import GrafoBipartito, Dibujo", "class DibujadorGrafoBipartito:\n def __init__(self, dibujo, nombre=\"GrafoBipartito\", height=800,marcados1=None,marcados2=None):\n self.dibujo = dibujo\n\n # calculo las dimensiones\n self.alto...
# Heuristica de agregar nodos de a uno y a acomodarlos from GrafoBipartito import ResolvedorConstructivo, Dibujo, GrafoBipartito from Dibujador import DibujadorGrafoBipartito from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from sets import * class HeuristicaInsercionNodosMenorGrado(ResolvedorConstructivo): def resolver(self, alfa=1): d = self.dibujo g = self.dibujo.g res1 = d.l1[:] res2 = d.l2[:] movilesEnV1 = [x for x in g.p1 if not x in d.l1] # los moviles de V1 movilesEnV2 = [x for x in g.p2 if not x in d.l2] # los moviles de V2 dibujo = Dibujo(g,res1[:],res2[:]) while(movilesEnV1 != [] or movilesEnV2 != []): if movilesEnV1 != [] : v = movilesEnV1.pop(self._indiceMenorGrado(movilesEnV1, movilesEnV2, dibujo, alfa)) # print 'v en v1', v dibujo = self._insertarNodo(v, res1, True, dibujo) res1 = dibujo.l1[:] if movilesEnV2 != [] : v = movilesEnV2.pop(self._indiceMenorGrado(movilesEnV2, movilesEnV1, dibujo, alfa)) # print 'v en v2', v dibujo = self._insertarNodo(v, res2, False, dibujo) res2 = dibujo.l2[:] # ahora intento mejorar el resultado con un sort loco por cruces entre pares de nodos for i in range(len(res1)-1): ejesDe = {} v1 = res1[i] v2 = res1[i+1] if v1 not in d.l1 or v2 not in d.l1: # verifico que v1 y v2 se puedan mover ejesDe[v1] = [x[1] for x in dibujo.g.ejes if x[0] == v1] ejesDe[v2] = [x[1] for x in dibujo.g.ejes if x[0] == v2] if self._crucesEntre(v1, v2, res1, res2, ejesDe) > self._crucesEntre(v2, v1, res1, res2, ejesDe): res1[i] = v2 res1[i+1] = v1 dibujo = Dibujo(g, res1, res2) return dibujo def _indiceMenorGrado(self, movilesEnVi, movilesEnVj, dibujo, alfa): indiceMenor = 0 ejesMenor = [x for x in dibujo.g.ejes if (x[0] == movilesEnVi[0] and x[1] not in movilesEnVj) or (x[1] == movilesEnVi[0] and x[0] not in movilesEnVj)] # print 'ejes de nodo', movilesEnVi[indiceMenor], '=', ejesMenor for i in range(len(movilesEnVi)): ejesIesimo = [x for x in dibujo.g.ejes if (x[0] == movilesEnVi[i] and x[1] not in movilesEnVj) or (x[1] == movilesEnVi[i] and x[0] not in movilesEnVj)] # print 'ejes de nodo', movilesEnVi[i], '=', ejesIesimo if len(ejesIesimo) < len(ejesMenor)*alfa: indiceMenor = i ejesMenor = ejesIesimo return indiceMenor def _insertarNodo(self, v, Vi, agregoEnV1, dibujo): g = self.dibujo.g aux = Vi[:] aux.insert(0, v) if agregoEnV1: mejorDibujo = Dibujo(g, aux[:], dibujo.l2) else: mejorDibujo = Dibujo(g, dibujo.l1, aux[:]) crucesMejorDibujo = mejorDibujo.contarCruces() for i in range(len(Vi)): aux.remove(v) aux.insert(i + 1, v) if(agregoEnV1): dibujoCandidato = Dibujo(g, aux[:], dibujo.l2) else: dibujoCandidato = Dibujo(g, dibujo.l1, aux[:]) crucesCandidato = dibujoCandidato.contarCruces() #print 'crucesCandidato', crucesCandidato #print 'crucesMejorDibujo', crucesMejorDibujo if crucesCandidato < crucesMejorDibujo : mejorDibujo = dibujoCandidato crucesMejorDibujo = crucesCandidato #print 'mejorDibujo', mejorDibujo #print 'cruces posta', mejorDibujo._contarCruces() return mejorDibujo def _crucesEntre(self,x,y,p1,p2,losEjesDe): indiceX = p1.index(x) indiceY = p1.index(y) acum = 0 for each in losEjesDe[x]: indiceEach = p2.index(each) for each2 in losEjesDe[y]: if indiceEach > p2.index(each2): acum += 1 return acum if __name__ == '__main__': p1 = Set([1,2,3,4]) p2 = Set([5,6,7,8]) l1 = [1,4] l2 = [5,8] print 'testeo menor' ejes = Set([(1,7), (2,5), (2,8), (3,6), (3,7), (3,8), (4,8)]) dib = Dibujo(GrafoBipartito(p1,p2,ejes), l1, l2) # DibujadorGrafoBipartito(dib).grabar('dibujo.svg') resultado = HeuristicaInsercionNodosMenorGrado(dib).resolver(1) DibujadorGrafoBipartito(resultado).grabar('resultado.svg')
[ [ 1, 0, 0.018, 0.009, 0, 0.66, 0, 16, 0, 3, 0, 0, 16, 0, 0 ], [ 1, 0, 0.027, 0.009, 0, 0.66, 0.2, 851, 0, 1, 0, 0, 851, 0, 0 ], [ 1, 0, 0.036, 0.009, 0, 0.66, 0...
[ "from GrafoBipartito import ResolvedorConstructivo, Dibujo, GrafoBipartito", "from Dibujador import DibujadorGrafoBipartito", "from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio", "from sets import *", "class HeuristicaInsercionNodosMenorGrado(ResolvedorConstructivo):\n de...
from GrafoBipartito import * from GeneradorGrafos import * from Dibujador import * # grafo: todos los nodos y ejes, p1 p2 estaRel(v,u) #dibujo: l1, l2 los nodos que no se pueden mover class HeuristicaRemocion (ResolvedorConstructivo): def contarCrucesAcumTree(p1,p2,ejes): if len(p1) < len(p2): return contarCrucesAcumTree(p2,p1,[(y,x) for (x,y) in ejes]) lista=[] indice1={} indice2={} for i in range(len(p1)): indice1[p1[i]]=i for i in range(len(p2)): indice2[p2[i]]=i for each in ejes: lista.append((indice1[each[0]],indice2[each[1]])) b1=[[] for each in range(len(p2))] b2=[[] for each in range(len(p1))] for each in lista: b1[each[1]].append(each) lista2=[] for i in range(len(b1)): lista2.extend(b1[i]) for each in lista2: b2[each[0]].append(each) lista2=[] for i in range(len(b2)): lista2.extend(b2[i]) #print lista2 sur=[] for each in lista2: sur.append(each[1]) primerIndice=1 while primerIndice <= len(p2): primerIndice *= 2 arbol = [0]*(2*primerIndice - 1) primerIndice -=1 cruces=0 for i in range(len(sur)): indice=sur[i]+primerIndice try: arbol[indice]+=1 except: print "arbol",arbol print "indice",indice print "sur",sur print "i",i print "p1", p1 print "p2",p2 #print "lista2",lista2 print "b1", b1 print "b2", b2 while(indice > 0): if (indice % 2 == 1): cruces += arbol[indice+1] indice=(indice -1)/2 arbol[indice]+=1 return cruces # establece el rango en el cual se puede insertar un nodo # basicamente me fijo que si el tipo esta marcado, no lo trate de poner # antes de su anterior y despues de su posterior def _rango(self,x,pi,marcados): if x not in marcados: return range(len(pi)+1) else: posxMarcado = marcados.index(x) anterior=0 siguiente=len(pi)+1 if posxMarcado != 0: anterior= pi.index(marcados[posxMarcado-1])+1 if posxMarcado != len(marcados)-1: siguiente = pi.index(marcados[posxMarcado+1])+1 z=range(anterior,siguiente) if z == []: print "error", z,pi,marcados assert z != [] return z #establece los cruces entre dos nodos x e y para un dibujo dado def crucesEntre(self,x,y,p1,p2,losEjesDe): indiceX = p1.index(x) indiceY = p1.index(y) acum=0 for each in losEjesDe[x]: indiceEach = p2.index(each) for each2 in losEjesDe[y]: if indiceEach > p2.index(each2): acum += 1 return acum def resolver(self): # Mariconadas p1 = list(self.dibujo.g.p1) p2 = list(self.dibujo.g.p2) grafo = self.dibujo.g dibujo=self.dibujo #separo a los q ya estan en el dibujo (son los q tengo q manteer ordenados) marcadosl1 = list(self.dibujo.l1) marcadosl2 = list(self.dibujo.l2) #obtengo los que tengo que poner (los q me dieron para agregar) v1 = [x for x in p1 if x not in marcadosl1] v2 = [y for y in p2 if y not in marcadosl2] #meto a todos los nodos en un "dibujo" p1Parcial = marcadosl1 + v1 p2Parcial = marcadosl2 + v2 ejes = list(grafo.ejes) #genero todos los ejes del mundo :D todosLosEjes=[] for each in p1Parcial: for each1 in p2Parcial: todosLosEjes.append((each,each1)) ejesASacar=[x for x in todosLosEjes if x not in ejes] cruces=contarCrucesAcumTree(p1Parcial,p2Parcial,todosLosEjes) #la idea es similar a insercion de ejes for each in ejesASacar: (x,y) = each cantCruces = None Pos = (None, None) p1Parcial.remove(x) p2Parcial.remove(y) todosLosEjes.remove((x,y)) for i in self._rango(x,p1Parcial,marcadosl1): p1Parcial.insert(i,x) for j in self._rango(y,p2Parcial,marcadosl2): p2Parcial.insert(j,y) actual = contarCrucesAcumTree(p1Parcial,p2Parcial,todosLosEjes) p2Parcial.remove(y) if cantCruces == None or actual < cantCruces: cantCruces=actual pos=(i,j) p1Parcial.remove(x) p1Parcial.insert(pos[0],x) p2Parcial.insert(pos[1],y) cruces=contarCrucesAcumTree(p1Parcial,p2Parcial,todosLosEjes) losEjesDe={} for each in p1Parcial: losEjesDe[each]=[] for each in p2Parcial: losEjesDe[each]=[] for each in ejes: losEjesDe[each[0]].append(each[1]) losEjesDe[each[1]].append(each[0]) cambio =True while(cambio): cambio = False for i in range(len(p1Parcial)-1): if p1Parcial[i] not in marcadosl1 or p1Parcial[i+1] not in marcadosl1: comoEsta=self.crucesEntre(p1Parcial[i],p1Parcial[i+1],p1Parcial,p2Parcial,losEjesDe) swapeado=self.crucesEntre(p1Parcial[i+1],p1Parcial[i],p1Parcial,p2Parcial,losEjesDe) if swapeado < comoEsta: aux=p1Parcial[i] p1Parcial[i]=p1Parcial[i+1] p1Parcial[i+1]=aux cambio =True for i in range(len(p2Parcial)-1): if p2Parcial[i] not in marcadosl2 or p2Parcial[i+1] not in marcadosl2: comoEsta=self.crucesEntre(p2Parcial[i],p2Parcial[i+1],p2Parcial,p1Parcial,losEjesDe) swapeado=self.crucesEntre(p2Parcial[i+1],p2Parcial[i],p2Parcial,p1Parcial,losEjesDe) if swapeado < comoEsta: aux=p2Parcial[i] p2Parcial[i]=p2Parcial[i+1] p2Parcial[i+1]=aux cambio =True listita = range(1,len(p1Parcial)) listita.reverse() for i in listita: if p1Parcial[i] not in marcadosl1 or p1Parcial[i-1] not in marcadosl1: comoEsta=self.crucesEntre(p1Parcial[i-1],p1Parcial[i],p1Parcial,p2Parcial,losEjesDe) swapeado=self.crucesEntre(p1Parcial[i],p1Parcial[i-1],p1Parcial,p2Parcial,losEjesDe) if swapeado < comoEsta: aux=p1Parcial[i] p1Parcial[i]=p1Parcial[i-1] p1Parcial[i-1]=aux cambio =True listita = range(1,len(p2Parcial)) listita.reverse() for i in listita: if p2Parcial[i] not in marcadosl2 or p2Parcial[i-1] not in marcadosl2: comoEsta=self.crucesEntre(p2Parcial[i-1],p2Parcial[i],p2Parcial,p1Parcial,losEjesDe) swapeado=self.crucesEntre(p2Parcial[i],p2Parcial[i-1],p2Parcial,p1Parcial,losEjesDe) if swapeado < comoEsta: aux=p2Parcial[i] p2Parcial[i]=p2Parcial[i-1] p2Parcial[i-1]=aux cambio =True return Dibujo(grafo,p1Parcial,p2Parcial) if __name__ == '__main__': g = generarGrafoBipartitoAleatorio(5,5,7) print 'nodos =', g.p1 print 'nodos =', g.p2 print 'ejes =', g.ejes dib = generarDibujoAleatorio(g,2,4) resultado = HeuristicaRemocion(dib).resolver() DibujadorGrafoBipartito(resultado).grabar('dibujo.svg')
[ [ 1, 0, 0.0049, 0.0049, 0, 0.66, 0, 16, 0, 1, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0097, 0.0049, 0, 0.66, 0.25, 590, 0, 1, 0, 0, 590, 0, 0 ], [ 1, 0, 0.0146, 0.0049, 0, 0.66...
[ "from GrafoBipartito import *", "from GeneradorGrafos import *", "from Dibujador import *", "class HeuristicaRemocion (ResolvedorConstructivo):\n def contarCrucesAcumTree(p1,p2,ejes):\n if len(p1) < len(p2):\n return contarCrucesAcumTree(p2,p1,[(y,x) for (x,y) in ejes])\n lista=[]\...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo from GrafoBipartito import crucesEntre, crucesPorAgregarAdelante, crucesPorAgregarAtras from SolucionFuerzaBruta import cuantasCombinaciones class ResolvedorSwapperTabla(ResolvedorConstructivo): ########################################################### # Funcion global de resolución exacta # ########################################################### def resolver(self): g = self.dibujo.g d = self.dibujo self._inicializar() # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + self.q1, d.l2 + self.q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self._mejor() print "Listo! (cruces: %s)" % self.mejorDibujo.contarCruces() return self.mejorDibujo ########################################################### # Función auxiliar de inicialización # ########################################################### def _inicializar(self): g = self.dibujo.g d = self.dibujo # armo las listas de adyacencia del grafo completo ady = {} for n in g.p1: ady[n] = [] for n in g.p2: ady[n] = [] for a,b in g.ejes: ady[a].append(b) ady[b].append(a) self.ady = ady # busco los nodos que quedan por posicionar self.q1 = [x for x in g.p1 if not x in self.dibujo.l1] self.q2 = [x for x in g.p2 if not x in self.dibujo.l2] # elijo cual de las 2 mitades tiene menos permutaciones # para llenarla primero en el arbol de combinaciones # (esto puede mejorar el rendimiento del algoritmo) combs1 = cuantasCombinaciones(len(d.l1),0,len(self.q1),0) combs2 = cuantasCombinaciones(len(d.l2),0,len(self.q2),0) if combs1 > combs2: invertirLados = True else: invertirLados = False self.invertirLados = invertirLados # estos son los buffers que usa el algoritmo recursivo # (todas las llamadas operan sobre los mismos para evitar copias) if invertirLados: self.fijo1 = d.l2[:] self.fijo2 = d.l1[:] self.movil1 = self.q2 self.movil2 = self.q1 else: self.fijo1 = d.l1[:] self.fijo2 = d.l2[:] self.movil1 = self.q1 self.movil2 = self.q2 # armo las listas de adyacencia de p1 con los de d.l1 # (esto me permite calcular de forma eficiente los cruces # de una cierta permutacion de p1) adyp1 = {} if invertirLados: p1 = g.p2 else: p1 = g.p1 for n in p1: adyp1[n] = [] for a,b in g.ejes: if a in adyp1 and b in self.fijo2: adyp1[a].append(b) elif b in adyp1 and a in self.fijo2: adyp1[b].append(a) self.adyp1 = adyp1 # cache de posiciones para evitar busquedas self.posiciones1 = {} for i in range(len(self.fijo1)): self.posiciones1[self.fijo1[i]] = i self.posiciones2 = {} for i in range(len(self.fijo2)): self.posiciones2[self.fijo2[i]] = i # Cache de cruces para reutilizar calculos # tablaN[(i,j)] es la cantidad de cruces que hay entre # los nodos i,j si son contiguos en el candidato actual de pN self.tabla1 = {} self._tabular2() # cargo los cruces del dibujo original self.cruces = d.contarCruces() def _tabular2(self): # Reinicia la tabla de valores precalculados para p2 cuando cambia p1 # (en la implementacion sobre diccionario equivale a borrarlo) self.tabla2 = {} ########################################################### # Funciones auxiliares para modificacion de candidatos # ########################################################### # mueve movil1[0] a fijo1[n] def _agregarAtras1(self): cab = self.movil1.pop(0) self.fijo1.append(cab) self.posiciones1[cab] = len(self.fijo1) - 1 self.cruces += crucesPorAgregarAtras(self.fijo1, self.dibujo.l2, self.adyp1, indice2=self.posiciones2) # analogo para p1 def _agregarAtras2(self): cab = self.movil2.pop(0) self.fijo2.append(cab) self.cruces += crucesPorAgregarAtras(self.fijo2, self.fijo1, self.ady, indice2=self.posiciones1) # mueve fijo1[0] a movil1[n] def _sacarPrincipio1(self): self.cruces -= crucesPorAgregarAdelante(self.fijo1, self.dibujo.l2, self.adyp1, indice2=self.posiciones2) self.movil1.append(self.fijo1.pop(0)) # FIXME: esta operacion se puede ahorrar con un # offset entero que se resta a todas las posiciones for i in range(len(self.fijo1)): self.posiciones1[self.fijo1[i]] = i # analogo para p2 def _sacarPrincipio2(self): self.cruces -= crucesPorAgregarAdelante(self.fijo2, self.fijo1, self.ady, indice2=self.posiciones1) self.movil2.append(self.fijo2.pop(0)) # swapea fijo1[i] con fijo1[i-1] def _retrasar1(self, i): fijo1 = self.fijo1 a = len(fijo1) - 1 - i # busco en tabla, sino calculo try: cAntes = self.tabla1[(fijo1[a-1],fijo1[a])] except KeyError: cAntes = crucesEntre(fijo1[a-1], fijo1[a], self.dibujo.l2, self.adyp1, indice2=self.posiciones2) self.tabla1[(fijo1[a-1],fijo1[a])] = cAntes # swapeo y actualizo fijo1[a], fijo1[a-1] = fijo1[a-1], fijo1[a] self.posiciones1[fijo1[a]] = a self.posiciones1[fijo1[a-1]] = a-1 # busco en tabla, sino calculo try: cDespues = self.tabla1[(fijo1[a-1],fijo1[a])] except KeyError: cDespues = crucesEntre(fijo1[a-1], fijo1[a], self.dibujo.l2, self.adyp1, indice2=self.posiciones2) self.tabla1[(fijo1[a-1],fijo1[a])] = cDespues # actualizo la cuenta de cruces self.cruces = self.cruces - cAntes + cDespues # analogo para p2 def _retrasar2(self, i): fijo2 = self.fijo2 a = len(fijo2) - 1 - i # busco en tabla, sino calculo try: cAntes = self.tabla2[(fijo2[a-1],fijo2[a])] except KeyError: cAntes = crucesEntre(fijo2[a-1], fijo2[a], self.fijo1, self.ady, indice2=self.posiciones1) self.tabla2[(fijo2[a-1],fijo2[a])] = cAntes # swapeo (no hay nada que actualizar) fijo2[a], fijo2[a-1] = fijo2[a-1], fijo2[a] # busco en tabla, sino calculo try: cDespues = self.tabla2[(fijo2[a-1],fijo2[a])] except KeyError: cDespues = crucesEntre(fijo2[a-1], fijo2[a], self.fijo1, self.ady, indice2=self.posiciones1) self.tabla2[(fijo2[a-1],fijo2[a])] = cDespues # actualizo la cuenta de cruces self.cruces = self.cruces - cAntes + cDespues ########################################################### # Funcion auxiliar de busqueda del mejor candidato # ########################################################### def _mejor(self): # valores misc fijo1 = self.fijo1 fijo2 = self.fijo2 movil1 = self.movil1 movil2 = self.movil2 nf1 = len(fijo1) nf2 = len(fijo2) # esto corresponde al caso base, donde chequeo si obtuve una # solución mejor a la previamente máxima, y de ser así la # actualizo con el nuevo valor if movil1 == [] and movil2 == []: if self.cruces < self.mejorDibujo.contarCruces(): # creo un dibujo (copiando las listas!), y guardo la cantidad # de cruces que ya tengo calculada en el atributo cruces (para # evitar que se recalcule) if self.invertirLados: self.mejorDibujo = Dibujo(self.dibujo.g, fijo2[:], fijo1[:]) else: self.mejorDibujo = Dibujo(self.dibujo.g, fijo1[:], fijo2[:]) self.mejorDibujo.cruces = self.cruces # entro en este caso cuando ya complete una permutacion # de fijo1, y ahora tengo que elegir la mejor permutacion # para la particion 2 elif movil1 == []: self._agregarAtras2() for i in range(-1, nf2): if i != -1: self._retrasar2(i) self._mejor() self._sacarPrincipio2() # entro en este caso cuando lleno la permutacion de fijo1 # (siempre se hace esto antes de verificar la otra particion, # ya que elegimos fijo1 para que tenga menos permutaciones) else: self._agregarAtras1() for i in range(-1, nf1): if i != -1: self._retrasar1(i) if movil1 == []: self._tabular2() self._mejor() self._sacarPrincipio1() def test_resolvedorSwapperTabla(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=7, n2=7, m=15) d = generarDibujoAleatorio(g, n1=4, n2=4) r1 = ResolvedorFuerzaBruta(d) s1 = r1.resolver() r2 = ResolvedorSwapperTabla(d) s2 = r2.resolver() assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorSwapperTabla()
[ [ 1, 0, 0.0129, 0.0032, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.029, 0.0032, 0, 0.66, 0.1667, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0323, 0.0032, 0, 0.6...
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "from GrafoBipartito import crucesEntre, crucesPorAgregarAdelante, crucesPorAgregarAtras", "from SolucionFuerzaBruta import cuantasCombinaciones", "class ResolvedorSwapperTabla(ResolvedorConstructivo):\n\n ########################...
# Heuristica de agregar nodos de a uno y a acomodarlos from GrafoBipartito import ResolvedorConstructivo, Dibujo, GrafoBipartito from Dibujador import DibujadorGrafoBipartito from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from sets import * class HeuristicaInsercionNodosMayorGrado(ResolvedorConstructivo): def resolver(self, alfa=1): d = self.dibujo g = self.dibujo.g res1 = d.l1[:] res2 = d.l2[:] movilesEnV1 = [x for x in g.p1 if not x in d.l1] # los moviles de V1 movilesEnV2 = [x for x in g.p2 if not x in d.l2] # los moviles de V2 dibujo = Dibujo(g,res1[:],res2[:]) while(movilesEnV1 != [] or movilesEnV2 != []): if movilesEnV1 != [] : v = movilesEnV1.pop(self._indiceMayorGrado(movilesEnV1, movilesEnV2, dibujo, alfa)) #print 'v en v1', v dibujo = self._insertarNodo(v, res1, True, dibujo) res1 = dibujo.l1[:] if movilesEnV2 != [] : v = movilesEnV2.pop(self._indiceMayorGrado(movilesEnV2, movilesEnV1, dibujo, alfa)) #print 'v en v2', v dibujo = self._insertarNodo(v, res2, False, dibujo) res2 = dibujo.l2[:] # ahora intento mejorar el resultado con un sort loco por cruces entre pares de nodos for i in range(len(res1)-1): ejesDe = {} v1 = res1[i] v2 = res1[i+1] if v1 not in d.l1 or v2 not in d.l1: # verifico que v1 y v2 se puedan mover ejesDe[v1] = [x[1] for x in dibujo.g.ejes if x[0] == v1] ejesDe[v2] = [x[1] for x in dibujo.g.ejes if x[0] == v2] if self._crucesEntre(v1, v2, res1, res2, ejesDe) > self._crucesEntre(v2, v1, res1, res2, ejesDe): res1[i] = v2 res1[i+1] = v1 dibujo = Dibujo(g, res1, res2) return dibujo def _indiceMayorGrado(self, movilesEnVi, movilesEnVj, dibujo, alfa): indiceMayor = 0 ejesMayor = [x for x in dibujo.g.ejes if (x[0] == movilesEnVi[0] and x[1] not in movilesEnVj) or (x[1] == movilesEnVi[0] and x[0] not in movilesEnVj)] for i in range(len(movilesEnVi)): ejesIesimo = [x for x in dibujo.g.ejes if (x[0] == movilesEnVi[i] and x[1] not in movilesEnVj) or (x[1] == movilesEnVi[i] and x[0] not in movilesEnVj)] if len(ejesIesimo) > len(ejesMayor)*alfa: indiceMayor = i ejesMayor = ejesIesimo return indiceMayor def _insertarNodo(self, v, Vi, agregoEnV1, dibujo): g = self.dibujo.g aux = Vi[:] aux.insert(0, v) if agregoEnV1: mejorDibujo = Dibujo(g, aux[:], dibujo.l2) else: mejorDibujo = Dibujo(g, dibujo.l1, aux[:]) crucesMejorDibujo = mejorDibujo.contarCruces() for i in range(len(Vi)): aux.remove(v) aux.insert(i + 1, v) if(agregoEnV1): dibujoCandidato = Dibujo(g, aux[:], dibujo.l2) else: dibujoCandidato = Dibujo(g, dibujo.l1, aux[:]) crucesCandidato = dibujoCandidato.contarCruces() #print 'crucesCandidato', crucesCandidato #print 'crucesMejorDibujo', crucesMejorDibujo if crucesCandidato < crucesMejorDibujo : mejorDibujo = dibujoCandidato crucesMejorDibujo = crucesCandidato #print 'mejorDibujo', mejorDibujo #print 'cruces posta', mejorDibujo._contarCruces() return mejorDibujo def _crucesEntre(self,x,y,p1,p2,losEjesDe): indiceX = p1.index(x) indiceY = p1.index(y) acum = 0 for each in losEjesDe[x]: indiceEach = p2.index(each) for each2 in losEjesDe[y]: if indiceEach > p2.index(each2): acum += 1 return acum if __name__ == '__main__': p1 = Set([1,2,3,4]) p2 = Set([5,6,7,8]) l1 = [2,4] l2 = [6,7,8] ejes = Set([(1,7), (2,5), (2,8), (3,6), (3,7), (3,8), (4,8)]) dib = Dibujo(GrafoBipartito(p1,p2,ejes), l1, l2) # DibujadorGrafoBipartito(dib).grabar('dibujo.svg') resultado = HeuristicaInsercionNodosMayorGrado(dib).resolver(1) DibujadorGrafoBipartito(resultado).grabar('resultado.svg')
[ [ 1, 0, 0.0183, 0.0092, 0, 0.66, 0, 16, 0, 3, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0275, 0.0092, 0, 0.66, 0.2, 851, 0, 1, 0, 0, 851, 0, 0 ], [ 1, 0, 0.0367, 0.0092, 0, 0.66,...
[ "from GrafoBipartito import ResolvedorConstructivo, Dibujo, GrafoBipartito", "from Dibujador import DibujadorGrafoBipartito", "from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio", "from sets import *", "class HeuristicaInsercionNodosMayorGrado(ResolvedorConstructivo):\n de...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys #import psyco #psyco.full() from GrafoBipartito import Dibujo, ResolvedorConstructivo from GrafoBipartito import crucesEntre, crucesPorAgregarAdelante, crucesPorAgregarAtras from SolucionFuerzaBruta import cuantasCombinaciones, tamArbol class ResolvedorSwapperTablaConPoda(ResolvedorConstructivo): ########################################################### # Funcion global de resolución exacta # ########################################################### def resolver(self, invertir=True): self.invertir = invertir g = self.dibujo.g d = self.dibujo self._inicializar() # cargo un candidato inicial self.mejorDibujo = Dibujo(g, d.l1 + self.q1, d.l2 + self.q2) # busco el mejor candidato print "Explorando conjunto de soluciones... ", sys.stdout.flush() self.podasHojas = 0 self.podasArbol = 0 self.casosBase = 0 self.llamadas = 0 combinaciones = cuantasCombinaciones(self.fijo1, self.fijo2, self.movil1, self.movil2) tamanioArbol = tamArbol(self.fijo1, self.fijo2, self.movil1, self.movil2) self._mejor() assert tamanioArbol == self.llamadas + self.podasArbol assert combinaciones == self.casosBase + self.podasHojas porcent_podasArbol = (self.podasArbol * 100.0) / tamanioArbol porcent_podasHojas = (self.podasHojas * 100.0) / combinaciones print "Listo! (cruces: %s, podas: %.6f%% de nodos, %.6f%% de hojas)" % \ (self.mejorDibujo.contarCruces(), porcent_podasArbol, porcent_podasHojas) return self.mejorDibujo ########################################################### # Función auxiliar de inicialización # ########################################################### def _inicializar(self): g = self.dibujo.g d = self.dibujo # armo las listas de adyacencia del grafo completo ady = {} for n in g.p1: ady[n] = [] for n in g.p2: ady[n] = [] for a,b in g.ejes: ady[a].append(b) ady[b].append(a) self.ady = ady # busco los nodos que quedan por posicionar self.q1 = [x for x in g.p1 if not x in self.dibujo.l1] self.q2 = [x for x in g.p2 if not x in self.dibujo.l2] # elijo cual de las 2 mitades tiene menos permutaciones # para llenarla primero en el arbol de combinaciones # (esto puede mejorar el rendimiento del algoritmo) combs1 = cuantasCombinaciones(len(d.l1),0,len(self.q1),0) combs2 = cuantasCombinaciones(len(d.l2),0,len(self.q2),0) if combs1 > combs2: invertirLados = True else: invertirLados = False if not self.invertir: invertirLados = False self.invertirLados = invertirLados # estos son los buffers que usa el algoritmo recursivo # (todas las llamadas operan sobre los mismos para evitar copias) if invertirLados: self.fijo1 = d.l2[:] self.fijo2 = d.l1[:] self.movil1 = self.q2 self.movil2 = self.q1 self.l1 = list(g.p2) self.l2 = list(g.p1) else: self.fijo1 = d.l1[:] self.fijo2 = d.l2[:] self.movil1 = self.q1 self.movil2 = self.q2 self.l1 = list(g.p1) self.l2 = list(g.p2) # armo las listas de adyacencia de p1 con los de d.l1 # (esto me permite calcular de forma eficiente los cruces # de una cierta permutacion de p1) adyp1 = {} if invertirLados: p1 = g.p2 else: p1 = g.p1 for n in p1: adyp1[n] = [] if not invertirLados: for a,b in g.ejes: if a in adyp1 and b in self.fijo2: adyp1[a].append(b) elif b in adyp1 and a in self.fijo2: adyp1[b].append(a) else: for b,a in g.ejes: if a in adyp1 and b in self.fijo2: adyp1[a].append(b) elif b in adyp1 and a in self.fijo2: adyp1[b].append(a) self.adyp1 = adyp1 # cache de posiciones para evitar busquedas self.posiciones1 = {} for i in range(len(self.fijo1)): self.posiciones1[self.fijo1[i]] = i self.posiciones2 = {} for i in range(len(self.fijo2)): self.posiciones2[self.fijo2[i]] = i # Cache de cruces para reutilizar calculos # tablaN[(i,j)] es la cantidad de cruces que hay entre # los nodos i,j si son contiguos en el candidato actual de pN self._tabular1() if self.movil1 == []: self._tabular2() # cargo los cruces del dibujo original self.cruces = d.contarCruces() def _tabular1(self): # Inicializa la tabla de valores precalculados para p1 (vs. fijo2) # FIXME: hay calculos innecesarios self.tabla1 = {} for i in self.l1: for j in self.l1: if i < j: c = crucesEntre(i, j, self.fijo2, self.adyp1,indice2=self.posiciones2) self.tabla1[(i,j)] = c c = crucesEntre(j, i, self.fijo2, self.adyp1,indice2=self.posiciones2) self.tabla1[(j,i)] = c def _tabular2(self): # Reinicia la tabla de valores precalculados para p2 cuando cambia p1 # FIXME: hay calculos innecesarios self.tabla2 = {} for i in self.l2: for j in self.l2: if i < j: c = crucesEntre(i,j, self.fijo1, self.ady,indice2=self.posiciones1) self.tabla2[(i,j)] = c c = crucesEntre(j,i, self.fijo1, self.ady,indice2=self.posiciones1) self.tabla2[(j,i)] = c def _minimosCrucesRestantes2(self): c = 0 for i in self.movil2: for j in self.movil2: if i < j: c += min(self.tabla2[(i,j)], self.tabla2[(j,i)]) for j in self.fijo2: c += min(self.tabla2[(i,j)], self.tabla2[(j,i)]) return c def _minimosCrucesRestantes1(self): c = 0 for i in self.movil1: for j in self.movil1: if i < j: c += min(self.tabla1[(i,j)], self.tabla1[(j,i)]) for j in self.fijo1: c += min(self.tabla1[(i,j)], self.tabla1[(j,i)]) return c ########################################################### # Funciones auxiliares para modificacion de candidatos # ########################################################### # mueve movil1[0] a fijo1[n] def _agregarAtras1(self): cab = self.movil1.pop(0) self.fijo1.append(cab) self.posiciones1[cab] = len(self.fijo1) - 1 self.cruces += crucesPorAgregarAtras(self.fijo1, self.fijo2, self.adyp1, indice2=self.posiciones2) # analogo para p1 def _agregarAtras2(self): cab = self.movil2.pop(0) self.fijo2.append(cab) self.cruces += crucesPorAgregarAtras(self.fijo2, self.fijo1, self.ady, indice2=self.posiciones1) # mueve fijo1[0] a movil1[n] def _sacarPrincipio1(self): self.cruces -= crucesPorAgregarAdelante(self.fijo1, self.fijo2, self.adyp1, indice2=self.posiciones2) self.movil1.append(self.fijo1.pop(0)) # FIXME: esta operacion se puede ahorrar con un # offset entero que se resta a todas las posiciones for i in range(len(self.fijo1)): self.posiciones1[self.fijo1[i]] = i # analogo para p2 def _sacarPrincipio2(self): self.cruces -= crucesPorAgregarAdelante(self.fijo2, self.fijo1, self.ady, indice2=self.posiciones1) self.movil2.append(self.fijo2.pop(0)) # swapea fijo1[i] con fijo1[i-1] def _retrasar1(self, i): fijo1 = self.fijo1 a = len(fijo1) - 1 - i cAntes = self.tabla1[(fijo1[a-1],fijo1[a])] # swapeo y actualizo fijo1[a], fijo1[a-1] = fijo1[a-1], fijo1[a] self.posiciones1[fijo1[a]] = a self.posiciones1[fijo1[a-1]] = a-1 # actualizo la cuenta de cruces cDespues = self.tabla1[(fijo1[a-1],fijo1[a])] self.cruces = self.cruces - cAntes + cDespues # analogo para p2 def _retrasar2(self, i): fijo2 = self.fijo2 a = len(fijo2) - 1 - i cAntes = self.tabla2[(fijo2[a-1],fijo2[a])] # swapeo (no hay nada que actualizar) fijo2[a], fijo2[a-1] = fijo2[a-1], fijo2[a] # actualizo la cuenta de cruces cDespues = self.tabla2[(fijo2[a-1],fijo2[a])] self.cruces = self.cruces - cAntes + cDespues ########################################################### # Funcion auxiliar de busqueda del mejor candidato # ########################################################### def _mejor(self): self.llamadas += 1 # valores misc fijo1 = self.fijo1 fijo2 = self.fijo2 movil1 = self.movil1 movil2 = self.movil2 nf1 = len(fijo1) nf2 = len(fijo2) # esto corresponde al caso base, donde chequeo si obtuve una # solución mejor a la previamente máxima, y de ser así la # actualizo con el nuevo valor if movil1 == [] and movil2 == []: self.casosBase += 1 if self.cruces < self.mejorDibujo.contarCruces(): # creo un dibujo (copiando las listas!), y guardo la cantidad # de cruces que ya tengo calculada en el atributo cruces (para # evitar que se recalcule) if self.invertirLados: self.mejorDibujo = Dibujo(self.dibujo.g, fijo2[:], fijo1[:]) else: self.mejorDibujo = Dibujo(self.dibujo.g, fijo1[:], fijo2[:]) self.mejorDibujo.cruces = self.cruces # entro en este caso cuando ya complete una permutacion # de fijo1, y ahora tengo que elegir la mejor permutacion # para la particion 2 elif movil1 == []: self._agregarAtras2() for i in range(-1, nf2): if i != -1: self._retrasar2(i) if self._minimosCrucesRestantes2() + self.cruces < self.mejorDibujo.contarCruces(): self._mejor() else: self.podasHojas += cuantasCombinaciones(fijo1, fijo2, movil1, movil2) self.podasArbol += tamArbol(fijo1, fijo2, movil1, movil2) self._sacarPrincipio2() # entro en este caso cuando lleno la permutacion de fijo1 # (siempre se hace esto antes de verificar la otra particion, # ya que elegimos fijo1 para que tenga menos permutaciones) else: self._agregarAtras1() for i in range(-1, nf1): if i != -1: self._retrasar1(i) if movil1 == []: self._tabular2() if self._minimosCrucesRestantes1() + self.cruces < self.mejorDibujo.contarCruces(): self._mejor() else: self.podasHojas += cuantasCombinaciones(fijo1, fijo2, movil1, movil2) self.podasArbol += tamArbol(fijo1, fijo2, movil1, movil2) self._sacarPrincipio1() def test_resolvedorSwapperTablaConPoda(): from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio from SolucionFuerzaBruta import ResolvedorFuerzaBruta g = generarGrafoBipartitoAleatorio(n1=6, n2=6, m=30) d = generarDibujoAleatorio(g, n1=4, n2=5) #r1 = ResolvedorFuerzaBruta(d) #s1 = r1.resolver() r2 = ResolvedorSwapperTablaConPoda(d) s2 = r2.resolver() #assert s1.contarCruces() == s2.contarCruces() if __name__ == '__main__': test_resolvedorSwapperTablaConPoda()
[ [ 1, 0, 0.0109, 0.0027, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0245, 0.0027, 0, 0.66, 0.1667, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0272, 0.0027, 0, 0....
[ "import sys", "from GrafoBipartito import Dibujo, ResolvedorConstructivo", "from GrafoBipartito import crucesEntre, crucesPorAgregarAdelante, crucesPorAgregarAtras", "from SolucionFuerzaBruta import cuantasCombinaciones, tamArbol", "class ResolvedorSwapperTablaConPoda(ResolvedorConstructivo):\n\n #######...
# Heuristica de agregar nodos de a uno y a acomodarlos from GrafoBipartito import ResolvedorConstructivo, Dibujo from Dibujador import DibujadorGrafoBipartito from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio import random class HeuristicaInsercionNodosRandom(ResolvedorConstructivo): #TODO: agregar valor alfa para la seleccion randomizada de los nodos def resolver(self): d = self.dibujo g = self.dibujo.g res1 = d.l1[:] res2 = d.l2[:] movilesEnV1 = [x for x in g.p1 if not x in d.l1] # los moviles de V1 movilesEnV2 = [x for x in g.p2 if not x in d.l2] # los moviles de V2 dibujo = Dibujo(g,res1[:],res2[:]) while(movilesEnV1 != [] or movilesEnV2 != []): if movilesEnV1 != [] : v = movilesEnV1.pop(random.randint(0, len(movilesEnV1) - 1)) dibujo = self._insertarNodo(v, res1, True, dibujo) res1 = dibujo.l1[:] if movilesEnV2 != [] : v = movilesEnV2.pop(random.randint(0, len(movilesEnV2) - 1)) dibujo = self._insertarNodo(v, res2, False, dibujo) res2 = dibujo.l2[:] # ahora intento mejorar el resultado con un sort loco por cruces entre pares de nodos for i in range(len(res1)-1): ejesDe = {} v1 = res1[i] v2 = res1[i+1] if v1 not in d.l1 or v2 not in d.l1: # verifico que v1 y v2 se puedan mover ejesDe[v1] = [x[1] for x in dibujo.g.ejes if x[0] == v1] ejesDe[v2] = [x[1] for x in dibujo.g.ejes if x[0] == v2] if self._crucesEntre(v1, v2, res1, res2, ejesDe) > self._crucesEntre(v2, v1, res1, res2, ejesDe): res1[i] = v2 res1[i+1] = v1 dibujo = Dibujo(g, res1, res2) return dibujo def _insertarNodo(self, v, Vi, agregoEnV1, dibujo): g = self.dibujo.g aux = Vi[:] aux.insert(0, v) if agregoEnV1: mejorDibujo = Dibujo(g, aux[:], dibujo.l2) else: mejorDibujo = Dibujo(g, dibujo.l1, aux[:]) crucesMejorDibujo = mejorDibujo.contarCruces() for i in range(len(Vi)): aux.remove(v) aux.insert(i + 1, v) if(agregoEnV1): dibujoCandidato = Dibujo(g, aux[:], dibujo.l2) else: dibujoCandidato = Dibujo(g, dibujo.l1, aux[:]) crucesCandidato = dibujoCandidato.contarCruces() #print 'crucesCandidato', crucesCandidato #print 'crucesMejorDibujo', crucesMejorDibujo if crucesCandidato < crucesMejorDibujo : mejorDibujo = dibujoCandidato crucesMejorDibujo = crucesCandidato #print 'mejorDibujo', mejorDibujo #print 'cruces posta', mejorDibujo._contarCruces() return mejorDibujo def _crucesEntre(self,x,y,p1,p2,losEjesDe): indiceX = p1.index(x) indiceY = p1.index(y) acum = 0 for each in losEjesDe[x]: indiceEach = p2.index(each) for each2 in losEjesDe[y]: if indiceEach > p2.index(each2): acum += 1 return acum if __name__ == '__main__': g = generarGrafoBipartitoAleatorio(10,10,30) print 'nodos =', g.p1 print 'nodos =', g.p2 print 'ejes =', g.ejes dib = generarDibujoAleatorio(g,2,4) resultado = HeuristicaInsercionNodosRandom(dib).resolver() DibujadorGrafoBipartito(resultado).grabar('dibujo.svg')
[ [ 1, 0, 0.0211, 0.0105, 0, 0.66, 0, 16, 0, 2, 0, 0, 16, 0, 0 ], [ 1, 0, 0.0316, 0.0105, 0, 0.66, 0.2, 851, 0, 1, 0, 0, 851, 0, 0 ], [ 1, 0, 0.0421, 0.0105, 0, 0.66,...
[ "from GrafoBipartito import ResolvedorConstructivo, Dibujo", "from Dibujador import DibujadorGrafoBipartito", "from GeneradorGrafos import generarGrafoBipartitoAleatorio, generarDibujoAleatorio", "import random", "class HeuristicaInsercionNodosRandom(ResolvedorConstructivo):\n #TODO: agregar valor alfa p...