code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
#!/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/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... |
# -*- coding: cp1252 -*-
from HeuristicaDeLaMediana import *
from HeuristicaInsercionEjes import *
from HeuristicaInsercionNodosMayorGrado import *
from HeuristicaInsercionNodosMenorGrado import *
from HeuristicaInsercionNodosPrimero import *
from HeuristicaInsercionNodosRandom import *
#import psyco
#psyco.full()
def testHeuristicasAgregarNodos(p1,p2,v1,v2,m):
g = generarGrafoBipartitoAleatorio(p1+v1, p2+v2, m)
d = generarDibujoAleatorio(g, v1, v2)
resMayorGrado = HeuristicaInsercionNodosMayorGrado(d).resolver(0)
print 'Cruces insercion nodo mayor grado:', resMayorGrado.contarCruces()
resMenorGrado = HeuristicaInsercionNodosMenorGrado(d).resolver(0)
print 'Cruces insercion nodo menor grado:', resMenorGrado.contarCruces()
resPrimero = HeuristicaInsercionNodosPrimero(d).resolver()
print 'Cruces insercion nodo primero:', resPrimero.contarCruces()
resRandom = HeuristicaInsercionNodosRandom(d).resolver()
print 'Cruces insercion nodo random:', resRandom.contarCruces()
def testHeuristicas(p1,p2,v1,v2,m):
g = generarGrafoBipartitoAleatorio(p1+v1, p2+v2, m)
d = generarDibujoAleatorio(g, v1, v2)
#resMed = HeuristicaDeLaMediana(d).resolver()
#resInsNM = HeuristicaInsercionNodosMayorGrado(d).resolver()
#resInsNP = HeuristicaInsercionNodosMayorGrado(d).resolver()
resInsNm = HeuristicaInsercionNodosMenorGrado(d).resolver()
resInsNR = HeuristicaInsercionNodosRandomGrado(d).resolver()
#resInsE = HeuristicaInsercionEjes(d).resolver()
return (resMed.contarCruces(),resInsNM.contarCruces(),resInsNm.contarCruces(),resInsNR.contarCruces(),resInsE.contarCruces())
def testEsparsos(p1Max):
med = open("testEsparsoMed.m","w")
insE = open("testEsparsoInsE.m","w")
insN = open("testEsparsoInsN.m","w")
med.write("med=[")
insN.write("insN=[")
insE.write("insE=[")
for each in range(3,p1Max+1):
res = testHeuristicas(each,each,each/2,each/2,2*each)
med.write(str(res[0])+" ")
insN.write(str(res[1])+" ")
insE.write(str(res[2])+" ")
med.write("];")
insN.write("];")
insE.write("];")
p1 = open("testEsparso.m","w")
p1.write("n="+str(range(3,p1Max+1))+";")
def testMitadDeEjes(p1Max):
med = open("testMitadMed.m","w")
insE = open("testMitadInsE.m","w")
insNM = open("testMitadInsNM.m","w")
insNm = open("testMitadInsNme.m","w")
insNR = open("testMitadInsNR.m","w")
med.write("med=[")
insNM.write("insNM=[")
insNm.write("insNm=[")
insNR.write("insNR=[")
insE.write("insE=[")
for each in range(3,p1Max+1):
print each
res = testHeuristicas(each,each,each/2,each/2,(each*each)/2)
med.write(str(res[0])+" ")
insNM.write(str(res[1])+" ")
insNm.write(str(res[2])+" ")
insNR.write(str(res[3])+" ")
insE.write(str(res[4])+" ")
med.write("];")
insNM.write("];")
insNm.write("];")
insNR.write("];")
insE.write("];")
p1 = open("testMitad.m","w")
p1.write("n="+str(range(3,p1Max+1))+";")
def testDenso(p1Max):
med = open("testDensoMed.m","w")
insE = open("testDensoInsE.m","w")
insN = open("testDensoInsN.m","w")
med.write("med=[")
insN.write("insN=[")
insE.write("insE=[")
for each in range(3,p1Max+1):
res = testHeuristicas(each,each,each/2,each/2,(each*each)-each)
med.write(str(res[0])+" ")
insN.write(str(res[1])+" ")
insE.write(str(res[2])+" ")
med.write("];")
insN.write("];")
insE.write("];")
p1 = open("testDenso.m","w")
p1.write("n="+str(range(3,p1Max+1))+";")
#testDenso(100)
#testHeuristicasAgregarNodos(10,10,5,5,30)
testMitadDeEjes(50)
| [
[
1,
0,
0.0202,
0.0101,
0,
0.66,
0,
580,
0,
1,
0,
0,
580,
0,
0
],
[
1,
0,
0.0303,
0.0101,
0,
0.66,
0.0909,
287,
0,
1,
0,
0,
287,
0,
0
],
[
1,
0,
0.0404,
0.0101,
0,
... | [
"from HeuristicaDeLaMediana import *",
"from HeuristicaInsercionEjes import *",
"from HeuristicaInsercionNodosMayorGrado import *",
"from HeuristicaInsercionNodosMenorGrado import *",
"from HeuristicaInsercionNodosPrimero import *",
"from HeuristicaInsercionNodosRandom import *",
"def testHeuristicasAgr... |
from GrafoBipartito import *
from GeneradorGrafos import *
from Dibujador import *
from SolucionBasicaPoda import *
# grafo: todos los nodos y ejes, p1 p2 estaRel(v,u)
#dibujo: l1, l2 los nodos que no se pueden mover
class HeuristicaMediana2 (ResolvedorConstructivo):
def calcularMediana(self,each,indicesV2,ejesDe):
med=[]
for each2 in ejesDe[each]:
med += [indicesV2[each2]]
med.sort()
if len(ejesDe[each]) % 2 == 1:
return med[len(ejesDe[each])/2]
elif len(ejesDe[each]) > 0:
return int(round((med[len(ejesDe[each])/2] + med[(len((ejesDe[each]))-1)/2])/2.0) )
else:
return 0
def disponerSegunMediana(self,v1,medianasV1,ejesDe,largoV2,marcados1):
#primero ordeno los v1 por grado, hago binsort
ordenados = [[] for x in range(largoV2+1)]
for each in v1:
ordenados[len(ejesDe[each])].append(each)
#los voy a meter en un arreglo que tiene tantos lugares como
#max v1,v2 porq si v2 es mas largo que v1 la mediana puede ser muy
#grande, y si v1 es mas grande tengo q meter a todos :D
metidos = [None for x in range(max(len(v1),largoV2)+1)]
#la idea es ir metiendo a los de mayor grado
while ordenados != []:
grado = ordenados.pop()
for each in grado:
if each not in marcados1:
if metidos[medianasV1[each]] == None:
metidos[medianasV1[each]] = each
else:
i = 1
loPuse = False
while(True):
if medianasV1[each] + i < len(metidos):
if metidos[medianasV1[each]+i] == None:
metidos[medianasV1[each]+i] = each
break
if medianasV1[each] - i >= 0:
if metidos[medianasV1[each]-i] == None:
metidos[medianasV1[each]-i] = each
break
elif medianasV1[each] - i >= 0:
if metidos[medianasV1[each]-i] == None:
metidos[medianasV1[each]-i] = each
break
else:
raise Exception("indice re sacado")
i+=1
else:
#primero averiguo el rango donde lo puedo poner
i = marcados1.index(each)
anterior = 0
siguiente = len(metidos)
k = 0
if i != 0:
while (i -1 - k) >= 0:
if marcados1[i-1-k] in metidos:
anterior = metidos.index(marcados1[i-1-k])
break
k+=1
k=0
if i != len(marcados1)- 1:
while(i+1+k <= len(marcados1)-1):
if marcados1[i+1+k] in metidos:
siguiente = metidos.index(marcados1[i+1+k])
break
k+=1
#despues trato de ponerlo:
loMeti = False
if medianasV1[each] == None:
if medianasV1[each] > anterior and medianasV1[each] < siguiente:
metidos[medianasV1[each]] = each
loMeti = True
if not loMeti:
i = 1
loPuse = False
while(True):
if medianasV1[each] + i < len(metidos):
if metidos[medianasV1[each]+i] == None:
pos = medianasV1[each]+i
break
elif medianasV1[each] - i >= 0:
if metidos[medianasV1[each]-i] == None:
pos = medianasV1[each]-i
break
else:
pos = None
break
i+=1
if pos != None and pos > anterior and pos < siguiente:
metidos[pos] = each
else:
if abs(anterior-medianasV1[each]) < abs(siguiente-medianasV1[each]):
metidos.insert(anterior+1,each)
else:
metidos.insert(siguiente,each)
v1Aux = [x for x in metidos if x != None]
return v1Aux
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 resolver(self):
#nodos sin marcar en cada particio
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
print "marcados1",marcados1
print "marcados2",marcados2
#nodos totales
v1 = sinMarcar1 + marcados1
v2 = sinMarcar2 + marcados2
#inicializa arreglo de medianas para los nodos de v1
medianaV1={}
#ejesDe: listas de adyacencias
ejesDe = {}
#lo inicializo
for each in v1+v2:
ejesDe[each] = []
#la completo
for each in self.dibujo.g.ejes:
ejesDe[each[0]].append(each[1])
ejesDe[each[1]].append(each[0])
#para calcular las medianas voy a necesitar saber las posiciones de
#cada nodo de v2
for each in range(2):
indicesV2 ={}
for i in range(len(v2)):
indicesV2[v2[i]] = i
#calculo las medianas de v1
for each in v1:
medianaV1[each] = self.calcularMediana(each,indicesV2,ejesDe)
#los dispongo segun la mediana
v1Aux = self.disponerSegunMediana(v1,medianaV1,ejesDe,len(v2),marcados1)
#se hace una pasada para corregir errores por desempate
v1 = self.corregirDesvios(v1Aux,v2,marcados1,ejesDe)
# ahora se repite el proceso pero para v2
indicesV1 ={}
medianaV2={}
for i in range(len(v1)):
indicesV1[v1[i]] = i
#calculo las medianas de v2
for each in v2:
medianaV2[each] = self.calcularMediana(each,indicesV1,ejesDe)
#los dispongo segun la mediana
v2Aux = self.disponerSegunMediana(v2,medianaV2,ejesDe,len(v1),marcados2)
#se hace una pasada para corregir errores por desempate
v2 = self.corregirDesvios(v2Aux,v1,marcados2,ejesDe)
# ahora se repite el proceso pero para v2
return Dibujo(self.dibujo.g,v1,v2)
if __name__ == '__main__':
g = generarGrafoBipartitoAleatorio(7,7,32)
print 'nodos =', g.p1
print 'nodos =', g.p2
print 'ejes =', g.ejes
dib = generarDibujoAleatorio(g,2,2)
resultado = HeuristicaMediana2(dib).resolver()
resultado2 = ResolvedorBasicoConPoda(dib).resolver()
print "mediana", resultado.contarCruces()
print "posta", resultado2.contarCruces()
DibujadorGrafoBipartito(resultado).grabar('dibujo.svg')
| [
[
1,
0,
0.0052,
0.0052,
0,
0.66,
0,
16,
0,
1,
0,
0,
16,
0,
0
],
[
1,
0,
0.0104,
0.0052,
0,
0.66,
0.2,
590,
0,
1,
0,
0,
590,
0,
0
],
[
1,
0,
0.0156,
0.0052,
0,
0.66,... | [
"from GrafoBipartito import *",
"from GeneradorGrafos import *",
"from Dibujador import *",
"from SolucionBasicaPoda import *",
"class HeuristicaMediana2 (ResolvedorConstructivo):\n def calcularMediana(self,each,indicesV2,ejesDe):\n med=[]\n for each2 in ejesDe[each]:\n med += [i... |
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\... |
from GrafoBipartito import GrafoBipartito, Dibujo
from Dibujador import DibujadorGrafoBipartito
from sets import Set
# Parsea un archivo .in con una sola instancia y produce
# el dibujo asociado.
class ParserDibujoIn:
def __init__(self, archivo="Tp3.in"):
f = open(archivo, 'r')
nf1 = int(f.readline())
fijo1 = []
nodos1 = []
for i in range(nf1):
n = int(f.readline())
fijo1.append(n)
nodos1.append(n)
nf2 = int(f.readline())
fijo2 = []
nodos2 = []
for i in range(nf2):
n = int(f.readline())
fijo2.append(n)
nodos2.append(n)
ejes = []
nejes = int(f.readline())
for i in range(nejes):
a,b = f.readline().split()
ejes.append((int(a),int(b)))
nm1 = int(f.readline())
for i in range(nm1):
n = int(f.readline())
nodos1.append(n)
nm2 = int(f.readline())
for i in range(nm2):
n = int(f.readline())
nodos2.append(n)
nejes = int(f.readline())
for i in range(nejes):
a,b = f.readline().split()
ejes.append((int(a),int(b)))
f.close()
g = GrafoBipartito(Set(nodos1), Set(nodos2), Set(ejes))
self.d = Dibujo(g, fijo1, fijo2)
def dibujo(self):
return self.d
# Parsea un archivo .out con una sola instancia y devuelve
# el dibujo asociado.
class ParserDibujoOut:
def __init__(self, archivo="Tp3.out"):
# levanto el archivo
f = open(archivo, 'r')
# cantidad de nodos en P1
cantLineas = int(f.readline())
nodosP1 = []
for i in range(cantLineas):
nodosP1.append(int(f.readline()))
print nodosP1[i]
# cantidad de nodos en P2
cantLineas = int(f.readline())
nodosP2 = []
for i in range(cantLineas):
nodosP2.append(int(f.readline()))
print nodosP2[i]
# cantidad de ejes
cantLineas = int(f.readline())
ejes = []
for i in range(cantLineas):
ejeArr = f.readline().split()
ejes.append((int(ejeArr[0]), int(ejeArr[1])))
print ejes[i]
# fin del archivo
f.close()
g = GrafoBipartito(Set(nodosP1), Set(nodosP2), Set(ejes))
self.d = Dibujo(g, nodosP1, nodosP2)
def dibujo(self):
return self.d
if __name__ == '__main__':
dib = ParserDibujoIn('../codigo/Tp3_chico.in').dibujo()
print dib
from SolucionSwapperTablaPoda import ResolvedorSwapperTablaConPoda
s = ResolvedorSwapperTablaConPoda(dib).resolver()
print s
| [
[
1,
0,
0.0103,
0.0103,
0,
0.66,
0,
16,
0,
2,
0,
0,
16,
0,
0
],
[
1,
0,
0.0206,
0.0103,
0,
0.66,
0.2,
851,
0,
1,
0,
0,
851,
0,
0
],
[
1,
0,
0.0309,
0.0103,
0,
0.66,... | [
"from GrafoBipartito import GrafoBipartito, Dibujo",
"from Dibujador import DibujadorGrafoBipartito",
"from sets import Set",
"class ParserDibujoIn:\n def __init__(self, archivo=\"Tp3.in\"):\n f = open(archivo, 'r')\n nf1 = int(f.readline())\n fijo1 = []\n nodos1 = []\n f... |
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.... |
from GrafoBipartito import *
from HeuristicaInsercionEjes import HeuristicaInsercionEjes
from BusquedaLocalReInsercion import *
from BusquedaLocalMix import *
from HeuristicaDeLaMediana import HeuristicaDeLaMediana
from BusquedaLocalMediana import BusquedaLocalMediana
from HeuristicaInsercionNodos import *
from SolucionSwapperPoda import ResolvedorSwapperConPoda
import psyco
psyco.full()
class GraspInsercionReInsercion (Grasp):
def resolver(self,dibujo):
marcados1 = dibujo.l1[:]
marcados2 = dibujo.l2[:]
print marcados1
print marcados2
losEjesDe = {}
for each in dibujo.g.p1 :
losEjesDe[each] = []
for each in dibujo.g.p2 :
losEjesDe[each] = []
for each in dibujo.g.ejes:
losEjesDe[each[0]].append(each[1])
losEjesDe[each[1]].append(each[0])
k = 0.3
print "antes de hacer nada hay", contadorDeCruces(marcados1 + [x for x in dibujo.g.p1 if x not in marcados1], marcados2 + [x for x in dibujo.g.p2 if x not in marcados2],losEjesDe)
mejorSol = HeuristicaInsercionNodos(dibujo).resolver()
blie = BusquedaLocalMediana()
blie.mejorar(mejorSol,marcados1,marcados2,losEjesDe)
mejoresCruces = contadorDeCruces(mejorSol.l1,mejorSol.l2,losEjesDe)
print "la solucion inicial tiene", mejoresCruces,"cruces"
sinMejorar = 0
while (sinMejorar < 100):
res = HeuristicaInsercionEjes(dibujo).resolver(alfa=k)
blie.mejorar(res,marcados1,marcados2,losEjesDe)
nuevosCruces = contadorDeCruces(res.l1,res.l2,losEjesDe)
print "en esta iteracion encontre uno de ",nuevosCruces,"cruces"
if nuevosCruces < mejoresCruces:
mejorSol = res
mejoresCruces = nuevosCruces
sinMejorar=0
print "mejore a una sol con: ", mejoresCruces
else:
sinMejorar +=1
DibujadorGrafoBipartito(mejorSol,marcados1=marcados1,marcados2=marcados2).grabar('grasp.svg')
print "lo mejor que encontre fue", mejoresCruces
print "solucion posta ",ResolvedorSwapperConPoda(dibujo).resolver()
return mejorSol
g = generarGrafoBipartitoAleatorio(15, 15, 30)
d = generarDibujoAleatorio(g,11, 11)
sol = GraspInsercionReInsercion().resolver(d)
| [
[
1,
0,
0.0189,
0.0189,
0,
0.66,
0,
16,
0,
1,
0,
0,
16,
0,
0
],
[
1,
0,
0.0377,
0.0189,
0,
0.66,
0.0769,
287,
0,
1,
0,
0,
287,
0,
0
],
[
1,
0,
0.0566,
0.0189,
0,
0.... | [
"from GrafoBipartito import *",
"from HeuristicaInsercionEjes import HeuristicaInsercionEjes",
"from BusquedaLocalReInsercion import *",
"from BusquedaLocalMix import *",
"from HeuristicaDeLaMediana import HeuristicaDeLaMediana",
"from BusquedaLocalMediana import BusquedaLocalMediana",
"from HeuristicaI... |
#!/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... |
#! /usr/bin/env python2.4
#
# Class for profiling python code. rev 1.0 6/2/94
#
# Based on prior profile module by Sjoerd Mullender...
# which was hacked somewhat by: Guido van Rossum
#
# See profile.doc for more information
"""Class for profiling Python code."""
# Copyright 1994, by InfoSeek Corporation, all rights reserved.
# Written by James Roskind
#
# Permission to use, copy, modify, and distribute this Python software
# and its associated documentation for any purpose (subject to the
# restriction in the following sentence) without fee is hereby granted,
# provided that the above copyright notice appears in all copies, and
# that both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of InfoSeek not be used in
# advertising or publicity pertaining to distribution of the software
# without specific, written prior permission. This permission is
# explicitly restricted to the copying and modification of the software
# to remain in Python, compiled Python, or other languages (such as C)
# wherein the modified or derived code is exclusively imported into a
# Python module.
#
# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import sys
import os
import time
import marshal
from optparse import OptionParser
__all__ = ["run", "runctx", "help", "Profile"]
# Sample timer for use with
#i_count = 0
#def integer_timer():
# global i_count
# i_count = i_count + 1
# return i_count
#itimes = integer_timer # replace with C coded timer returning integers
#**************************************************************************
# The following are the static member functions for the profiler class
# Note that an instance of Profile() is *not* needed to call them.
#**************************************************************************
def run(statement, filename=None, sort=-1):
"""Run statement under profiler optionally saving results in filename
This function takes a single argument that can be passed to the
"exec" statement, and an optional file name. In all cases this
routine attempts to "exec" its first argument and gather profiling
statistics from the execution. If no file name is present, then this
function automatically prints a simple profiling report, sorted by the
standard name string (file/line/function-name) that is presented in
each line.
"""
prof = Profile()
try:
prof = prof.run(statement)
except SystemExit:
pass
if filename is not None:
prof.dump_stats(filename)
else:
return prof.print_stats(sort)
def runctx(statement, globals, locals, filename=None):
"""Run statement under profiler, supplying your own globals and locals,
optionally saving results in filename.
statement and filename have the same semantics as profile.run
"""
prof = Profile()
try:
prof = prof.runctx(statement, globals, locals)
except SystemExit:
pass
if filename is not None:
prof.dump_stats(filename)
else:
return prof.print_stats()
# print help
def help():
for dirname in sys.path:
fullname = os.path.join(dirname, 'profile.doc')
if os.path.exists(fullname):
sts = os.system('${PAGER-more} ' + fullname)
if sts: print '*** Pager exit status:', sts
break
else:
print 'Sorry, can\'t find the help file "profile.doc"',
print 'along the Python search path.'
if os.name == "mac":
import MacOS
def _get_time_mac(timer=MacOS.GetTicks):
return timer() / 60.0
if hasattr(os, "times"):
def _get_time_times(timer=os.times):
t = timer()
return t[0] + t[1]
class Profile:
"""Profiler class.
self.cur is always a tuple. Each such tuple corresponds to a stack
frame that is currently active (self.cur[-2]). The following are the
definitions of its members. We use this external "parallel stack" to
avoid contaminating the program that we are profiling. (old profiler
used to write into the frames local dictionary!!) Derived classes
can change the definition of some entries, as long as they leave
[-2:] intact (frame and previous tuple). In case an internal error is
detected, the -3 element is used as the function name.
[ 0] = Time that needs to be charged to the parent frame's function.
It is used so that a function call will not have to access the
timing data for the parent frame.
[ 1] = Total time spent in this frame's function, excluding time in
subfunctions (this latter is tallied in cur[2]).
[ 2] = Total time spent in subfunctions, excluding time executing the
frame's function (this latter is tallied in cur[1]).
[-3] = Name of the function that corresponds to this frame.
[-2] = Actual frame that we correspond to (used to sync exception handling).
[-1] = Our parent 6-tuple (corresponds to frame.f_back).
Timing data for each function is stored as a 5-tuple in the dictionary
self.timings[]. The index is always the name stored in self.cur[-3].
The following are the definitions of the members:
[0] = The number of times this function was called, not counting direct
or indirect recursion,
[1] = Number of times this function appears on the stack, minus one
[2] = Total time spent internal to this function
[3] = Cumulative time that this function was present on the stack. In
non-recursive functions, this is the total execution time from start
to finish of each invocation of a function, including time spent in
all subfunctions.
[4] = A dictionary indicating for each function name, the number of times
it was called by us.
"""
bias = 0 # calibration constant
def __init__(self, timer=None, bias=None):
self.timings = {}
self.cur = None
self.cmd = ""
self.c_func_name = ""
if bias is None:
bias = self.bias
self.bias = bias # Materialize in local dict for lookup speed.
if timer is None:
if os.name == 'mac':
self.timer = MacOS.GetTicks
self.dispatcher = self.trace_dispatch_mac
self.get_time = _get_time_mac
elif hasattr(time, 'clock'):
self.timer = self.get_time = time.clock
self.dispatcher = self.trace_dispatch_i
elif hasattr(os, 'times'):
self.timer = os.times
self.dispatcher = self.trace_dispatch
self.get_time = _get_time_times
else:
self.timer = self.get_time = time.time
self.dispatcher = self.trace_dispatch_i
else:
self.timer = timer
t = self.timer() # test out timer function
try:
length = len(t)
except TypeError:
self.get_time = timer
self.dispatcher = self.trace_dispatch_i
else:
if length == 2:
self.dispatcher = self.trace_dispatch
else:
self.dispatcher = self.trace_dispatch_l
# This get_time() implementation needs to be defined
# here to capture the passed-in timer in the parameter
# list (for performance). Note that we can't assume
# the timer() result contains two values in all
# cases.
def get_time_timer(timer=timer, sum=sum):
return sum(timer())
self.get_time = get_time_timer
self.t = self.get_time()
self.simulate_call('profiler')
# Heavily optimized dispatch routine for os.times() timer
def trace_dispatch(self, frame, event, arg):
timer = self.timer
t = timer()
t = t[0] + t[1] - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame,t):
t = timer()
self.t = t[0] + t[1]
else:
r = timer()
self.t = r[0] + r[1] - t # put back unrecorded delta
# Dispatch routine for best timer program (return = scalar, fastest if
# an integer but float works too -- and time.clock() relies on that).
def trace_dispatch_i(self, frame, event, arg):
timer = self.timer
t = timer() - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame, t):
self.t = timer()
else:
self.t = timer() - t # put back unrecorded delta
# Dispatch routine for macintosh (timer returns time in ticks of
# 1/60th second)
def trace_dispatch_mac(self, frame, event, arg):
timer = self.timer
t = timer()/60.0 - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame, t):
self.t = timer()/60.0
else:
self.t = timer()/60.0 - t # put back unrecorded delta
# SLOW generic dispatch routine for timer returning lists of numbers
def trace_dispatch_l(self, frame, event, arg):
get_time = self.get_time
t = get_time() - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame, t):
self.t = get_time()
else:
self.t = get_time() - t # put back unrecorded delta
# In the event handlers, the first 3 elements of self.cur are unpacked
# into vrbls w/ 3-letter names. The last two characters are meant to be
# mnemonic:
# _pt self.cur[0] "parent time" time to be charged to parent frame
# _it self.cur[1] "internal time" time spent directly in the function
# _et self.cur[2] "external time" time spent in subfunctions
def trace_dispatch_exception(self, frame, t):
rpt, rit, ret, rfn, rframe, rcur = self.cur
if (rframe is not frame) and rcur:
return self.trace_dispatch_return(rframe, t)
self.cur = rpt, rit+t, ret, rfn, rframe, rcur
return 1
def trace_dispatch_call(self, frame, t):
if self.cur and frame.f_back is not self.cur[-2]:
rpt, rit, ret, rfn, rframe, rcur = self.cur
if not isinstance(rframe, Profile.fake_frame):
assert rframe.f_back is frame.f_back, ("Bad call", rfn,
rframe, rframe.f_back,
frame, frame.f_back)
self.trace_dispatch_return(rframe, 0)
assert (self.cur is None or \
frame.f_back is self.cur[-2]), ("Bad call",
self.cur[-3])
fcode = frame.f_code
fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name)
self.cur = (t, 0, 0, fn, frame, self.cur)
timings = self.timings
if fn in timings:
cc, ns, tt, ct, callers = timings[fn]
timings[fn] = cc, ns + 1, tt, ct, callers
else:
timings[fn] = 0, 0, 0, 0, {}
return 1
def trace_dispatch_c_call (self, frame, t):
fn = ("", 0, self.c_func_name)
self.cur = (t, 0, 0, fn, frame, self.cur)
timings = self.timings
if timings.has_key(fn):
cc, ns, tt, ct, callers = timings[fn]
timings[fn] = cc, ns+1, tt, ct, callers
else:
timings[fn] = 0, 0, 0, 0, {}
return 1
def trace_dispatch_return(self, frame, t):
if frame is not self.cur[-2]:
assert frame is self.cur[-2].f_back, ("Bad return", self.cur[-3])
self.trace_dispatch_return(self.cur[-2], 0)
# Prefix "r" means part of the Returning or exiting frame.
# Prefix "p" means part of the Previous or Parent or older frame.
rpt, rit, ret, rfn, frame, rcur = self.cur
rit = rit + t
frame_total = rit + ret
ppt, pit, pet, pfn, pframe, pcur = rcur
self.cur = ppt, pit + rpt, pet + frame_total, pfn, pframe, pcur
timings = self.timings
cc, ns, tt, ct, callers = timings[rfn]
if not ns:
# This is the only occurrence of the function on the stack.
# Else this is a (directly or indirectly) recursive call, and
# its cumulative time will get updated when the topmost call to
# it returns.
ct = ct + frame_total
cc = cc + 1
if pfn in callers:
callers[pfn] = callers[pfn] + 1 # hack: gather more
# stats such as the amount of time added to ct courtesy
# of this specific call, and the contribution to cc
# courtesy of this call.
else:
callers[pfn] = 1
timings[rfn] = cc, ns - 1, tt + rit, ct, callers
return 1
dispatch = {
"call": trace_dispatch_call,
"exception": trace_dispatch_exception,
"return": trace_dispatch_return,
"c_call": trace_dispatch_c_call,
"c_exception": trace_dispatch_return, # the C function returned
"c_return": trace_dispatch_return,
}
# The next few functions play with self.cmd. By carefully preloading
# our parallel stack, we can force the profiled result to include
# an arbitrary string as the name of the calling function.
# We use self.cmd as that string, and the resulting stats look
# very nice :-).
def set_cmd(self, cmd):
if self.cur[-1]: return # already set
self.cmd = cmd
self.simulate_call(cmd)
class fake_code:
def __init__(self, filename, line, name):
self.co_filename = filename
self.co_line = line
self.co_name = name
self.co_firstlineno = 0
def __repr__(self):
return repr((self.co_filename, self.co_line, self.co_name))
class fake_frame:
def __init__(self, code, prior):
self.f_code = code
self.f_back = prior
def simulate_call(self, name):
code = self.fake_code('profile', 0, name)
if self.cur:
pframe = self.cur[-2]
else:
pframe = None
frame = self.fake_frame(code, pframe)
self.dispatch['call'](self, frame, 0)
# collect stats from pending stack, including getting final
# timings for self.cmd frame.
def simulate_cmd_complete(self):
get_time = self.get_time
t = get_time() - self.t
while self.cur[-1]:
# We *can* cause assertion errors here if
# dispatch_trace_return checks for a frame match!
self.dispatch['return'](self, self.cur[-2], t)
t = 0
self.t = get_time() - t
def print_stats(self, sort=-1):
import pstats
pstats.Stats(self).strip_dirs().sort_stats(sort). \
print_stats()
def dump_stats(self, file):
f = open(file, 'wb')
self.create_stats()
marshal.dump(self.stats, f)
f.close()
def create_stats(self):
self.simulate_cmd_complete()
self.snapshot_stats()
def snapshot_stats(self):
self.stats = {}
for func, (cc, ns, tt, ct, callers) in self.timings.iteritems():
callers = callers.copy()
nc = 0
for callcnt in callers.itervalues():
nc += callcnt
self.stats[func] = cc, nc, tt, ct, callers
# The following two methods can be called by clients to use
# a profiler to profile a statement, given as a string.
def run(self, cmd):
import __main__
dict = __main__.__dict__
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
self.set_cmd(cmd)
sys.setprofile(self.dispatcher)
try:
exec cmd in globals, locals
finally:
sys.setprofile(None)
return self
# This method is more useful to profile a single function call.
def runcall(self, func, *args, **kw):
self.set_cmd(repr(func))
sys.setprofile(self.dispatcher)
try:
return func(*args, **kw)
finally:
sys.setprofile(None)
#******************************************************************
# The following calculates the overhead for using a profiler. The
# problem is that it takes a fair amount of time for the profiler
# to stop the stopwatch (from the time it receives an event).
# Similarly, there is a delay from the time that the profiler
# re-starts the stopwatch before the user's code really gets to
# continue. The following code tries to measure the difference on
# a per-event basis.
#
# Note that this difference is only significant if there are a lot of
# events, and relatively little user code per event. For example,
# code with small functions will typically benefit from having the
# profiler calibrated for the current platform. This *could* be
# done on the fly during init() time, but it is not worth the
# effort. Also note that if too large a value specified, then
# execution time on some functions will actually appear as a
# negative number. It is *normal* for some functions (with very
# low call counts) to have such negative stats, even if the
# calibration figure is "correct."
#
# One alternative to profile-time calibration adjustments (i.e.,
# adding in the magic little delta during each event) is to track
# more carefully the number of events (and cumulatively, the number
# of events during sub functions) that are seen. If this were
# done, then the arithmetic could be done after the fact (i.e., at
# display time). Currently, we track only call/return events.
# These values can be deduced by examining the callees and callers
# vectors for each functions. Hence we *can* almost correct the
# internal time figure at print time (note that we currently don't
# track exception event processing counts). Unfortunately, there
# is currently no similar information for cumulative sub-function
# time. It would not be hard to "get all this info" at profiler
# time. Specifically, we would have to extend the tuples to keep
# counts of this in each frame, and then extend the defs of timing
# tuples to include the significant two figures. I'm a bit fearful
# that this additional feature will slow the heavily optimized
# event/time ratio (i.e., the profiler would run slower, fur a very
# low "value added" feature.)
#**************************************************************
def calibrate(self, m, verbose=0):
if self.__class__ is not Profile:
raise TypeError("Subclasses must override .calibrate().")
saved_bias = self.bias
self.bias = 0
try:
return self._calibrate_inner(m, verbose)
finally:
self.bias = saved_bias
def _calibrate_inner(self, m, verbose):
get_time = self.get_time
# Set up a test case to be run with and without profiling. Include
# lots of calls, because we're trying to quantify stopwatch overhead.
# Do not raise any exceptions, though, because we want to know
# exactly how many profile events are generated (one call event, +
# one return event, per Python-level call).
def f1(n):
for i in range(n):
x = 1
def f(m, f1=f1):
for i in range(m):
f1(100)
f(m) # warm up the cache
# elapsed_noprofile <- time f(m) takes without profiling.
t0 = get_time()
f(m)
t1 = get_time()
elapsed_noprofile = t1 - t0
if verbose:
print "elapsed time without profiling =", elapsed_noprofile
# elapsed_profile <- time f(m) takes with profiling. The difference
# is profiling overhead, only some of which the profiler subtracts
# out on its own.
p = Profile()
t0 = get_time()
p.runctx('f(m)', globals(), locals())
t1 = get_time()
elapsed_profile = t1 - t0
if verbose:
print "elapsed time with profiling =", elapsed_profile
# reported_time <- "CPU seconds" the profiler charged to f and f1.
total_calls = 0.0
reported_time = 0.0
for (filename, line, funcname), (cc, ns, tt, ct, callers) in \
p.timings.items():
if funcname in ("f", "f1"):
total_calls += cc
reported_time += tt
if verbose:
print "'CPU seconds' profiler reported =", reported_time
print "total # calls =", total_calls
if total_calls != m + 1:
raise ValueError("internal error: total calls = %d" % total_calls)
# reported_time - elapsed_noprofile = overhead the profiler wasn't
# able to measure. Divide by twice the number of calls (since there
# are two profiler events per call in this test) to get the hidden
# overhead per event.
mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls
if verbose:
print "mean stopwatch overhead per profile event =", mean
return mean
#****************************************************************************
def Stats(*args):
print 'Report generating functions are in the "pstats" module\a'
# When invoked as main program, invoke the profiler on a script
if __name__ == '__main__':
usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
if not sys.argv[1:]:
print "Usage: ", usage
sys.exit(2)
class ProfileParser(OptionParser):
def __init__(self, usage):
OptionParser.__init__(self)
self.usage = usage
parser = ProfileParser(usage)
parser.allow_interspersed_args = False
parser.add_option('-o', '--outfile', dest="outfile",
help="Save stats to <outfile>", default=None)
parser.add_option('-s', '--sort', dest="sort",
help="Sort order when printing to stdout, based on pstats.Stats class", default=-1)
(options, args) = parser.parse_args()
sys.argv[:] = args
if (len(sys.argv) > 0):
sys.path.insert(0, os.path.dirname(sys.argv[0]))
run('execfile(%r)' % (sys.argv[0],), options.outfile, options.sort)
else:
print "Usage: ", usage
| [
[
8,
0,
0.0163,
0.0016,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0621,
0.0016,
0,
0.66,
0.0714,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0637,
0.0016,
0,
0.66... | [
"\"\"\"Class for profiling Python code.\"\"\"",
"import sys",
"import os",
"import time",
"import marshal",
"from optparse import OptionParser",
"__all__ = [\"run\", \"runctx\", \"help\", \"Profile\"]",
"def run(statement, filename=None, sort=-1):\n \"\"\"Run statement under profiler optionally sav... |
#! /usr/bin/env python2.4
#
# Class for profiling python code. rev 1.0 6/2/94
#
# Based on prior profile module by Sjoerd Mullender...
# which was hacked somewhat by: Guido van Rossum
#
# See profile.doc for more information
"""Class for profiling Python code."""
# Copyright 1994, by InfoSeek Corporation, all rights reserved.
# Written by James Roskind
#
# Permission to use, copy, modify, and distribute this Python software
# and its associated documentation for any purpose (subject to the
# restriction in the following sentence) without fee is hereby granted,
# provided that the above copyright notice appears in all copies, and
# that both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of InfoSeek not be used in
# advertising or publicity pertaining to distribution of the software
# without specific, written prior permission. This permission is
# explicitly restricted to the copying and modification of the software
# to remain in Python, compiled Python, or other languages (such as C)
# wherein the modified or derived code is exclusively imported into a
# Python module.
#
# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import sys
import os
import time
import marshal
from optparse import OptionParser
__all__ = ["run", "runctx", "help", "Profile"]
# Sample timer for use with
#i_count = 0
#def integer_timer():
# global i_count
# i_count = i_count + 1
# return i_count
#itimes = integer_timer # replace with C coded timer returning integers
#**************************************************************************
# The following are the static member functions for the profiler class
# Note that an instance of Profile() is *not* needed to call them.
#**************************************************************************
def run(statement, filename=None, sort=-1):
"""Run statement under profiler optionally saving results in filename
This function takes a single argument that can be passed to the
"exec" statement, and an optional file name. In all cases this
routine attempts to "exec" its first argument and gather profiling
statistics from the execution. If no file name is present, then this
function automatically prints a simple profiling report, sorted by the
standard name string (file/line/function-name) that is presented in
each line.
"""
prof = Profile()
try:
prof = prof.run(statement)
except SystemExit:
pass
if filename is not None:
prof.dump_stats(filename)
else:
return prof.print_stats(sort)
def runctx(statement, globals, locals, filename=None):
"""Run statement under profiler, supplying your own globals and locals,
optionally saving results in filename.
statement and filename have the same semantics as profile.run
"""
prof = Profile()
try:
prof = prof.runctx(statement, globals, locals)
except SystemExit:
pass
if filename is not None:
prof.dump_stats(filename)
else:
return prof.print_stats()
# print help
def help():
for dirname in sys.path:
fullname = os.path.join(dirname, 'profile.doc')
if os.path.exists(fullname):
sts = os.system('${PAGER-more} ' + fullname)
if sts: print '*** Pager exit status:', sts
break
else:
print 'Sorry, can\'t find the help file "profile.doc"',
print 'along the Python search path.'
if os.name == "mac":
import MacOS
def _get_time_mac(timer=MacOS.GetTicks):
return timer() / 60.0
if hasattr(os, "times"):
def _get_time_times(timer=os.times):
t = timer()
return t[0] + t[1]
class Profile:
"""Profiler class.
self.cur is always a tuple. Each such tuple corresponds to a stack
frame that is currently active (self.cur[-2]). The following are the
definitions of its members. We use this external "parallel stack" to
avoid contaminating the program that we are profiling. (old profiler
used to write into the frames local dictionary!!) Derived classes
can change the definition of some entries, as long as they leave
[-2:] intact (frame and previous tuple). In case an internal error is
detected, the -3 element is used as the function name.
[ 0] = Time that needs to be charged to the parent frame's function.
It is used so that a function call will not have to access the
timing data for the parent frame.
[ 1] = Total time spent in this frame's function, excluding time in
subfunctions (this latter is tallied in cur[2]).
[ 2] = Total time spent in subfunctions, excluding time executing the
frame's function (this latter is tallied in cur[1]).
[-3] = Name of the function that corresponds to this frame.
[-2] = Actual frame that we correspond to (used to sync exception handling).
[-1] = Our parent 6-tuple (corresponds to frame.f_back).
Timing data for each function is stored as a 5-tuple in the dictionary
self.timings[]. The index is always the name stored in self.cur[-3].
The following are the definitions of the members:
[0] = The number of times this function was called, not counting direct
or indirect recursion,
[1] = Number of times this function appears on the stack, minus one
[2] = Total time spent internal to this function
[3] = Cumulative time that this function was present on the stack. In
non-recursive functions, this is the total execution time from start
to finish of each invocation of a function, including time spent in
all subfunctions.
[4] = A dictionary indicating for each function name, the number of times
it was called by us.
"""
bias = 0 # calibration constant
def __init__(self, timer=None, bias=None):
self.timings = {}
self.cur = None
self.cmd = ""
self.c_func_name = ""
if bias is None:
bias = self.bias
self.bias = bias # Materialize in local dict for lookup speed.
if timer is None:
if os.name == 'mac':
self.timer = MacOS.GetTicks
self.dispatcher = self.trace_dispatch_mac
self.get_time = _get_time_mac
elif hasattr(time, 'clock'):
self.timer = self.get_time = time.clock
self.dispatcher = self.trace_dispatch_i
elif hasattr(os, 'times'):
self.timer = os.times
self.dispatcher = self.trace_dispatch
self.get_time = _get_time_times
else:
self.timer = self.get_time = time.time
self.dispatcher = self.trace_dispatch_i
else:
self.timer = timer
t = self.timer() # test out timer function
try:
length = len(t)
except TypeError:
self.get_time = timer
self.dispatcher = self.trace_dispatch_i
else:
if length == 2:
self.dispatcher = self.trace_dispatch
else:
self.dispatcher = self.trace_dispatch_l
# This get_time() implementation needs to be defined
# here to capture the passed-in timer in the parameter
# list (for performance). Note that we can't assume
# the timer() result contains two values in all
# cases.
def get_time_timer(timer=timer, sum=sum):
return sum(timer())
self.get_time = get_time_timer
self.t = self.get_time()
self.simulate_call('profiler')
# Heavily optimized dispatch routine for os.times() timer
def trace_dispatch(self, frame, event, arg):
timer = self.timer
t = timer()
t = t[0] + t[1] - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame,t):
t = timer()
self.t = t[0] + t[1]
else:
r = timer()
self.t = r[0] + r[1] - t # put back unrecorded delta
# Dispatch routine for best timer program (return = scalar, fastest if
# an integer but float works too -- and time.clock() relies on that).
def trace_dispatch_i(self, frame, event, arg):
timer = self.timer
t = timer() - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame, t):
self.t = timer()
else:
self.t = timer() - t # put back unrecorded delta
# Dispatch routine for macintosh (timer returns time in ticks of
# 1/60th second)
def trace_dispatch_mac(self, frame, event, arg):
timer = self.timer
t = timer()/60.0 - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame, t):
self.t = timer()/60.0
else:
self.t = timer()/60.0 - t # put back unrecorded delta
# SLOW generic dispatch routine for timer returning lists of numbers
def trace_dispatch_l(self, frame, event, arg):
get_time = self.get_time
t = get_time() - self.t - self.bias
if event == "c_call":
self.c_func_name = arg.__name__
if self.dispatch[event](self, frame, t):
self.t = get_time()
else:
self.t = get_time() - t # put back unrecorded delta
# In the event handlers, the first 3 elements of self.cur are unpacked
# into vrbls w/ 3-letter names. The last two characters are meant to be
# mnemonic:
# _pt self.cur[0] "parent time" time to be charged to parent frame
# _it self.cur[1] "internal time" time spent directly in the function
# _et self.cur[2] "external time" time spent in subfunctions
def trace_dispatch_exception(self, frame, t):
rpt, rit, ret, rfn, rframe, rcur = self.cur
if (rframe is not frame) and rcur:
return self.trace_dispatch_return(rframe, t)
self.cur = rpt, rit+t, ret, rfn, rframe, rcur
return 1
def trace_dispatch_call(self, frame, t):
if self.cur and frame.f_back is not self.cur[-2]:
rpt, rit, ret, rfn, rframe, rcur = self.cur
if not isinstance(rframe, Profile.fake_frame):
assert rframe.f_back is frame.f_back, ("Bad call", rfn,
rframe, rframe.f_back,
frame, frame.f_back)
self.trace_dispatch_return(rframe, 0)
assert (self.cur is None or \
frame.f_back is self.cur[-2]), ("Bad call",
self.cur[-3])
fcode = frame.f_code
fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name)
self.cur = (t, 0, 0, fn, frame, self.cur)
timings = self.timings
if fn in timings:
cc, ns, tt, ct, callers = timings[fn]
timings[fn] = cc, ns + 1, tt, ct, callers
else:
timings[fn] = 0, 0, 0, 0, {}
return 1
def trace_dispatch_c_call (self, frame, t):
fn = ("", 0, self.c_func_name)
self.cur = (t, 0, 0, fn, frame, self.cur)
timings = self.timings
if timings.has_key(fn):
cc, ns, tt, ct, callers = timings[fn]
timings[fn] = cc, ns+1, tt, ct, callers
else:
timings[fn] = 0, 0, 0, 0, {}
return 1
def trace_dispatch_return(self, frame, t):
if frame is not self.cur[-2]:
assert frame is self.cur[-2].f_back, ("Bad return", self.cur[-3])
self.trace_dispatch_return(self.cur[-2], 0)
# Prefix "r" means part of the Returning or exiting frame.
# Prefix "p" means part of the Previous or Parent or older frame.
rpt, rit, ret, rfn, frame, rcur = self.cur
rit = rit + t
frame_total = rit + ret
ppt, pit, pet, pfn, pframe, pcur = rcur
self.cur = ppt, pit + rpt, pet + frame_total, pfn, pframe, pcur
timings = self.timings
cc, ns, tt, ct, callers = timings[rfn]
if not ns:
# This is the only occurrence of the function on the stack.
# Else this is a (directly or indirectly) recursive call, and
# its cumulative time will get updated when the topmost call to
# it returns.
ct = ct + frame_total
cc = cc + 1
if pfn in callers:
callers[pfn] = callers[pfn] + 1 # hack: gather more
# stats such as the amount of time added to ct courtesy
# of this specific call, and the contribution to cc
# courtesy of this call.
else:
callers[pfn] = 1
timings[rfn] = cc, ns - 1, tt + rit, ct, callers
return 1
dispatch = {
"call": trace_dispatch_call,
"exception": trace_dispatch_exception,
"return": trace_dispatch_return,
"c_call": trace_dispatch_c_call,
"c_exception": trace_dispatch_return, # the C function returned
"c_return": trace_dispatch_return,
}
# The next few functions play with self.cmd. By carefully preloading
# our parallel stack, we can force the profiled result to include
# an arbitrary string as the name of the calling function.
# We use self.cmd as that string, and the resulting stats look
# very nice :-).
def set_cmd(self, cmd):
if self.cur[-1]: return # already set
self.cmd = cmd
self.simulate_call(cmd)
class fake_code:
def __init__(self, filename, line, name):
self.co_filename = filename
self.co_line = line
self.co_name = name
self.co_firstlineno = 0
def __repr__(self):
return repr((self.co_filename, self.co_line, self.co_name))
class fake_frame:
def __init__(self, code, prior):
self.f_code = code
self.f_back = prior
def simulate_call(self, name):
code = self.fake_code('profile', 0, name)
if self.cur:
pframe = self.cur[-2]
else:
pframe = None
frame = self.fake_frame(code, pframe)
self.dispatch['call'](self, frame, 0)
# collect stats from pending stack, including getting final
# timings for self.cmd frame.
def simulate_cmd_complete(self):
get_time = self.get_time
t = get_time() - self.t
while self.cur[-1]:
# We *can* cause assertion errors here if
# dispatch_trace_return checks for a frame match!
self.dispatch['return'](self, self.cur[-2], t)
t = 0
self.t = get_time() - t
def print_stats(self, sort=-1):
import pstats
pstats.Stats(self).strip_dirs().sort_stats(sort). \
print_stats()
def dump_stats(self, file):
f = open(file, 'wb')
self.create_stats()
marshal.dump(self.stats, f)
f.close()
def create_stats(self):
self.simulate_cmd_complete()
self.snapshot_stats()
def snapshot_stats(self):
self.stats = {}
for func, (cc, ns, tt, ct, callers) in self.timings.iteritems():
callers = callers.copy()
nc = 0
for callcnt in callers.itervalues():
nc += callcnt
self.stats[func] = cc, nc, tt, ct, callers
# The following two methods can be called by clients to use
# a profiler to profile a statement, given as a string.
def run(self, cmd):
import __main__
dict = __main__.__dict__
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
self.set_cmd(cmd)
sys.setprofile(self.dispatcher)
try:
exec cmd in globals, locals
finally:
sys.setprofile(None)
return self
# This method is more useful to profile a single function call.
def runcall(self, func, *args, **kw):
self.set_cmd(repr(func))
sys.setprofile(self.dispatcher)
try:
return func(*args, **kw)
finally:
sys.setprofile(None)
#******************************************************************
# The following calculates the overhead for using a profiler. The
# problem is that it takes a fair amount of time for the profiler
# to stop the stopwatch (from the time it receives an event).
# Similarly, there is a delay from the time that the profiler
# re-starts the stopwatch before the user's code really gets to
# continue. The following code tries to measure the difference on
# a per-event basis.
#
# Note that this difference is only significant if there are a lot of
# events, and relatively little user code per event. For example,
# code with small functions will typically benefit from having the
# profiler calibrated for the current platform. This *could* be
# done on the fly during init() time, but it is not worth the
# effort. Also note that if too large a value specified, then
# execution time on some functions will actually appear as a
# negative number. It is *normal* for some functions (with very
# low call counts) to have such negative stats, even if the
# calibration figure is "correct."
#
# One alternative to profile-time calibration adjustments (i.e.,
# adding in the magic little delta during each event) is to track
# more carefully the number of events (and cumulatively, the number
# of events during sub functions) that are seen. If this were
# done, then the arithmetic could be done after the fact (i.e., at
# display time). Currently, we track only call/return events.
# These values can be deduced by examining the callees and callers
# vectors for each functions. Hence we *can* almost correct the
# internal time figure at print time (note that we currently don't
# track exception event processing counts). Unfortunately, there
# is currently no similar information for cumulative sub-function
# time. It would not be hard to "get all this info" at profiler
# time. Specifically, we would have to extend the tuples to keep
# counts of this in each frame, and then extend the defs of timing
# tuples to include the significant two figures. I'm a bit fearful
# that this additional feature will slow the heavily optimized
# event/time ratio (i.e., the profiler would run slower, fur a very
# low "value added" feature.)
#**************************************************************
def calibrate(self, m, verbose=0):
if self.__class__ is not Profile:
raise TypeError("Subclasses must override .calibrate().")
saved_bias = self.bias
self.bias = 0
try:
return self._calibrate_inner(m, verbose)
finally:
self.bias = saved_bias
def _calibrate_inner(self, m, verbose):
get_time = self.get_time
# Set up a test case to be run with and without profiling. Include
# lots of calls, because we're trying to quantify stopwatch overhead.
# Do not raise any exceptions, though, because we want to know
# exactly how many profile events are generated (one call event, +
# one return event, per Python-level call).
def f1(n):
for i in range(n):
x = 1
def f(m, f1=f1):
for i in range(m):
f1(100)
f(m) # warm up the cache
# elapsed_noprofile <- time f(m) takes without profiling.
t0 = get_time()
f(m)
t1 = get_time()
elapsed_noprofile = t1 - t0
if verbose:
print "elapsed time without profiling =", elapsed_noprofile
# elapsed_profile <- time f(m) takes with profiling. The difference
# is profiling overhead, only some of which the profiler subtracts
# out on its own.
p = Profile()
t0 = get_time()
p.runctx('f(m)', globals(), locals())
t1 = get_time()
elapsed_profile = t1 - t0
if verbose:
print "elapsed time with profiling =", elapsed_profile
# reported_time <- "CPU seconds" the profiler charged to f and f1.
total_calls = 0.0
reported_time = 0.0
for (filename, line, funcname), (cc, ns, tt, ct, callers) in \
p.timings.items():
if funcname in ("f", "f1"):
total_calls += cc
reported_time += tt
if verbose:
print "'CPU seconds' profiler reported =", reported_time
print "total # calls =", total_calls
if total_calls != m + 1:
raise ValueError("internal error: total calls = %d" % total_calls)
# reported_time - elapsed_noprofile = overhead the profiler wasn't
# able to measure. Divide by twice the number of calls (since there
# are two profiler events per call in this test) to get the hidden
# overhead per event.
mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls
if verbose:
print "mean stopwatch overhead per profile event =", mean
return mean
#****************************************************************************
def Stats(*args):
print 'Report generating functions are in the "pstats" module\a'
# When invoked as main program, invoke the profiler on a script
if __name__ == '__main__':
usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
if not sys.argv[1:]:
print "Usage: ", usage
sys.exit(2)
class ProfileParser(OptionParser):
def __init__(self, usage):
OptionParser.__init__(self)
self.usage = usage
parser = ProfileParser(usage)
parser.allow_interspersed_args = False
parser.add_option('-o', '--outfile', dest="outfile",
help="Save stats to <outfile>", default=None)
parser.add_option('-s', '--sort', dest="sort",
help="Sort order when printing to stdout, based on pstats.Stats class", default=-1)
(options, args) = parser.parse_args()
sys.argv[:] = args
if (len(sys.argv) > 0):
sys.path.insert(0, os.path.dirname(sys.argv[0]))
run('execfile(%r)' % (sys.argv[0],), options.outfile, options.sort)
else:
print "Usage: ", usage
| [
[
8,
0,
0.0163,
0.0016,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0621,
0.0016,
0,
0.66,
0.0714,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0637,
0.0016,
0,
0.66... | [
"\"\"\"Class for profiling Python code.\"\"\"",
"import sys",
"import os",
"import time",
"import marshal",
"from optparse import OptionParser",
"__all__ = [\"run\", \"runctx\", \"help\", \"Profile\"]",
"def run(statement, filename=None, sort=-1):\n \"\"\"Run statement under profiler optionally sav... |
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... |
import random
from HeuristicaInsercionEjes import *
from HeuristicaInsercionNodos import *
from HeuristicaDeLaMediana import *
from SolucionSwapperTablaPoda import *
import psyco
from psyco import *
class Tp3:
def limpiarDibujo(self,d,losEjesDe):
g = d.g
marcados1 = d.l1
marcados2 = d.l2
print "marcados1",marcados1
print "marcados2",marcados2
marcadosNoNulos1 = [x for x in marcados1 if not len(losEjesDe[x]) == 0]
marcadosNoNulos2 = [x for x in marcados2 if not len(losEjesDe[x]) == 0]
nulos1=[]
noNulos1=[]
noNulos2=[]
nulos2=[]
for each in g.p1:
if each not in marcados1:
if len(losEjesDe[each]) == 0:
nulos1.append(each)
else:
noNulos1.append(each)
for each in g.p2:
if each not in marcados2:
if len(losEjesDe[each]) == 0:
nulos2.append(each)
else:
noNulos2.append(each)
self.traduccion = [0 for x in range(len(noNulos1)+ len(noNulos2)+len(marcadosNoNulos1)+ len(marcadosNoNulos2))]
i = 0
losEjesNuevos ={}
indice = [ 0 for x in range(len(g.p1)+len(g.p2))]
nuevoP1=[]
nuevoP2=[]
for each in marcadosNoNulos1:
losEjesNuevos[i]=[]
self.traduccion[i] = each
indice[each] = i
i = i +1
for each in marcadosNoNulos2:
losEjesNuevos[i]=[]
self.traduccion[i] = each
indice[each] = i
i = i +1
for each in noNulos1:
losEjesNuevos[i]=[]
self.traduccion[i] = each
indice[each] = i
i+=1
for each in noNulos2:
losEjesNuevos[i]=[]
self.traduccion[i] = each
indice[each] = i
i+=1
ejesNuevos = []
ejes = [] #esto es solo por el generador de python
for each in noNulos1+marcadosNoNulos1:
for y in losEjesDe[each]:
x=each
losEjesNuevos[indice[x]].append(indice[y])
ejes.append((indice[x],indice[y]))
losEjesNuevos[indice[y]].append(indice[x])
ejesNuevos.append((x,y))
cantV1 = len(marcadosNoNulos1)
cantIV1 = len(noNulos1)
cantV2 = len(marcadosNoNulos2)
cantIV2 = len(noNulos2)
grafo = GrafoBipartito(Set(range(cantV1)+range(cantV1+cantV2,cantV1+cantV2+cantIV1)),Set(range(cantV1,cantV1+cantV2)+range(cantV1+cantV2+cantIV1,cantV1+cantV2+cantIV1+cantIV2)),Set(ejes))
Dib = Dibujo(grafo,range(cantV1),range(cantV1,cantV1+cantV2))
self.indice=indice
self.marcados1 = marcados1
self.marcados2 = marcados2
self.noNulos1 = noNulos1
self.noNulos2 = noNulos2
self.g = g
self.nulos1 = nulos1
self.nulos2 = nulos2
self.marcadosNoNulos1 = marcadosNoNulos1
self.marcadosNoNulos2 = marcadosNoNulos2
return Dib
def reconstruirDibujo(self,d):
i = 0
marcados1=self.marcados1
traduccion = self.traduccion
marcados2=self.marcados2
p1Posta = []
for each in d.l1:
if traduccion[each] not in marcados1:
p1Posta.append(self.traduccion[each])
else:
while(i < len(marcados1) and marcados1[i] != traduccion[each]):
p1Posta.append(marcados1[i])
i+=1
i+=1
p1Posta.append(self.traduccion[each])
p1Posta.extend(self.nulos1)
p1Posta.extend(self.marcados1[i:])
p2Posta = []
i=0
for each in d.l2:
if traduccion[each] not in marcados2:
p2Posta.append(self.traduccion[each])
else:
while(i < len(marcados2) and marcados2[i] != traduccion[each]):
p2Posta.append(marcados2[i])
i+=1
i+=1
p2Posta.append(self.traduccion[each])
p2Posta.extend(self.nulos2)
p2Posta.extend(self.marcados2[i:])
return Dibujo(self.g,p1Posta,p2Posta)
g = generarGrafoBipartitoAleatorio(10, 7, 8)
d = generarDibujoAleatorio(g,5,4)
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])
tp3 = Tp3()
dibu = tp3.limpiarDibujo(d,losEjesDe)
print dibu.l1
res = HeuristicaInsercionNodos(tp3.limpiarDibujo(d,losEjesDe)).resolver()
print "ahhh",len(dibu.l2),len(dibu.g.p2)
print tp3.reconstruirDibujo(res)
| [
[
1,
0,
0.0068,
0.0068,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0136,
0.0068,
0,
0.66,
0.0526,
287,
0,
1,
0,
0,
287,
0,
0
],
[
1,
0,
0.0204,
0.0068,
0,
... | [
"import random",
"from HeuristicaInsercionEjes import *",
"from HeuristicaInsercionNodos import *",
"from HeuristicaDeLaMediana import *",
"from SolucionSwapperTablaPoda import *",
"import psyco",
"from psyco import *",
"class Tp3:\n def limpiarDibujo(self,d,losEjesDe):\n g = d.g\n ma... |
#!/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... |
#!/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 ###############... |
import random
moda=5
for i in range(1,1000):
x=[0]*i
y = random.sample( range(i), i/2+1)
for j in range(i):
if j in y:
x[j] = moda
else:
x[j] = random.randint(0,10)
print i
for each in range(i):
print x[each]," ",
print ""
print 0
| [
[
1,
0,
0.0625,
0.0625,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.125,
0.0625,
0,
0.66,
0.3333,
881,
1,
0,
0,
0,
0,
1,
0
],
[
6,
0,
0.5312,
0.75,
0,
0.66... | [
"import random",
"moda=5",
"for i in range(1,1000):\n x=[0]*i\n y = random.sample( range(i), i/2+1)\n for j in range(i):\n if j in y:\n x[j] = moda\n else:\n x[j] = random.randint(0,10)",
" x=[0]*i",
" y = random.sample( range(i), i/2+1)",
" for j in r... |
import random
for n in range(1,30):
print "Caso"
print n," ",
print 200
x=[[0,0] for i in range(n)]
for i in range(n-1):
x[i][0] = 1
x[i][1] = 1
print x[i][0], " ", x[i][1]
print 200," ",200
print "Fin"
| [
[
1,
0,
0.0833,
0.0833,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
6,
0,
0.5833,
0.75,
0,
0.66,
0.5,
773,
3,
0,
0,
0,
0,
0,
7
],
[
8,
1,
0.3333,
0.0833,
1,
0.39,
... | [
"import random",
"for n in range(1,30):\n\tprint(\"Caso\")\n\tprint(n,\" \",)\n\tprint(200)\n\tx=[[0,0] for i in range(n)]\n\tfor i in range(n-1):\n\t\tx[i][0] = 1\n\t\tx[i][1] = 1",
"\tprint(\"Caso\")",
"\tprint(n,\" \",)",
"\tprint(200)",
"\tx=[[0,0] for i in range(n)]",
"\tfor i in range(n-1):\n\t\tx... |
for i in range(10000000):
print i+2
print 0
| [
[
6,
0,
0.5,
0.6667,
0,
0.66,
0,
826,
3,
0,
0,
0,
0,
0,
2
],
[
8,
1,
0.6667,
0.3333,
1,
0.46,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
1,
0.3333,
0,
0.66,
1,
... | [
"for i in range(10000000):\n print(i+2)",
" print(i+2)",
"print(0)"
] |
from math import ceil, sqrt
class FabricaPrimos:
def __init__(self):
self.fab = FabricaCandidatos()
self.primosHastaAhora = []
def _esPrimo(self, n):
s = sqrt(n)
for each in self.primosHastaAhora:
if each > s:
return True
if n % each == 0:
return False
return True
def next(self):
cand = self.fab.next()
while not self._esPrimo(cand):
cand = self.fab.next()
self.primoActual = cand
self.primosHastaAhora.append(cand)
return self.primoActual
class FabricaCandidatos:
def __init__(self):
self.numeroActual = 1
# Optimizacion loca: los primos mayores que 5 son 6k+1 o 6k+5
# turno = 0 -> el siguiente candidato es 6 * k + 5
# turno = 1 -> el siguiente candidato es 6 * k + 1
self.turno = 0
self.k = 1
def next(self):
if self.numeroActual in [1,2]:
self.numeroActual = self.numeroActual + 1
elif self.numeroActual in [3,5]:
self.numeroActual = self.numeroActual + 2
else:
if self.turno == 0:
self.numeroActual = 6 * self.k + 5
self.k = self.k + 1
self.turno = 1
else:
self.numeroActual = 6 * self.k + 1
self.turno = 0
return self.numeroActual
def primoDeMayorPotencia(n):
assert(n > 1)
mejorPrimo = 1
mejorPotencia = 0
f = FabricaPrimos()
primoActual = f.next()
potenciaActual = 0
s = int(ceil(sqrt(n)))
while n != 1:
# si me paso de la raiz, pruebo con el numero
if primoActual > s:
primoActual = n
potenciaActual = 1
break
if n % primoActual == 0:
potenciaActual += 1
n = n / primoActual
else:
if potenciaActual >= mejorPotencia:
mejorPrimo = primoActual
mejorPotencia = potenciaActual
potenciaActual = 0
primoActual = f.next()
s = int(ceil(sqrt(n)))
if potenciaActual >= mejorPotencia:
mejorPrimo = primoActual
mejorPotencia = potenciaActual
return mejorPrimo, mejorPotencia
def primoDeMayorPotencia2(n):
assert(n > 1)
mejorPrimo = 1
mejorPotencia = 0
f = FabricaPrimos()
primoActual = f.next()
potenciaActual = 0
s = int(ceil(sqrt(n)))
while n != 1 and primoActual <= s:
if n % primoActual == 0:
potenciaActual += 1
n = n / primoActual
else:
if potenciaActual >= mejorPotencia:
mejorPrimo = primoActual
mejorPotencia = potenciaActual
potenciaActual = 0
primoActual = f.next()
s = int(ceil(sqrt(n)))
if primoActual > s:
primoActual = n
potenciaActual = 1
if potenciaActual >= mejorPotencia:
mejorPrimo = primoActual
mejorPotencia = potenciaActual
return mejorPrimo, mejorPotencia
if __name__ == '__main__':
for each in range(2, 10000):
if primoDeMayorPotencia(each) != primoDeMayorPotencia2(each):
print "no anda con n=%s" % each
#import sys
#print primoDeMayorPotencia(int(sys.argv[1]))
| [
[
1,
0,
0.0075,
0.0075,
0,
0.66,
0,
526,
0,
2,
0,
0,
526,
0,
0
],
[
3,
0,
0.109,
0.1805,
0,
0.66,
0.2,
61,
0,
3,
0,
0,
0,
0,
6
],
[
2,
1,
0.0376,
0.0226,
1,
0.96,
... | [
"from math import ceil, sqrt",
"class FabricaPrimos:\n def __init__(self):\n self.fab = FabricaCandidatos()\n self.primosHastaAhora = []\n\n def _esPrimo(self, n):\n s = sqrt(n)\n for each in self.primosHastaAhora:",
" def __init__(self):\n self.fab = FabricaCandidato... |
class Cosa:
def __init__(self, costo, valor):
self.costo = costo
self.valor = valor
def __repr__(self):
return "<Cosa de valor %s y peso %s>" % (self.valor, self.costo)
class Mochila:
def __init__(self, cosas, capacidad):
self.cosas = cosas
self.capacidad = capacidad
# Halla el valor maximo que se puede cargar con programacion dinamica.
def knapDinamico(m):
return knapDinAux(len(m.cosas), m.capacidad, m)
def knapDinAux(i,j,m):
if i == 0 or j == 0:
return 0
elif m.cosas[i-1].valor > j:
return knapDinAux(i-1, j, m)
else:
return max(knapDinAux(i-1,j,m), m.cosas[i-1].valor + knapDinAux(i-1, j-m.cosas[i-1].costo, m))
# Halla la combinacion de objetos que produce el mejor valor
# haciendo backtracking.
def knapBT(m):
return knapBTAux([], m.cosas, m.capacidad)
# FIXME: estas funciones se usan indiscriminadamente y provocan
# mucha repeticion de cuentas. Habria que crear una clase que wrapee
# la lista de candidatos que estoy usando y cachee el costo y valor
# asociados a la misma.
def costo(cand):
s = 0
for each in cand:
s += each.costo
return s
def valor(cand):
s = 0
for each in cand:
s += each.valor
return s
def knapBTAux(candActual, restantes, capacidad):
if restantes == []:
return candActual
else:
a = knapBTAux(candActual, restantes[1:], capacidad)
if costo(candActual) + restantes[0].costo <= capacidad:
b = knapBTAux(candActual + [restantes[0]], restantes[1:], capacidad)
if valor(b) > valor(a):
return b
return a
if __name__ == '__main__':
cosas = [Cosa(3,4),
Cosa(7,2),
Cosa(2,5),
Cosa(3,4),
Cosa(6,4)
]
m = Mochila(cosas, 10)
print "La mejor solucion es %s con un valor de %s." % (knapBT(m), knapDinamico(m))
| [
[
3,
0,
0.0556,
0.0972,
0,
0.66,
0,
435,
0,
2,
0,
0,
0,
0,
0
],
[
2,
1,
0.0417,
0.0417,
1,
0.84,
0,
555,
0,
3,
0,
0,
0,
0,
0
],
[
14,
2,
0.0417,
0.0139,
2,
0.07,
... | [
"class Cosa:\n def __init__(self, costo, valor):\n self.costo = costo\n self.valor = valor\n\n def __repr__(self):\n return \"<Cosa de valor %s y peso %s>\" % (self.valor, self.costo)",
" def __init__(self, costo, valor):\n self.costo = costo\n self.valor = valor",
" ... |
#PROCEDURE KESIMO3(VAR A:VECTOR;PRIM,ULT,K:CARDINAL):INTEGER;
#VAR I,D:CARDINAL; PM:INTEGER; (* PSEUDO_MEDIANA *)
#BEGIN
#IF PRIM<ULT THEN
#PM:=CASIMEDIANA(A,PRIM,ULT);
#PIVOTE2(A,PM,PRIM,ULT,I,D);
#IF (PRIM+K-1)<I THEN RETURN KESIMO3(A,PRIM,I-1,K) END;
#IF D<=(PRIM+K-1) THEN RETURN KESIMO3(A,D,ULT,K-D+PRIM) END;
#RETURN A[I]
#ELSE
#RETURN A[ULT]
#END
#END KESIMO3;
#ult es la ultima valida
def kesimo(a,prim,ult,k):
if prim < ult:
pm = casiMediana(a,prim,ult)
i=0
d=0
(i,d)=pivote(a,pm,prim,ult,i,d)
if prim+k < i:
return kesimo(a,prim,i-1,k)
if d <=prim+k:
return kesimo(a,d,ult,k-d+prim)
return a[i]
else:
return a[ult]
#PROCEDURE CasiMediana(VAR a:vector; prim,ult:CARDINAL):INTEGER;
#(* calcula una mediana aproximada del vector a[prim..ult] *)
#VAR n,i:CARDINAL; b:vector;
#BEGIN
#n:=ult-prim+1;
#IF n<=5 THEN
#RETURN Medianade5(a,prim,ult)
#END;
#n:=n DIV 5;
#FOR i:=1 TO n DO
#b[i]:=Medianade5(a,5*i-4+prim-1,5*i+prim-1)
#END;
#RETURN Kesimo3(b,1,n,(n+1)DIV 2)
#END CasiMediana
def casiMediana(a,prim,ult):
n = ult - prim
if n <= 5:
return medianaDe5(a,prim,ult)
n = n / 5
b=[0]*n
for i in range(n):
b[i] = medianaDe5(a,5*i+prim,5*i+prim+4)
return kesimo(b,0,n-1,(n+1)/2)
#PROCEDURE Medianade5(VAR a:vector; prim,ult:CARDINAL):INTEGER;
#(* calcula la mediana de un vector de hasta 5 elementos (es
#decir, ult<prim+5) *)
#VAR i,n:CARDINAL; b:vector; (* para no modificar el vector *)
#BEGIN
#n:=ult-prim+1; (* numero de elementos *)
#FOR i:=1 TO n DO
#b[i]:=a[prim+i-1]
#END;
#FOR i:=1 TO (n+1) DIV 2 DO
#Intercambia(b,i,PosMinimo(b,i,n))
#END;
#RETURN b[(n+1) DIV 2];
#END Medianade5;
def medianaDe5(a,prim,ult):
n = ult - prim + 1
b= [0] * n
for i in range(n):
b[i] = a[prim + i]
for i in range((n+1)/2):
aux = b[i]
pos = posMinimo(b,i,n-1)
b[i]=b[pos]
b[pos]=aux
return b[(n+1)/2]
def posMinimo(b,i,n):
pos = i
for j in range(i,n):
if b[j] < b[pos]:
pos = j
return pos
#PROCEDURE Pivote2(VAR a:vector; p:INTEGER; prim,ult:CARDINAL;
#VAR k,l:CARDINAL);
#(* permuta los elementos de a[prim..ult] y devuelve dos
#posiciones k,l tales que prim-1<=k<l<=ult+1, a[i]<p si
#prim<=i<=k, a[i]=p si k<i<l, y a[i]>p si l<=i<=ult, donde p es
#el pivote y aparece como argumento *)
#VAR m:CARDINAL;
#BEGIN
#k:=prim; l:=ult+1;
#(* primero buscamos l *)
#REPEAT INC(k) UNTIL (a[k]>p) OR (k>=ult);
#REPEAT DEC(l) UNTIL (a[l]<=p);
#WHILE k<l DO
#Intercambia(a,k,l);
#REPEAT INC(k) UNTIL (a[k]>p);
#REPEAT DEC(l) UNTIL (a[l]<=p)
#END;
#Intercambia(a,prim,l);
#INC(l); (* ya tenemos l *)
#(* ahora buscamos el valor de k *)
#k:=prim-1;
#m:=l;
#REPEAT INC(k) UNTIL (a[k]=p) OR (k>=l);
#REPEAT DEC(m) UNTIL (a[m]<>p) OR (m<prim);
#WHILE k<m DO
#Intercambia(a,k,m);
#REPEAT INC(k) UNTIL (a[k]=p);
#REPEAT DEC(m) UNTIL (a[m]<>p);
#END;
#END Pivote2;
def pivote(a,p,prim,ult,k,l):
k = prim+1
l=ult
while not(a[k]>p or k >=ult ):
k=k+1
while not(a[l] <= p):
l=l-1
aux=a[prim]
a[prim] = a[l]
a[l] = aux
l=l+1
k = prim
m = l-1
while not(a[k] == p or k >= 1):
k=k+1
while not(a[m] != p or m<prim):
m=m-1
while k< m:
aux = a[k]
a[k] = a[m]
a[m] = aux
k=k+1
m=m-1
while not(a[k] == p):
k=k+1
while not(a[m] != p):
m=m-1
return (k,l)
a=[9]*44+[999]*100+[7,6]+[4]*15+[999]*10000+[500]*40+[200]*30+[1,2]*2800+[2,1]*100000+[8]*100000000
print kesimo(a,0,len(a)-1,len(a)/2)
| [
[
2,
0,
0.1438,
0.085,
0,
0.66,
0,
393,
0,
4,
1,
0,
0,
0,
4
],
[
4,
1,
0.1471,
0.0784,
1,
0.08,
0,
0,
0,
0,
0,
0,
0,
0,
4
],
[
14,
2,
0.1176,
0.0065,
2,
0.45,
0... | [
"def kesimo(a,prim,ult,k):\n if prim < ult:\n pm = casiMediana(a,prim,ult)\n i=0\n d=0\n (i,d)=pivote(a,pm,prim,ult,i,d)\n if prim+k < i:\n return kesimo(a,prim,i-1,k)",
" if prim < ult:\n pm = casiMediana(a,prim,ult)\n... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for data_structure.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of data_structure.
"""
import unittest
class UnionFindSet:
def __init__(self, n):
self.n = self.n
self.parent = [x for x in xrnage(n)]
self.rank = [0] * n
self.size = [1] * n
def find(self, x):
rootX = x
while rootX != self.parent[rootX]:
rootX = self.parent[rootX]
while x != self.parent[x]:
nextX = self.parent[x]
self.parent[x] = rootX
x = nextX
return rootX
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if self.rank[x] > self.rank[y]:
self.parent[y] = x
self.size[x] += self.size[y]
else:
self.parent[x] = y
self.size[y] += self.size[x]
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
def size(self, x):
return self.size[self.parent[x]]
class TrieNode:
def __init__(self, char):
self.char = char
self.children = {}
self.isLeaf = False
class Trie:
def __init__(self):
self.root = TrieNode('')
"""
Insert a word into Trie, return True is new word inserted.
"""
def insert(self, word):
node = self.root
for index, char in enumerate(word):
if char not in node.children:
node.children[char] = TrieNode(char)
node = node.children[char]
if node.isLeaf:
return False
else:
node.isLeaf = True
return True
"""
A degenerate segment tree like structure that use for count point in a interval
"""
class TreeArray:
"""
Init a tree arary for interval [0, n)
"""
def __init__(self, n):
self.n = n
self.array = [0] * self.n * 2 #allocate twice space
"""
The lowest '1' bit of x in binary base
"""
def lowBit(self, x):
return x & (x ^ (x - 1))
"""
Insert points (count = value) at x.
"""
def add(self, x, value):
while x <= self.n:
self.array[x] += value
x += self.lowBit(x)
"""
Return the totals numer of points in [0, x]
"""
def sum(self, x):
result = 0
while x > 0:
result += self.array[x]
x -= self.lowBit(x)
return result
class Test(unittest.TestCase):
def setUp(self):
pass
def testTrie(self):
trie = Trie()
self.assertEquals(True, trie.insert('gnefihz'))
self.assertEquals(True, trie.insert('gnefih'))
self.assertEquals(True, trie.insert('fengyu'))
self.assertEquals(True, trie.insert('feng'))
self.assertEquals(True, trie.insert('xxx'))
self.assertEquals(False, trie.insert('feng'))
self.assertEquals(False, trie.insert('gnefihz'))
self.assertEquals(False, trie.insert('xxx'))
def testTreeArray(self):
treeArray = TreeArray(100)
treeArray.add(3, 10)
treeArray.add(100, 10)
treeArray.add(34, 10)
treeArray.add(64, 10)
treeArray.add(1, 10)
self.assertEquals(10 * 3, treeArray.sum(50))
self.assertEquals(10 * 5, treeArray.sum(100))
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0189,
0.0303,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0455,
0.0076,
0,
0.66,
0.125,
88,
0,
1,
0,
0,
88,
0,
0
],
[
3,
0,
0.1818,
0.25,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for data_structure.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of data_structure.\n\"\"\"",
"import unittest",
"class UnionFindSet:\n def __init__(self, n):\n self.n = self.n\n self.parent = [x for x in xrnage(n)]\n ... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for HuffmanCode.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of HuffmanCode.
"""
import unittest
from heapq import *
class HuffmanCodeNode:
def __init__(self, code, weight):
self.code = code
self.weight = weight
self.leftChild = None
self.rightChild = None
def __cmp__(self, other):
return self.weight - other.weight
def CreateHuffmanTree(codes, weights):
nodeCount = len(codes)
assert(nodeCount == len(weights))
assert(nodeCount > 1)
heap = []
for idx, code in enumerate(codes):
heappush(heap, HuffmanCodeNode(code, weights[idx]))
while len(heap) > 1:
node1 = heappop(heap)
node2 = heappop(heap)
inNode = HuffmanCodeNode(None, node1.weight + node2.weight)
inNode.leftChild = node1
inNode.rightChild = node2
heappush(heap, inNode)
return heappop(heap)
def listCode(rootNode, code=""):
if not rootNode.leftChild and not rootNode.rightChild:
print(rootNode.code, code)
if rootNode.leftChild:
listCode(rootNode.leftChild, code + '0')
if rootNode.rightChild:
listCode(rootNode.rightChild, code + '1')
def decode(currentNode, code):
for char in code:
if char == '0' and currentNode.leftChild:
currentNode = currentNode.leftChild
elif char == '1' and currentNode.rightChild:
currentNode = currentNode.rightChild
else:
return None
return currentNode.code
class Test(unittest.TestCase):
def setUp(self):
pass
def testHuffmanCode(self):
rootNode = CreateHuffmanTree(
['b','p','`','m','o','d','j','a','i','r','u','l','s','e',' '],
[1,1,2,2,3,3,3,4,4,5,5,6,6,8,12])
listCode(rootNode)
self.assertEquals('l', decode(rootNode, '1111'))
self.assertEquals('b', decode(rootNode, '100010'))
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0362,
0.058,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.087,
0.0145,
0,
0.66,
0.125,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.1014,
0.0145,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for HuffmanCode.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of HuffmanCode.\n\"\"\"",
"import unittest",
"from heapq import *",
"class HuffmanCodeNode:\n def __init__(self, code, weight):\n self.code = code\n self.we... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for data_structure.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of data_structure.
"""
import unittest
"""
General Segment Tree for interval statistics.
"""
class SegmentTreeNode:
def __init__(self, begin, end):
self.begin = begin
self.end = end
self.count = 0
self.left = None
self.right = None
self.m = 0
self.leftBound = 0
self.rightBound = 0
self.line = 0
def isLeaf(self):
return self.end - self.begin == 1
def middle(self):
return (self.begin + self.end) / 2
class SegmentTree:
"""
Create a new interval [begin, end)
"""
def __init__(self, begin, end):
self.root = self.build(begin, end)
def build(self, begin, end):
parent = SegmentTreeNode(begin, end)
if end - begin > 1:
middle = (begin + end) / 2
parent.left = self.build(begin, middle)
parent.right = self.build(middle, end)
return parent
"""
[x, y) += value
"""
def update(self, x, y, value=1, node=None):
if node == None:
node = self.root
# node in [x, y)
if x <= node.begin and node.end <= y:
node.count += value
elif not node.isLeaf():
middle = (node.begin + node.end) / 2
if x < middle:
self.update(x, y, value, node.left)
if middle < y:
self.update(x, y, value, node.right)
self.updateM(node)
self.updateLines(node)
"""
How many points is cover in the interval
"""
def updateM(self, node):
if node.count > 0:
node.m = node.end - node.begin
elif node.isLeaf():
node.m = 0
else:
node.m = node.left.m + node.right.m
"""
Number of lines in the interval
"""
def updateLines(self, node):
if node.count > 0:
node.leftBound = node.rightBound = node.line = 1
elif node.isLeaf():
node.leftBound = node.rightBound = 0
else:
node.leftBound = node.left.leftBound
node.rightBound = node.right.rightBound
node.line = node.left.line + node.right.line - (node.left.rightBound * node.right.leftBound)
def query(self, point, node=None):
if node == None:
node = self.root
if point < node.begin or point >= node.end:
return 0
value = node.count
if node.isLeaf():
return node.count
middle = node.middle()
if point < middle:
value += self.query(point, node.left)
elif point >= middle:
value += self.query(point, node.right)
return value
class Test(unittest.TestCase):
def setUp(self):
pass
def testSegmentTree(self):
segmentTree = SegmentTree(0, 10)
segmentTree.update(2, 7)
self.assertEquals(5, segmentTree.root.m)
segmentTree.update(3, 5)
self.assertEquals(1, segmentTree.root.line)
segmentTree.update(4, 7)
segmentTree.update(0, 10)
segmentTree.update(6, 9)
self.assertEquals(1, segmentTree.query(0))
self.assertEquals(1, segmentTree.query(1))
self.assertEquals(2, segmentTree.query(2))
self.assertEquals(3, segmentTree.query(3))
self.assertEquals(4, segmentTree.query(4))
self.assertEquals(3, segmentTree.query(5))
self.assertEquals(4, segmentTree.query(6))
self.assertEquals(2, segmentTree.query(7))
self.assertEquals(2, segmentTree.query(8))
self.assertEquals(1, segmentTree.query(9))
self.assertEquals(0, segmentTree.query(10))
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0191,
0.0305,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0458,
0.0076,
0,
0.66,
0.1667,
88,
0,
1,
0,
0,
88,
0,
0
],
[
8,
0,
0.0687,
0.0229,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for data_structure.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of data_structure.\n\"\"\"",
"import unittest",
"\"\"\"\nGeneral Segment Tree for interval statistics.\n\"\"\"",
"class SegmentTreeNode:\n def __init__(self, b... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for BST.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of BST.
"""
import unittest
"""
Binary search tree without using recursion
"""
class BST:
class Node:
def __init__(self, key, parent=None, left=None, right=None):
self.key = key
self.left = left
self.right = right
self.parent = parent
def __init__(self):
self.root = None
def insert(self, key):
node = self.root
if node is None:
self.root = self.Node(key)
return
while node and node.left and key < node.key:
node = node.left
while node and node.right and key > node.key:
node = node.right
newNode = self.Node(key, node)
if key < node.key:
node.left = newNode
elif key > node.key:
node.right = newNode
else: #a duplicated root
pass
def remove(self, key):
node = self.search(key)
if node is None:
return False
# perform a remove at a incompleted node
if not (node.left and node.right):
inCompletedNode = node
else:
# find a incompleted node to replace the current node
inCompletedNode = self.successor(node)
node.key = inCompletedNode.key
# find the single child of the incompleted node
if inCompletedNode.left:
singleChildNode = inCompletedNode.left
else:
singleChildNode = inCompletedNode.right
# link the single child to incompleted node's parent
if singleChildNode:
singleChildNode.parent = inCompletedNode.parent
if inCompletedNode.parent is None:
self.root = singleChildNode
elif inCompletedNode == inCompletedNode.parent.left:
inCompletedNode.parent.left = singleChildNode
else:
inCompletedNode.parent.right = singleChildNode
return True
def _walk(self,
preOrderFunc=None, inOrderFunc=None, postOrderFunc=None, node=None):
if node is None:
node = self.root
preOrderFunc and preOrderFunc(node)
if node.left:
self._walk(preOrderFunc, inOrderFunc, postOrderFunc, node.left)
inOrderFunc and inOrderFunc(node)
if node.right:
self._walk(preOrderFunc, inOrderFunc, postOrderFunc, node.right)
postOrderFunc and postOrderFunc(node)
def search(self, key, node=None):
if node is None:
node = self.root
if node.key == key:
return node
if node.left and key < node.key:
return self.search(key, node.left)
elif node.right and key > node.key:
return self.search(key, node.right)
return None
def min(self, node=None):
if node is None:
node = self.root
while node and (not node.left is None):
node = node.left
return node
def max(self):
node = self.root
while node and (not node.right is None):
node = node.right
return node
def successor(self, node):
if node.right:
return self.min(node.right)
parentNode = node.parent
while parentNode and parentNode.right == node:
node = parentNode
parentNode = parentNode.parent
return parentNode
def predecsessor(self, node):
if node.left:
return self.max(node.left)
parentNode = node.parent
while parentNode and parentNode.left == node:
node = parentNode
parentNode = parentNode.parent
return parentNode
class Test(unittest.TestCase):
def setUp(self):
pass
def testBST(self):
bst = BST()
"""
5 -> 8 -> 10
-> 9
-> 7
-> 1 -> 4
-> 3
-> 0
pre:5 1 0 4 3 8 7 10 9
in:0 1 3 4 5 7 8 9 10
post:0 3 4 1 7 9 10 8 5
"""
bst.insert(5)
bst.insert(8)
bst.insert(10)
bst.insert(9)
bst.insert(7)
bst.insert(1)
bst.insert(0)
bst.insert(4)
bst.insert(3)
class Recorder:
def __init__(self):
self.path = []
def __call__(self, node):
self.path.append(node.key)
preFunc = Recorder()
inFunc = Recorder()
postFunc = Recorder()
bst._walk(preFunc, inFunc, postFunc)
self.assertEquals([5,1,0,4,3,8,7,10,9], preFunc.path)
self.assertEquals([0,1,3,4,5,7,8,9, 10], inFunc.path)
self.assertEquals([0,3,4,1,7,9,10,8,5], postFunc.path)
self.assertEquals(0, bst.min().key)
self.assertEquals(10, bst.max().key)
self.assertEquals(None, bst.search(11))
self.assertEquals(8, bst.successor(bst.search(7)).key)
"""
After remove
5 -> 9 -> 10
-> 7
-> 1 -> 3
-> 0
"""
bst.remove(8)
bst.remove(4)
preFunc = Recorder()
inFunc = Recorder()
postFunc = Recorder()
bst._walk(preFunc, inFunc, postFunc)
self.assertEquals([5,1,0,3,9,7,10], preFunc.path)
self.assertEquals([0,1,3,5,7,9,10], inFunc.path)
self.assertEquals([0,3,1,7,10,9,5], postFunc.path)
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0132,
0.0211,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0263,
0.0053,
0,
0.66,
0.2,
88,
0,
1,
0,
0,
88,
0,
0
],
[
8,
0,
0.0474,
0.0158,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for BST.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of BST.\n\"\"\"",
"import unittest",
"\"\"\"\nBinary search tree without using recursion\n\"\"\"",
"class BST:\n class Node:\n def __init__(self, key, parent=None, lef... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for DFS.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of DFS.
"""
import unittest
"""
A general back tracking search
"""
def backTracking(problem, candidate=None):
if candidate is None:
candidate = problem.getRoot()
if problem.accept(candidate):
problem.record(candidate)
return
extendCandidate = problem.fristExtend(candidate)
while not extendCandidate is None:
if not (problem.reject(extendCandidate) or
problem.underBound(extendCandidate)):
backTracking(problem, extendCandidate)
extendCandidate = problem.nextExtent(extendCandidate)
class MaxLoadingProblem:
class MaxLoadingProblemCandidate:
def __init__(self, selected, remainWeight):
self.selected = selected
self.currentWeight = 0
self.pendingIndex = 0
self.remainWeight = remainWeight
def __repr__(self):
return self.selected.__repr__()
def __init__(self, weights, maxWeight):
self.maxWeight = maxWeight
self.weights = weights
self.n = len(weights)
self.bestWeight = 0
self.bestSolution = None
def getRoot(self):
return self.MaxLoadingProblemCandidate([0] * self.n, sum(self.weights))
def reject(self, candidate):
return candidate.currentWeight > self.maxWeight
def underBound(self, candidate):
candidate.currentWeight + candidate.remainWeight < self.bestWeight
def accept(self, candidate):
return candidate.pendingIndex >= self.n
def record(self, candidate):
if candidate.currentWeight > self.bestWeight:
self.bestWeight = candidate.currentWeight
self.bestSolution = list(candidate.selected)
def fristExtend(self, candidate):
candidate.remainWeight -= self.weights[candidate.pendingIndex]
candidate.pendingIndex += 1
return candidate
def nextExtent(self, candidate):
if candidate.selected[candidate.pendingIndex - 1] == 0:
candidate.selected[candidate.pendingIndex - 1] = 1
candidate.currentWeight += self.weights[candidate.pendingIndex - 1]
return candidate
else:
candidate.pendingIndex -= 1
candidate.selected[candidate.pendingIndex] = 0
candidate.currentWeight -= self.weights[candidate.pendingIndex]
candidate.remainWeight += self.weights[candidate.pendingIndex]
return None
class Test(unittest.TestCase):
def setUp(self):
pass
def testMaxLoading(self):
problem = MaxLoadingProblem([0,1,2,3,4,5], 11)
backTracking(problem)
self.assertEquals(11, problem.bestWeight)
self.assertEquals([0,0,1,0,1,1], problem.bestSolution)
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0281,
0.0449,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0674,
0.0112,
0,
0.66,
0.1667,
88,
0,
1,
0,
0,
88,
0,
0
],
[
8,
0,
0.1011,
0.0337,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for DFS.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of DFS.\n\"\"\"",
"import unittest",
"\"\"\"\nA general back tracking search\n\"\"\"",
"def backTracking(problem, candidate=None):\n if candidate is None:\n candidate ... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for knapsack.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of knapsack.
"""
import unittest
"""
A dynamic programing to solve 0/1 knapsack problem
dp[itemIndex][capability] =
if itemIndex == n:
values[itemIndex] | 0 (capability > weights[itemIndex] ?)
else:
max( dp[itemIndex + 1][capability],
dp[itemIndex + 1][capability - weights[itemIndex]] + values[itemIndex] | 0
(capability > weight[itemIndex] ?)
)
"""
def knapsackDp(weights, values, capability):
n = len(weights)
assert(len(weights) == len(values))
dpArray2D = [ [0 for x in xrange(capability + 1)] for y in xrange(n)]
#dp[n-1][weights[n-1]..capability] = values[n-1]
index = n - 1
if weights[index] <= capability:
dpArray2D[index][weights[index]:] = \
[values[index]] * (capability + 1 - weights[index])
for index in xrange(n - 2, -1, -1):
dpArray2D[index][:weights[index]] = dpArray2D[index + 1][:weights[index]]
for x in xrange(weights[index], capability + 1):
dpArray2D[index][x] = max(dpArray2D[index + 1][x],
dpArray2D[index + 1][x - weights[index]] + values[index])
solution = [0] * n
totalValue = dpArray2D[0][capability]
for x in xrange(n - 1):
if dpArray2D[x][capability] == dpArray2D[x + 1][capability]:
solution[x] = 0
else:
solution[x] = 1
capability -= weights[x]
solution[n - 1] = dpArray2D[n - 1][capability] > 0 and 1 or 0
return totalValue, solution
"""
A general back tracking search
"""
def backTracking(problem, candidate=None):
if candidate is None:
candidate = problem.getRoot()
if problem.accept(candidate):
problem.record(candidate)
return
extendCandidate = problem.fristExtend(candidate)
while not extendCandidate is None:
if not (problem.reject(extendCandidate) or
problem.underBound(extendCandidate)):
backTracking(problem, extendCandidate)
extendCandidate = problem.nextExtent(extendCandidate)
"""
Knapsack problem using backtracking
"""
class KnapsackProblem:
class KnapsackProblemCandidate:
def __init__(self, selected, remainValue):
self.selected = selected
self.currentWeight = 0
self.currentValue = 0
self.pendingIndex = 0
self.remainValue = remainValue
def __repr__(self):
return self.selected.__repr__()
class Item:
def __init__(self, weight, value):
self.weight = weight
self.value = value
def __cmp__(self, other):
valueSelf = self.value // self.weight
valueOther = other.value // other.weight
if valueSelf < valueOther:
return -1
else:
return 1
def __init__(self, weights, values, capability):
self.weights = weights
self.values = values
self.n = len(weights)
items = []
for x in xrange(self.n):
item = self.Item(weights[x], values[x])
items.append(item)
self.items = sorted(items)
self.capability = capability
self.bestValue = 0
self.bestSolution = None
def getRoot(self):
return self.KnapsackProblemCandidate([0] * self.n, sum(self.values))
def reject(self, candidate):
return candidate.currentWeight > self.capability
def underBound(self, candidate):
candidate.currentValue + candidate.remainValue < self.bestValue
def accept(self, candidate):
return candidate.pendingIndex >= self.n
def record(self, candidate):
if candidate.currentValue > self.bestValue:
self.bestValue = candidate.currentValue
self.bestSolution = list(candidate.selected)
def fristExtend(self, candidate):
candidate.remainValue -= self.values[candidate.pendingIndex]
candidate.pendingIndex += 1
return candidate
def nextExtent(self, candidate):
if candidate.selected[candidate.pendingIndex - 1] == 0:
candidate.selected[candidate.pendingIndex - 1] = 1
candidate.currentWeight += self.weights[candidate.pendingIndex - 1]
candidate.currentValue += self.values[candidate.pendingIndex - 1]
return candidate
else:
candidate.pendingIndex -= 1
candidate.selected[candidate.pendingIndex] = 0
candidate.currentWeight -= self.weights[candidate.pendingIndex]
candidate.currentValue -= self.values[candidate.pendingIndex]
candidate.remainValue += self.values[candidate.pendingIndex]
return None
class Test(unittest.TestCase):
def setUp(self):
pass
def testKnapsackDp(self):
self.assertEquals(27, knapsackDp([1,2,1,3,2], [7,8,6,5,6], 6)[0]);
self.assertEquals([1,1,1,0,1], knapsackDp([1,2,1,3,2], [7,8,6,5,6], 6)[1]);
self.assertEquals(21, knapsackDp([1,2,1,3,2], [7,8,6,5,6], 5)[0]);
self.assertEquals(21, knapsackDp([1,2,1,3,2], [7,8,6,5,6], 4)[0]);
self.assertEquals(15, knapsackDp([1,2,1,3,2], [7,8,6,5,6], 3)[0]);
self.assertEquals(13, knapsackDp([1,2,1,3,2], [7,8,6,5,6], 2)[0]);
self.assertEquals(7, knapsackDp([1,2,1,3,2], [7,8,6,5,6], 1)[0]);
self.assertEquals(0, knapsackDp([1,2,1,3,2], [7,8,6,5,6], 0)[0]);
problem = KnapsackProblem([1,2,1,3,2], [7,8,6,5,6], 6)
backTracking(problem)
self.assertEquals(27, problem.bestValue)
self.assertEquals([1,1,1,0,1], problem.bestSolution)
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0152,
0.0244,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0305,
0.0061,
0,
0.66,
0.1111,
88,
0,
1,
0,
0,
88,
0,
0
],
[
8,
0,
0.0793,
0.0671,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for knapsack.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of knapsack.\n\"\"\"",
"import unittest",
"\"\"\"\nA dynamic programing to solve 0/1 knapsack problem\ndp[itemIndex][capability] =\n if itemIndex == n:\n values[i... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for search.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of search.
"""
import unittest
from heapq import heappop, heappush
"""
Genernal Breath first search
"""
def BFS(startState, terminateState):
if startState == terminateState:
return 0, []
opened = [startState]
cost = {}
cost[startState] = 0
while len(opened) > 0:
current = opened.pop(0)
for nextState in current.getNexts():
if nextState not in cost:
cost[nextState] = cost[current] + 1
nextState.fromState = current
if nextState == terminateState:
return cost[nextState], nextState.getPath()
opened.append(nextState)
return -1, []
"""
General a star search
"""
def AStar(startState, terminateState):
if startState == terminateState:
return 0, []
opened = []
heappush(opened, (0, startState))
cost = {}
cost[startState] = 0
while len(opened) > 0:
h, current = heappop(opened)
#print current
if current.g > cost[current]: # have visit with a low past cost
continue
for nextState in current.getNexts():
g = cost[current] + 1
if nextState not in cost or g < cost[nextState]:
cost[nextState] = g
nextState.g = g
nextState.fromState = current
if nextState == terminateState:
return g, nextState.getPath()
heappush(opened, (nextState.heuristicCostEstimate(), nextState))
return -1, []
"""
General iterative depening depth first search
"""
def IDA(startState, terminateState, protectDeep=32):
if startState == terminateState:
return 0, []
maxDeep = startState.heuristicEstimate()
while maxDeep < protectDeep:
cost = {}
cost[startState] = 0
opened = [startState]
while len(opened) > 0:
current = opened.pop()
for nextState in current.getNexts():
g = cost[current] + 1
if (nextState not in cost or g < cost[nextState]) and \
g + nextState.heuristicEstimate() <= maxDeep:
cost[nextState] = g
nextState.fromState = current
if nextState == terminateState:
return cost[nextState], nextState.getPath()
opened.append(nextState)
maxDeep += 1
return -1, []
"""
State represent for eight digits.
"""
class State:
def __init__(self, sequence):
assert(len(sequence) == 9)
self.sequence = sequence
self.g = 0
self.fromState = None
def Hamilton(self, a, b):
return abs(a/3 - b/3) + abs(a%3 - b%3)
def heuristicEstimate(self):
value = 0
targetPosision = [8, 0, 1, 2, 3, 4, 5, 6, 7]
for index, x in enumerate(self.sequence):
value += self.Hamilton(index, targetPosision[x])
return value
def heuristicCostEstimate(self):
return self.g + self.heuristicEstimate()
def __eq__(self, other):
return self.sequence == other.sequence
def __hash__(self):
hashValue = 0
factor = 1
for index in xrange(9):
factor *= (index + 1)
inverse = 0
for j in range(index):
if self.sequence[j] > self.sequence[index]:
inverse += 1
hashValue += factor * inverse
return hashValue
def __repr__(self):
if not self.fromState is None:
return "%d %d\n%s\n%s\n%s\n from\n%s\n%s\n%s\n" % (self.g, self.heuristicCostEstimate(),
self.sequence[0:3], self.sequence[3:6], self.sequence[6:9],
self.fromState.sequence[0:3], self.fromState.sequence[3:6], self.fromState.sequence[6:9])
else:
return "%d %d\n%s\n%s\n%s\n" % (self.g, self.heuristicCostEstimate(),
self.sequence[0:3], self.sequence[3:6], self.sequence[6:9])
def getNexts(self):
nextStates = []
switchPoints = [
[1, 3],
[0, 2, 4],
[1, 5],
[0, 4, 6],
[1, 3, 5, 7],
[2, 4, 8],
[3, 7],
[4, 6, 8],
[5, 7]
]
zeroPosition = self.sequence.index(0)
for switchPoint in switchPoints[zeroPosition]:
newSequence = list(self.sequence)
newSequence[zeroPosition], newSequence[switchPoint] = newSequence[switchPoint], newSequence[zeroPosition]
nextStates.append(State(newSequence))
return nextStates
def getPath(self):
current = self
path = []
step = 0
while not current is None:
step += 1
assert(step < 65536)
path.append(current)
current = current.fromState
return path
"""
A* search on 8-dights problem
f = g(past step) + heuristic(Hamilton distance)
"""
def EightDigits_AStar(startSequence):
startState = State(startSequence)
terminateState = State([1,2,3,4,5,6,7,8,0])
return AStar(startState, terminateState)
def EightDigits_BFS(startSequence):
startState = State(startSequence)
terminateState = State([1,2,3,4,5,6,7,8,0])
return BFS(startState, terminateState)
def EightDigits_IDA(startSequence):
startState = State(startSequence)
terminateState = State([1,2,3,4,5,6,7,8,0])
return IDA(startState, terminateState)
class Test(unittest.TestCase):
def setUp(self):
pass
def testBFS(self):
self.assertEquals(0, EightDigits_BFS([1,2,3,4,5,6,7,8,0])[0])
self.assertEquals(1, EightDigits_BFS([1,2,3,4,5,6,7,0,8])[0])
self.assertEquals(4, EightDigits_BFS([1,5,2,4,0,3,7,8,6])[0])
def testAStar(self):
self.assertEquals(0, EightDigits_AStar([1,2,3,4,5,6,7,8,0])[0])
self.assertEquals(1, EightDigits_AStar([1,2,3,4,5,6,7,0,8])[0])
(step, path) = EightDigits_AStar([1,5,2,4,0,3,7,8,6])
self.assertEquals(4, step)
(step, path) = EightDigits_AStar([8,7,4,0,5,1,6,3,2])
self.assertEquals(21, step)
self.assertEquals(path, EightDigits_BFS([8,7,4,0,5,1,6,3,2])[1])
def testIDA(self):
self.assertEquals(0, EightDigits_IDA([1,2,3,4,5,6,7,8,0])[0])
self.assertEquals(1, EightDigits_IDA([1,2,3,4,5,6,7,0,8])[0])
(step, path) = EightDigits_IDA([1,5,2,4,0,3,7,8,6])
self.assertEquals(4, step)
(step, path) = EightDigits_IDA([8,7,4,0,5,1,6,3,2])
self.assertEquals(21, step)
self.assertEquals(path, EightDigits_AStar([8,7,4,0,5,1,6,3,2])[1])
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0119,
0.019,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0286,
0.0048,
0,
0.66,
0.0625,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0333,
0.0048,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for search.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of search.\n\"\"\"",
"import unittest",
"from heapq import heappop, heappush",
"\"\"\"\nGenernal Breath first search\n\"\"\"",
"def BFS(startState, terminateState):\n... |
"""
Common function use in combinatics
"""
import unittest
import math
def P(n, k):
result = 1
for i in xrange(n - k + 1, n + 1):
result = result * i;
return result
def C(n, k):
if k < 0:
return 0
if k == 0:
return 1
result = 1
if k > n - k:
k = n - k
for i in xrange(n - k + 1, n + 1):
result = result * i / (i - (n - k))
return result
"""
c[i][j] = c[i-1][j] + cpi-1][j-1]
"""
def CombinationWithDp(n):
array2D = [[0 for _ in xrange(0, x + 1)] for x in xrange(n + 1)]
array2D[0][0] = 1;
for i in xrange(1, n + 1):
array2D[i][0] = 1;
array2D[i][i] = 1;
for j in range(1, i):
array2D[i][j] = array2D[i - 1][j] + array2D[i - 1][j - 1];
return array2D
"""
Stirling's approximation (or Stirling's formula) is an approximation for factorials.
ln(n!) = n*ln(n) - n + O(ln(n))
=>
n! = sqrt(2*pi*n) (n/e)^n
"""
def StirlingApproximation(n):
return math.sqrt(2 * math.pi * n) * (n / math.e)**n
class TestCombination(unittest.TestCase):
def setUp(self):
pass
def testAll(self):
self.assertEquals(P(10, 3), 10 * 9 * 8)
self.assertEquals(C(10, 3), 10 * 9 * 8 / (1 * 2 * 3))
self.assertEquals(CombinationWithDp(10)[10][5], C(10, 5))
self.assertTrue(abs(StirlingApproximation(10) - P(10, 10)) <
P(10, 10) / 10)
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0333,
0.05,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0833,
0.0167,
0,
0.66,
0.1,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.1,
0.0167,
0,
0.66,
0.2,... | [
"\"\"\"\nCommon function use in combinatics\n\"\"\"",
"import unittest",
"import math",
"def P(n, k):\n result = 1\n for i in xrange(n - k + 1, n + 1):\n result = result * i;\n return result",
" result = 1",
" for i in xrange(n - k + 1, n + 1):\n result = result * i;",
" result = result * ... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for kth.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of kth.
"""
import unittest
def swap(array, x, y):
array[x], array[y] = array[y], array[x]
def partition(array, start, end):
I = start + 1
J = I
pivot = start
while I < end:
if array[I] < array[pivot]:
swap(array, I, J)
J += 1
I += 1
swap(array, pivot, J - 1)
return J-1
def _findKth(array, start, end, kth):
if start < end:
partitionIndex = partition(array, start, end)
if partitionIndex == kth - 1:
return array[partitionIndex]
elif partitionIndex > kth - 1:
return _findKth(array, start, partitionIndex, kth)
else:
return _findKth(array, partitionIndex + 1, end, kth)
def findKth(array, kth):
return _findKth(array, 0, len(array), kth)
class test(unittest.TestCase):
def test(self):
self.assertEquals(1, findKth([4,2,1,7,5,3,8,10,9,6], 1))
self.assertEquals(2, findKth([4,2,1,7,5,3,8,10,9,6], 2))
self.assertEquals(3, findKth([4,2,1,7,5,3,8,10,9,6], 3))
self.assertEquals(4, findKth([4,2,1,7,5,3,8,10,9,6], 4))
self.assertEquals(5, findKth([4,2,1,7,5,3,8,10,9,6], 5))
self.assertEquals(6, findKth([4,2,1,7,5,3,8,10,9,6], 6))
self.assertEquals(7, findKth([4,2,1,7,5,3,8,10,9,6], 7))
self.assertEquals(8, findKth([4,2,1,7,5,3,8,10,9,6], 8))
self.assertEquals(9, findKth([4,2,1,7,5,3,8,10,9,6], 9))
self.assertEquals(10, findKth([4,2,1,7,5,3,8,10,9,6], 10))
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0472,
0.0755,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0943,
0.0189,
0,
0.66,
0.1429,
88,
0,
1,
0,
0,
88,
0,
0
],
[
2,
0,
0.1415,
0.0377,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for kth.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of kth.\n\"\"\"",
"import unittest",
"def swap(array, x, y):\n array[x], array[y] = array[y], array[x]",
" array[x], array[y] = array[y], array[x]",
"def partition(arr... |
# Kadane's algorithm consists
def max_subarray(A):
max_ending_here = max_so_far = 0
for x in A:
max_ending_here = max(0, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
#
# A variation of the problem that does not allow zero-length
#subarrays to be returned in the case that the entire array consists of
#negative numbers can be solved with the following code:
def max_subarray(A):
max_ending_here = max_so_far = A[0]
for x in A[1:]:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
| [
[
2,
0,
0.2895,
0.3158,
0,
0.66,
0,
90,
0,
1,
1,
0,
0,
0,
2
],
[
14,
1,
0.2105,
0.0526,
1,
0.62,
0,
33,
1,
0,
0,
0,
0,
1,
0
],
[
6,
1,
0.3158,
0.1579,
1,
0.62,
... | [
"def max_subarray(A):\n max_ending_here = max_so_far = 0\n for x in A:\n max_ending_here = max(0, max_ending_here + x)\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far",
" max_ending_here = max_so_far = 0",
" for x in A:\n max_ending_here = max(0, max_ending_here + x)\n max_s... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for shortest_path.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of shortest_path.
"""
import unittest
from heapq import heappush, heappop
"""
Dijkstra algorithm using a binary heap
O(nlogn)
"""
def dijkstraShortestPath(array2D, source):
n = len(array2D)
assert (len(array2D[0]) == n)
distances = [float('Inf')] * n
distances[source] = 0
opened = []
heappush(opened, (0, source))
while len(opened) > 0:
(currectDistance, vertex) = heappop(opened)
if currectDistance != distances[vertex]: #have been updated
continue
for x in xrange(n):
if x != vertex and distances[x] > distances[vertex] + array2D[vertex][x]:
distances[x] = distances[vertex] + array2D[vertex][x]
heappush(opened, (distances[x], x))
return distances
"""
Floyd algorihm
O(n^3)
"""
def floydShortestPath(array2D):
distances = array2D[:]
n = len(array2D)
for x in xrange(n):
for i in xrange(n):
for j in xrange(n):
if distances[i][j] > distances[i][x] + distances[x][j]:
distances[i][j] = distances[i][x] + distances[x][j]
for x in xrange(n):
if distances[x][x] < 0:
return False
return True, distances
"""
Bellman algorithm for negative edge
O(nm)
"""
def Bellman(array2D):
pass
class Test(unittest.TestCase):
def setUp(self):
inf = float('Inf')
array2D = [[inf] * 5 for x in xrange(5)]
for x in xrange(5):
array2D[x][x] = 0
array2D[0][1] = array2D[1][0] = 1
array2D[0][3] = array2D[3][0] = 3
array2D[0][4] = array2D[4][0] = 1
array2D[1][2] = array2D[2][1] = 2
array2D[1][4] = array2D[4][1] = 4
array2D[2][3] = array2D[3][2] = 2
array2D[2][4] = array2D[4][2] = 3
array2D[3][4] = array2D[4][3] = 5
self.array2D = array2D
def testDijkstra(self):
distances = dijkstraShortestPath(self.array2D, 0)
self.assertEquals([0, 1, 3, 3, 1], distances)
def testFloyd(self):
distances = floydShortestPath(self.array2D)[1]
self.assertEquals([0, 1, 3, 3, 1], distances[0])
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0284,
0.0455,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0682,
0.0114,
0,
0.66,
0.1,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0795,
0.0114,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for shortest_path.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of shortest_path.\n\"\"\"",
"import unittest",
"from heapq import heappush, heappop",
"\"\"\"\nDijkstra algorithm using a binary heap\nO(nlogn)\n\"\"\"",
"def ... |
"""
Common function use in graph
"""
import unittest
import math
"""
For sparse graph
"""
class Graph:
"""
Create a graph with n node [0, n)
"""
def __init__(self, n):
self.n = n
self.adjacents = [list() for x in xrange(n)]
"""
Insert a edit x->y
"""
def insert(self, x, y):
self.adjacents[x].append(y)
def insertList(self, x, nodeList):
for y in nodeList:
self.adjacents[x].append(y)
def remove(self, x, y):
self.adjacents[x].remove(y)
def hasEdge(self, x, y):
return self.adjacents[x].count(y) > 0
def toString(self):
for x in xrange(self.n):
print x, ":", self.adjacents[x]
"""
A DFS to collect as much as information of a graph
degree[]: degree of a node
edge[][]: edge type
0:no edge
1:tree (a edge from parent to a child in a tree)
2:back (a edge from a node to its ancestor in a tree)
3:down (a edge from two diffient branch, the current visit first)
4:cross (a edge from tow diffient branch, the current visit late)
start[]: start index of visit a node
finish[]: finish index of visit a node
parent[]: parent node
lowIndex[]: represents the smallest index of any node known to be reachable from
(including itself)
lowIndex[u] = start[u]
lowIndex[u] = min(lowIndex[u], lowIndex[v]) when u->v
"""
def generalDFS(self):
class Env:
def __init__(self, n):
self.index = 0
self.edge = [[0] * n] * n #TODO store it in a spare way
self.degree = [0] * n
self.start = [0] * n
self.finish = [0] * n
self.index = 0
self.lowIndex = [0] * n
self.parent = [-1] * n
env = Env(self.n)
def dfs(u, env):
env.index += 1
env.start[u] = env.lowIndex[u] = env.index
for v in self.adjacents[u]:
if env.start[v] == 0: #found an untouched node
env.edge[u][v] = 1 #a tree edge
env.degree[u] += 1
env.parent[v] = u
dfs(v, env)
env.lowIndex[u] = min(env.lowIndex[v], env.lowIndex[u])
if env.lowIndex[v] == env.start[v]:
pass # found a bridge of two SCC(see tarjanSCC below)
elif env.finish[v] == 0: # found a node opened, but not closed
env.edge[u][v] = 2 # a back edge
env.lowIndex[u] = min(env.lowIndex[v], env.lowIndex[u])
elif env.start[v] > env.start[u]: # found a closed node that started later
env.edge[u][v] = 3 # a down edge
else:
env.edge[u][v] = 4 # a cross edge
env.index += 1
env.finish[u] = env.index
for u in xrange(self.n):
if env.start[u] == 0: # an untouched node
env.parent[u] = -1 # empty parent
dfs(u, env)
"""
Topological sort by removing node in-dergree = 0
O(|V| + |E|)
"""
def topologicalSort(self):
order = []
n = self.n
# Count the incoming edges
incomingDegree = [0] * n
for x in xrange(n):
for node in self.adjacents[x]:
incomingDegree[node] += 1
for x in xrange(n):
if incomingDegree[x] == 0:
order.append(x)
# index that point to node that having proceed
index = 0
while index < len(order):
currentNode = order[index]
for nextNode in self.adjacents[currentNode]:
incomingDegree[nextNode] -= 1
if incomingDegree[nextNode] == 0:
order.append(nextNode)
index += 1
if len(order) < n:
raise IndexError('This graph is not a DAG')
return order
"""
Tarjan's Algorithm
finding the strongly connected components of a graph.
proceess with a DFS.
O(|V| + |E|)
"""
def tarjanSCC(self):
class Env:
def __init__(self, n):
self.start = [0] * n
self.closed = [0] * n
self.lowIndex = [0] * n
self.scc = []
self.stack = []
self.index = 0
env = Env(self.n)
def dfs(x, env):
env.index += 1
env.start[x] = env.index
env.lowIndex[x] = env.index
env.stack.append(x)
for y in self.adjacents[x]:
if env.start[y] == 0: #untouched
dfs(y, env)
env.lowIndex[x] = min(env.lowIndex[y], env.lowIndex[x])
elif env.closed[y] == 0:
env.lowIndex[x] = min(env.lowIndex[y], env.lowIndex[x])
env.closed[x] = 1
if env.lowIndex[x] == env.start[x]:
# found a scc, pop the stack until the top one == x
scc = []
while env.stack[-1] != x:
scc.append(env.stack.pop())
scc.append(env.stack.pop())
env.scc.append(scc)
for x in xrange(self.n):
if env.start[x] == 0:
dfs(x, env)
return env.scc
"""
For density grpah
"""
"""
Floyd-Warshall algorithm:
finding shortest paths in a weighted graph with positive or
negative edge weights (but with no negative cycles, see below) and
also for finding transitive closure of a relation R
O(n^3)
for every x, s->x && x->t => s->t
"""
def floydWarshallTransitive(array2D):
for x in xrange(n):
array2D[x][x] = True
for s in xrange(n):
if array2D[s][x]:
for t in xrange(n):
if array2D[x][t]:
array2D[s][t] = True
class TestGraph(unittest.TestCase):
def setUp(self):
pass
def testTopo(self):
graph = Graph(4)
graph.insertList(2, [1, 3])
graph.insertList(1, [0])
graph.insertList(3, [0, 1])
self.assertEquals([2, 3, 1, 0], graph.topologicalSort())
def testSCC(self):
graph = Graph(9)
graph.insertList(0, [1])
graph.insertList(1, [2])
graph.insertList(2, [0, 3])
graph.insertList(3, [4, 6])
graph.insertList(4, [5])
graph.insertList(5, [3])
graph.insertList(6, [7])
graph.insertList(7, [8])
graph.insertList(8, [6])
self.assertEquals([[8, 7, 6], [5, 4, 3], [2, 1, 0]], graph.tarjanSCC())
graph.generalDFS()
def testAll(self):
pass
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0089,
0.0134,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0179,
0.0045,
0,
0.66,
0.1111,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0223,
0.0045,
0,
0.66,
... | [
"\"\"\"\nCommon function use in graph\n\"\"\"",
"import unittest",
"import math",
"\"\"\"\nFor sparse graph\n\"\"\"",
"class Graph:\n \"\"\"\n Create a graph with n node [0, n)\n \"\"\"\n def __init__(self, n):\n self.n = n\n self.adjacents = [list() for x in xrange(n)]",
" \"\"\"\n Create a g... |
"""TODO(gnefihz): DO NOT SUBMIT without one-line documentation for MST.
TODO(gnefihz): DO NOT SUBMIT without a detailed description of MST.
"""
import unittest
import heapq
"""
For sparse graph
"""
class WeightGraph:
"""
Create a graph with n node [0, n)
"""
def __init__(self, n):
self.n = n
self.adjacents = {}
"""
Insert a edit x->y
"""
def insert(self, x, y, w):
if x not in self.adjacents:
self.adjacents[x] = {}
self.adjacents[x][y] = w
def insertList(self, x, nodeList):
for (y, w) in nodeList:
self.insert(x, y, w)
def remove(self, x, y):
del self.adjacents[x][y]
def hasEdge(self, x, y):
y in self.adjacents[x]
"""
Prim's algorithm
O(|E| log |V|)
"""
def primMST(self):
totalWeight = 0
closed = [0] * self.n
nodeHeap = []
heapq.heappush(nodeHeap, (0, 0)) # start from 0 node
totalNodeCount = 0
while len(nodeHeap) > 0:
(w, node) = heapq.heappop(nodeHeap)
if closed[node] == 0:
closed[node] = 1
totalWeight += w
totalNodeCount += 1
if totalNodeCount == self.n:
break
for nextNode, nextW in self.adjacents[node].iteritems():
if closed[nextNode] == 0:
heapq.heappush(nodeHeap, (nextW, nextNode))
return totalWeight
class Edge:
def __init__(self, x, y, w):
self.x = x
self.y = y
self.w = w
def __repr__(self):
return '(%d->%d:%d)' % (self.x, self.y, self.w)
def compareKey(self):
return self.w
"""
A disjion set without union by rank
"""
class DisjoinSet:
def __init__(self, n):
self.n = n
self.parent = {}
self.rank = {}
"""
Apply path compression
"""
def find(self, x):
if x not in self.parent:
return x
else:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
"""
Union by rank
"""
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX == rootY:
return
rankX = self.rank.get(x, 0)
rankY = self.rank.get(y, 0)
if rankX < rankY:
self.parent[rootX] = rootY
elif rankY < rankX:
self.parent[rootY] = rootX
else:
self.rank[rootY] = rankY + 1
self.parent[rootX] = rootY
"""
Kruskal on a edge list
O(E * log(E))
"""
def kruskalMst(edgeList, n):
totalWeight = 0
edgeList.sort(key=Edge.compareKey)
treeEdgeList = []
disjionSet = DisjoinSet(n)
for edge in edgeList:
rootX = disjionSet.find(edge.x)
rootY = disjionSet.find(edge.y)
if rootX != rootY:
disjionSet.union(edge.x, edge.y)
totalWeight += edge.w
treeEdgeList.append(edge)
if len(treeEdgeList) == n - 1:
break
return totalWeight, treeEdgeList
class TestGraph(unittest.TestCase):
def setUp(self):
pass
def testMST(self):
self.assertEquals(11,
kruskalMst(
[Edge(0, 1, 3), Edge(0, 2, 1), Edge(1, 2, 4),
Edge(1, 3, 5), Edge(2, 3, 6), Edge(3, 4, 2),
Edge(2, 4, 7)], 5)[0])
graph = WeightGraph(5)
graph.insert(0, 1, 3)
graph.insert(0, 2, 1)
graph.insert(1, 2, 4)
graph.insert(1, 3, 5)
graph.insert(2, 3, 6)
graph.insert(3, 4, 2)
graph.insert(2, 4, 7)
self.assertEquals(11, graph.primMST())
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.0156,
0.025,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0375,
0.0063,
0,
0.66,
0.0909,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0437,
0.0063,
0,
0.66,
... | [
"\"\"\"TODO(gnefihz): DO NOT SUBMIT without one-line documentation for MST.\n\nTODO(gnefihz): DO NOT SUBMIT without a detailed description of MST.\n\"\"\"",
"import unittest",
"import heapq",
"\"\"\"\nFor sparse graph\n\"\"\"",
"class WeightGraph:\n \"\"\"\n Create a graph with n node [0, n)\n \"\"\"\n ... |
#!/usr/bin/env python
from random import randint
a = raw_input("Cantidad de nodos :")
b = raw_input("cantidad de ramas :")
f = open("p1.in", "w")
f.write(str(a)+" ")
cantcepa = int(a)-1
f.write(str(cantcepa)+"\n")
"""
for m in range(0,int(a)):
izq = 2*m+1
der = 2*m+2
if izq<int(a):
f.write( str(m)+" "+str(izq)+"\n")
if der<len(li):
f.write(str(m)+" "+str(der)+"\n")
"""
cont = 1
for m in range(0,int(a)):
if cont<int(a):
for i in range(0,int(b)):
if cont<int(a):
f.write( str(m)+" "+str(cont)+"\n")
cont+=1
f.write("#")
f.close()
| [
[
1,
0,
0.0606,
0.0303,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.1515,
0.0303,
0,
0.66,
0.0909,
475,
3,
1,
0,
0,
821,
10,
1
],
[
14,
0,
0.1818,
0.0303,
0,
... | [
"from random import randint",
"a = raw_input(\"Cantidad de nodos :\")",
"b = raw_input(\"cantidad de ramas :\")",
"f = open(\"p1.in\", \"w\")",
"f.write(str(a)+\" \")",
"cantcepa = int(a)-1",
"f.write(str(cantcepa)+\"\\n\")",
"\"\"\"\nfor m in range(0,int(a)):\n\tizq = 2*m+1\n\tder = 2*m+2\n\n\tif izq... |
#!/usr/bin/env python
from random import randint
a = raw_input("Cantidad de nodos :")
b = raw_input("cantidad de ramas :")
f = open("p1.in", "w")
f.write(str(a)+" ")
cantcepa = int(a)-1
f.write(str(cantcepa)+"\n")
"""
for m in range(0,int(a)):
izq = 2*m+1
der = 2*m+2
if izq<int(a):
f.write( str(m)+" "+str(izq)+"\n")
if der<len(li):
f.write(str(m)+" "+str(der)+"\n")
"""
cont = 1
for m in range(0,int(a)):
if cont<int(a):
for i in range(0,int(b)):
if cont<int(a):
f.write( str(m)+" "+str(cont)+"\n")
cont+=1
f.write("#")
f.close()
| [
[
1,
0,
0.0606,
0.0303,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.1515,
0.0303,
0,
0.66,
0.0909,
475,
3,
1,
0,
0,
821,
10,
1
],
[
14,
0,
0.1818,
0.0303,
0,
... | [
"from random import randint",
"a = raw_input(\"Cantidad de nodos :\")",
"b = raw_input(\"cantidad de ramas :\")",
"f = open(\"p1.in\", \"w\")",
"f.write(str(a)+\" \")",
"cantcepa = int(a)-1",
"f.write(str(cantcepa)+\"\\n\")",
"\"\"\"\nfor m in range(0,int(a)):\n\tizq = 2*m+1\n\tder = 2*m+2\n\n\tif izq... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('time_err.dat')
fin2=open('time_err_n3.dat')
todo=fin.read().split('\n')
todo2=fin2.read().split('\n')
xs=[float(x.split()[0]) for x in todo if x]
ys=[float(x.split()[1]) for x in todo if x]
ys2=[float(x.split()[1]) for x in todo2 if x]
yerr=[float(x.split()[2]) for x in todo if x]
yerr2=[float(x.split()[2]) for x in todo2 if x]
diff=reduce(lambda x,y:x+y, [ys2[i]/ys[i] for i in range(len(ys))], 0)/len(ys)
title("Comparacion de strassen vs algoritmo en $cw$")
xlabel("Cantidad de Personas")
ylabel("Tiempo de ejecucion (s)")
errorbar(xs,ys,yerr,marker='_',color='k',ls='None',label="Strassen con umbral=4")
errorbar(xs,ys2,yerr2,marker='_',color='b',ls='None',label="Algoritmo tradicional")
legend(loc="upper left")
#text(1,.06,"en promedio,\nalgoritmo_cubico/strassen="+str("%.3f"%diff))
savefig('ej3_times_vs.png',dpi=640./8)
show()
| [
[
1,
0,
0.1304,
0.0435,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2174,
0.0435,
0,
0.66,
0.0556,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.2609,
0.0435,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('time_err.dat')",
"fin2=open('time_err_n3.dat')",
"todo=fin.read().split('\\n')",
"todo2=fin2.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo if x]",
"ys=[float(x.split()[1]) for x in todo if x]",
"ys2=[float(x.split()[1]) for x in todo2 if x]"... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('time_err.dat')
todo=fin.read().split('\n')
xs=[float(x.split()[0]) for x in todo if x]
ys=[float(x.split()[1]) for x in todo if x]
yerr=[float(x.split()[2]) for x in todo if x]
title("Tiempo de ejecucion de $cw$")
xlabel("Cantidad de Personas")
ylabel("Tiempo de ejecucion (s)")
errorbar(xs,ys,yerr,marker='_',color='k',ls='None')
plot(xs,[(x**2.81)*.000004 for x in xs],label=r"$c \times n^{log_2(7)}$")
ylim(0,0.08)
legend(loc=0)
savefig('ej3_times.png',dpi=640./8)
show()
| [
[
1,
0,
0.1667,
0.0556,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2778,
0.0556,
0,
0.66,
0.0714,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3333,
0.0556,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('time_err.dat')",
"todo=fin.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo if x]",
"ys=[float(x.split()[1]) for x in todo if x]",
"yerr=[float(x.split()[2]) for x in todo if x]",
"title(\"Tiempo de ejecucion de $cw$\")",
"xlabel(\"Cantidad de ... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('time_err.dat')
fin2=open('time_err_n3.dat')
todo=fin.read().split('\n')
todo2=fin2.read().split('\n')
xs=[float(x.split()[0]) for x in todo if x]
ys=[float(x.split()[1]) for x in todo if x]
ys2=[float(x.split()[1]) for x in todo2 if x]
yerr=[float(x.split()[2]) for x in todo if x]
yerr2=[float(x.split()[2]) for x in todo2 if x]
diff=reduce(lambda x,y:x+y, [ys2[i]/ys[i] for i in range(len(ys))], 0)/len(ys)
title("Comparacion de strassen vs algoritmo en $cw$")
xlabel("Cantidad de Personas")
ylabel("Tiempo de ejecucion (s)")
errorbar(xs,ys,yerr,marker='_',color='k',ls='None',label="Strassen con umbral=4")
errorbar(xs,ys2,yerr2,marker='_',color='b',ls='None',label="Algoritmo tradicional")
legend(loc="upper left")
#text(1,.06,"en promedio,\nalgoritmo_cubico/strassen="+str("%.3f"%diff))
savefig('ej3_times_vs.png',dpi=640./8)
show()
| [
[
1,
0,
0.1304,
0.0435,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2174,
0.0435,
0,
0.66,
0.0556,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.2609,
0.0435,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('time_err.dat')",
"fin2=open('time_err_n3.dat')",
"todo=fin.read().split('\\n')",
"todo2=fin2.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo if x]",
"ys=[float(x.split()[1]) for x in todo if x]",
"ys2=[float(x.split()[1]) for x in todo2 if x]"... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('counts.dat')
todo=fin.read().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 $cw$")
xlabel("Cantidad de Personas")
ylabel("Cantidad de operaciones")
plot(xs,ys,'kx',label="__nolabel__")
plot(xs,[x**2.81*150 for x in xs],label=r"$c \times n^{log_2(7)}$")
legend(loc=0)
ylim(0,.27e7)
savefig('ej3_counts.png',dpi=640./8)
show()
| [
[
1,
0,
0.1765,
0.0588,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2941,
0.0588,
0,
0.66,
0.0769,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3529,
0.0588,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('counts.dat')",
"todo=fin.read().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 $cw$\")",
"xlabel(\"Cantidad de Personas\")",
"ylabel(\"Cantidad de operaciones\")"... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed
from math import sqrt
seed(1234) # defino el seed para hacer el experimento reproducible
ejecutable="cw"
tamanios_entrada=sorted(range(1,45)*2)
def prueba(tamanio_entrada):
out=str(tamanio_entrada)
for i in range(tamanio_entrada):
out+='\n'
li=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint(0,tamanio_entrada))] if x!=i]))
out+=str(len(li))+' '+' '.join(li)
return out
ender="-1"
pruebas=[(n,prueba(n)) for n in tamanios_entrada]
open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas)))
def runtest(pruebas,args):
fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for prueba in pruebas:
fp.stdin.write(prueba[1]+"\n") # le manda la instancia
r=fp.stdout.readline().rstrip() # recibo el resultado
print "tamanio: ",prueba[0]," ",args[0],"=",r
yield prueba[0],r # lo devuelvo
fp.stdin.write(ender+"\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)
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(pruebas,['time','0.06','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(pruebas,['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.0385,
0.0385,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0769,
0.0385,
0,
0.66,
0.1667,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1154,
0.0385,
0,
... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed",
"from math import sqrt",
"def prueba(tamanio_entrada):\n\tout=str(tamanio_entrada)\n\tfor i in range(tamanio_entrada):\n\t\tout+='\\n'\n\t\tli=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed
from math import sqrt
seed(1234) # defino el seed para hacer el experimento reproducible
ejecutable="cw_n3"
tamanios_entrada=sorted(range(1,45)*2)
def prueba(tamanio_entrada):
out=str(tamanio_entrada)
for i in range(tamanio_entrada):
out+='\n'
li=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint(0,tamanio_entrada))] if x!=i]))
out+=str(len(li))+' '+' '.join(li)
return out
ender="-1"
pruebas=[(n,prueba(n)) for n in tamanios_entrada]
open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas)))
def runtest(pruebas,args):
fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for prueba in pruebas:
fp.stdin.write(prueba[1]+"\n") # le manda la instancia
r=fp.stdout.readline().rstrip() # recibo el resultado
print "tamanio: ",prueba[0]," ",args[0],"=",r
yield prueba[0],r # lo devuelvo
fp.stdin.write(ender+"\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)
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(pruebas,['time','0.06','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_n3.dat','w').write(out) # lo guardo en el archivo
print "\nOutput escrito a time_err_n3.dat"
out=""
if "--count" in opts or "-c" in opts:
for i in runtest(pruebas,['count']): #para cada caso de prueba..
dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida
out += dat
open('counts_n3.dat','w').write(out) # lo guardo en el archivo
print "\nOutput escrito a counts_n3.dat"
| [
[
1,
0,
0.0385,
0.0385,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0769,
0.0385,
0,
0.66,
0.1667,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1154,
0.0385,
0,
... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed",
"from math import sqrt",
"def prueba(tamanio_entrada):\n\tout=str(tamanio_entrada)\n\tfor i in range(tamanio_entrada):\n\t\tout+='\\n'\n\t\tli=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin2=open('time_err_n3.dat')
todo2=fin2.read().split('\n')
xs=[float(x.split()[0]) for x in todo2 if x]
ys2=[float(x.split()[1]) for x in todo2 if x]
yerr2=[float(x.split()[2]) for x in todo2 if x]
title("Tiempo de ejecución de algoritmo cubico de $cw$")
xlabel("Tamano de entrada")
ylabel("Tiempo de ejecucion")
errorbar(xs,ys2,yerr2,marker='_',color='b',ls='None',label="$algoritmo cubico$")
plot(xs,[x**3*.00000024 for x in xs],color='r',label=r"$c \times n^3$")
legend(loc="upper left")
#text(1,.6,"en promedio,\nalgoritmo_cubico/strassen="+str("%.3f"%diff))
savefig('ej3_times_n3.png',dpi=640./8)
show()
| [
[
1,
0,
0.1667,
0.0556,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2778,
0.0556,
0,
0.66,
0.0769,
965,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3333,
0.0556,
0,
... | [
"from matplotlib.pyplot import *",
"fin2=open('time_err_n3.dat')",
"todo2=fin2.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo2 if x]",
"ys2=[float(x.split()[1]) for x in todo2 if x]",
"yerr2=[float(x.split()[2]) for x in todo2 if x]",
"title(\"Tiempo de ejecución de algoritmo cubico de $cw... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin2=open('time_err_n3.dat')
todo2=fin2.read().split('\n')
xs=[float(x.split()[0]) for x in todo2 if x]
ys2=[float(x.split()[1]) for x in todo2 if x]
yerr2=[float(x.split()[2]) for x in todo2 if x]
title("Tiempo de ejecución de algoritmo cubico de $cw$")
xlabel("Tamano de entrada")
ylabel("Tiempo de ejecucion")
errorbar(xs,ys2,yerr2,marker='_',color='b',ls='None',label="$algoritmo cubico$")
plot(xs,[x**3*.00000024 for x in xs],color='r',label=r"$c \times n^3$")
legend(loc="upper left")
#text(1,.6,"en promedio,\nalgoritmo_cubico/strassen="+str("%.3f"%diff))
savefig('ej3_times_n3.png',dpi=640./8)
show()
| [
[
1,
0,
0.1667,
0.0556,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2778,
0.0556,
0,
0.66,
0.0769,
965,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3333,
0.0556,
0,
... | [
"from matplotlib.pyplot import *",
"fin2=open('time_err_n3.dat')",
"todo2=fin2.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo2 if x]",
"ys2=[float(x.split()[1]) for x in todo2 if x]",
"yerr2=[float(x.split()[2]) for x in todo2 if x]",
"title(\"Tiempo de ejecución de algoritmo cubico de $cw... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed
from math import sqrt
seed(1234) # defino el seed para hacer el experimento reproducible
ejecutable="cw"
tamanios_entrada=sorted(range(1,45)*2)
def prueba(tamanio_entrada):
out=str(tamanio_entrada)
for i in range(tamanio_entrada):
out+='\n'
li=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint(0,tamanio_entrada))] if x!=i]))
out+=str(len(li))+' '+' '.join(li)
return out
ender="-1"
pruebas=[(n,prueba(n)) for n in tamanios_entrada]
open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas)))
def runtest(pruebas,args):
fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for prueba in pruebas:
fp.stdin.write(prueba[1]+"\n") # le manda la instancia
r=fp.stdout.readline().rstrip() # recibo el resultado
print "tamanio: ",prueba[0]," ",args[0],"=",r
yield prueba[0],r # lo devuelvo
fp.stdin.write(ender+"\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)
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(pruebas,['time','0.06','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(pruebas,['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.0385,
0.0385,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0769,
0.0385,
0,
0.66,
0.1667,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1154,
0.0385,
0,
... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed",
"from math import sqrt",
"def prueba(tamanio_entrada):\n\tout=str(tamanio_entrada)\n\tfor i in range(tamanio_entrada):\n\t\tout+='\\n'\n\t\tli=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('time_err.dat')
todo=fin.read().split('\n')
xs=[float(x.split()[0]) for x in todo if x]
ys=[float(x.split()[1]) for x in todo if x]
yerr=[float(x.split()[2]) for x in todo if x]
title("Tiempo de ejecucion de $cw$")
xlabel("Cantidad de Personas")
ylabel("Tiempo de ejecucion (s)")
errorbar(xs,ys,yerr,marker='_',color='k',ls='None')
plot(xs,[(x**2.81)*.000004 for x in xs],label=r"$c \times n^{log_2(7)}$")
ylim(0,0.08)
legend(loc=0)
savefig('ej3_times.png',dpi=640./8)
show()
| [
[
1,
0,
0.1667,
0.0556,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2778,
0.0556,
0,
0.66,
0.0714,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3333,
0.0556,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('time_err.dat')",
"todo=fin.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo if x]",
"ys=[float(x.split()[1]) for x in todo if x]",
"yerr=[float(x.split()[2]) for x in todo if x]",
"title(\"Tiempo de ejecucion de $cw$\")",
"xlabel(\"Cantidad de ... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('counts.dat')
todo=fin.read().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 $cw$")
xlabel("Cantidad de Personas")
ylabel("Cantidad de operaciones")
plot(xs,ys,'kx',label="__nolabel__")
plot(xs,[x**2.81*150 for x in xs],label=r"$c \times n^{log_2(7)}$")
legend(loc=0)
ylim(0,.27e7)
savefig('ej3_counts.png',dpi=640./8)
show()
| [
[
1,
0,
0.1765,
0.0588,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2941,
0.0588,
0,
0.66,
0.0769,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3529,
0.0588,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('counts.dat')",
"todo=fin.read().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 $cw$\")",
"xlabel(\"Cantidad de Personas\")",
"ylabel(\"Cantidad de operaciones\")"... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('time_err.dat')
todo=fin.read().split('\n')
xs=[float(x.split()[0]) for x in todo if x]
ys=[float(x.split()[1]) for x in todo if x]
yerr=[float(x.split()[2]) for x in todo if x]
title("Tiempo de ejecucion de $matching$")
xlabel("Tamano de entrada")
ylabel("Tiempo de ejecucion")
errorbar(xs,ys,yerr,marker='_',color='k',ls='None')
plot(xs,[x*.000000025+.0000005 for x in xs],label=r"$c \times x$")
legend(loc=0)
savefig('ej1_times.png',dpi=640./8)
show()
| [
[
1,
0,
0.1765,
0.0588,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2941,
0.0588,
0,
0.66,
0.0769,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3529,
0.0588,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('time_err.dat')",
"todo=fin.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo if x]",
"ys=[float(x.split()[1]) for x in todo if x]",
"yerr=[float(x.split()[2]) for x in todo if x]",
"title(\"Tiempo de ejecucion de $matching$\")",
"xlabel(\"Tamano... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('counts.dat')
todo=fin.read().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("Tamano de entrada")
ylabel("Cantidad de operaciones")
plot(xs,ys,'kx',label="__nolabel__")
plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
savefig('ej1_counts.png',dpi=640./8)
show()
| [
[
1,
0,
0.1875,
0.0625,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.3125,
0.0625,
0,
0.66,
0.0833,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.375,
0.0625,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('counts.dat')",
"todo=fin.read().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(\"Tamano de entrada\")",
"ylabel(\"Cantidad de operaciones\... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed
from math import sqrt
seed(1234) # defino el seed para hacer el experimento reproducible
ejecutable="matching"
tamanios_entrada=sorted(range(3,300)[::5])
def prueba(tamanio_entrada):
return str(tamanio_entrada)+' '+' '.join([str(randint(0,tamanio_entrada/2)) for x in range(tamanio_entrada)])
ender="-1"
pruebas=[(n,prueba(n)) for n in tamanios_entrada]
open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas)))
def runtest(pruebas,args):
fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for prueba in pruebas:
fp.stdin.write(prueba[1]+"\n") # le manda la instancia
r=fp.stdout.readline().rstrip() # recibo el resultado
print "tamanio: ",prueba[0]," ",args[0],"=",r
yield prueba[0],r # lo devuelvo
fp.stdin.write(ender+"\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)
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(pruebas,['time','0.2','2']): # 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(pruebas,['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.1667,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1429,
0.0476,
0,
... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed",
"from math import sqrt",
"def prueba(tamanio_entrada):\n\treturn str(tamanio_entrada)+' '+' '.join([str(randint(0,tamanio_entrada/2)) for x in range(tamanio_entrada)])",
"\treturn str(tamanio_entrada)+' '+' '.join([str(ran... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed
from math import sqrt
seed(1234) # defino el seed para hacer el experimento reproducible
ejecutable="matching"
tamanios_entrada=sorted(range(3,300)[::5])
def prueba(tamanio_entrada):
return str(tamanio_entrada)+' '+' '.join([str(randint(0,tamanio_entrada/2)) for x in range(tamanio_entrada)])
ender="-1"
pruebas=[(n,prueba(n)) for n in tamanios_entrada]
open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas)))
def runtest(pruebas,args):
fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for prueba in pruebas:
fp.stdin.write(prueba[1]+"\n") # le manda la instancia
r=fp.stdout.readline().rstrip() # recibo el resultado
print "tamanio: ",prueba[0]," ",args[0],"=",r
yield prueba[0],r # lo devuelvo
fp.stdin.write(ender+"\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)
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(pruebas,['time','0.2','2']): # 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(pruebas,['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.1667,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1429,
0.0476,
0,
... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed",
"from math import sqrt",
"def prueba(tamanio_entrada):\n\treturn str(tamanio_entrada)+' '+' '.join([str(randint(0,tamanio_entrada/2)) for x in range(tamanio_entrada)])",
"\treturn str(tamanio_entrada)+' '+' '.join([str(ran... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('time_err.dat')
todo=fin.read().split('\n')
xs=[float(x.split()[0]) for x in todo if x]
ys=[float(x.split()[1]) for x in todo if x]
yerr=[float(x.split()[2]) for x in todo if x]
title("Tiempo de ejecucion de $matching$")
xlabel("Tamano de entrada")
ylabel("Tiempo de ejecucion")
errorbar(xs,ys,yerr,marker='_',color='k',ls='None')
plot(xs,[x*.000000025+.0000005 for x in xs],label=r"$c \times x$")
legend(loc=0)
savefig('ej1_times.png',dpi=640./8)
show()
| [
[
1,
0,
0.1765,
0.0588,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2941,
0.0588,
0,
0.66,
0.0769,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3529,
0.0588,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('time_err.dat')",
"todo=fin.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo if x]",
"ys=[float(x.split()[1]) for x in todo if x]",
"yerr=[float(x.split()[2]) for x in todo if x]",
"title(\"Tiempo de ejecucion de $matching$\")",
"xlabel(\"Tamano... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('counts.dat')
todo=fin.read().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("Tamano de entrada")
ylabel("Cantidad de operaciones")
plot(xs,ys,'kx',label="__nolabel__")
plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
savefig('ej1_counts.png',dpi=640./8)
show()
| [
[
1,
0,
0.1875,
0.0625,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.3125,
0.0625,
0,
0.66,
0.0833,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.375,
0.0625,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('counts.dat')",
"todo=fin.read().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(\"Tamano de entrada\")",
"ylabel(\"Cantidad de operaciones\... |
#!/usr/bin/env python
from Tkinter import *
from random import *
from math import sqrt
import subprocess
def prueba(tamanio_entrada):
cant=int(random()*tamanio_entrada)
w=randint(3,int(2*sqrt(tamanio_entrada)))
h=tamanio_entrada/w
vs=[]
for v in range(cant):
orient=choice(['-','|'])
if orient=='|':
l=randint(1,int(h*.5))
x,y=randint(1,w),randint(1,h-l)
else:
l=randint(1,int(w*.5))
x,y=randint(1,w-l),randint(1,h)
ok=True
for v2 in vs:
if orient=='-':
if v2[2]=='-' and v2[1]==y and (x<v2[0]<x+l or x<v2[0]+v2[3]<x+l or v2[0]<x<v2[0]+v2[3] or v2[0]<x+l<v2[0]+v2[3] or x==v2[0]): ok=False
if orient=='|':
if v2[2]=='|' and v2[0]==x and (y<v2[1]<y+l or y<v2[1]+v2[3]<y+l or v2[1]<y<v2[1]+v2[3] or v2[1]<y+l<v2[1]+v2[3] or y==v2[1]): ok=False
if ok: vs.append((x,y,orient,l,randint(0,10)))
offsx,offsy=randint(0,800),randint(0,800)
return str(randint(0,10))+'\t'+str(len(vs))+'\n'+'\n'.join([str(v[0]+offsx)+' '+str(v[1]+offsy)+' '+v[2]+' '+str(v[3])+' '+str(v[4])+' ' for v in vs])
factor=20
maxx,maxy,w=0,0,0
sp=Spinbox(from_=100,to=1000,increment=1)
canvas = Canvas(width=factor+factor*maxx, height=factor+factor*maxy, bg='lightblue')
def change():
global canvas
caso=prueba(int(sp.get()))
print caso
print
vallas=[[int(x[0])]+[int(x[1])]+[x[2]]+[int(x[3])]+[int(x[4])] for x in map(lambda x:x.split(),caso[1:].split('\n')) if len(x)==5]
maxx=max([x[0]+x[3] for x in vallas if x[2]=='-']+[x[0] for x in vallas if x[2]=='|']+[3])
maxy=max([x[1]+x[3] for x in vallas if x[2]=='|']+[x[1] for x in vallas if x[2]=='-']+[3])
w=int(caso.split()[0])
fp=subprocess.Popen(['./floodmapa'], shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
fp.stdin.write(caso+"\n")
r=fp.stdout.read().split()
miny=int(r.pop())
minx=int(r.pop())
canvas.delete("all")
canvas.config(width=factor+factor*(maxx-minx), height=factor+factor*(maxy-miny))
ii,jj=0,0
for i in r:
jj=0
for j in i:
if j=='0': canvas.create_rectangle(jj*factor, ii*factor, jj*factor+factor, ii*factor+factor, fill="white", width=0)
jj+=1
ii+=1
for v in vallas:
v[0]-=minx
v[1]-=miny
canvas.create_line(v[0]*factor,v[1]*factor,(v[0]+(v[2]=='-' and v[3] or 0))*factor,(v[1]+(v[2]=='|' and v[3] or 0))*factor,fill=(v[4]<w and 'gray70' or 'black'))
change()
Button(text="random",command=change).grid(row=0,column=1)
sp.grid(row=0,column=0)
canvas.grid(row=2,columnspan=2)
mainloop()
| [
[
1,
0,
0.0405,
0.0135,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0541,
0.0135,
0,
0.66,
0.0714,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0676,
0.0135,
0,
... | [
"from Tkinter import *",
"from random import *",
"from math import sqrt",
"import subprocess",
"def prueba(tamanio_entrada):\n\tcant=int(random()*tamanio_entrada)\n\tw=randint(3,int(2*sqrt(tamanio_entrada)))\n\th=tamanio_entrada/w\n\tvs=[]\n\tfor v in range(cant):\n\t\torient=choice(['-','|'])\n\t\tif orien... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('time_err.dat')
todo=fin.read().split('\n')
xs=[float(x.split()[0]) for x in todo if x]
ys=[float(x.split()[1]) for x in todo if x]
yerr=[float(x.split()[2]) for x in todo if x]
title("Tiempo de ejecucion de $flood$")
xlabel("Tamano de entrada")
ylabel("Tiempo de ejecucion")
errorbar(xs,ys,yerr,marker='_',color='k',ls='None')
plot(xs,[x*.00000035+.00004 for x in xs],label=r"$c \times n$")
legend(loc=0)
savefig('ej2_times.png',dpi=640./8)
show()
| [
[
1,
0,
0.1765,
0.0588,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2941,
0.0588,
0,
0.66,
0.0769,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3529,
0.0588,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('time_err.dat')",
"todo=fin.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo if x]",
"ys=[float(x.split()[1]) for x in todo if x]",
"yerr=[float(x.split()[2]) for x in todo if x]",
"title(\"Tiempo de ejecucion de $flood$\")",
"xlabel(\"Tamano de... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('counts.dat')
todo=fin.read().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 $flood$")
xlabel("Tamano de entrada")
ylabel("Cantidad de operaciones")
plot(xs,ys,'kx',label="__nolabel__")
plot(xs,[x*10+2000 for x in xs],label=r"$c \times n$")
legend(loc=0)
savefig('ej2_counts.png',dpi=640./8)
show()
| [
[
1,
0,
0.1875,
0.0625,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.3125,
0.0625,
0,
0.66,
0.0833,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.375,
0.0625,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('counts.dat')",
"todo=fin.read().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 $flood$\")",
"xlabel(\"Tamano de entrada\")",
"ylabel(\"Cantidad de operaciones\")"... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed,choice
from math import sqrt
seed(1234) # defino el seed para hacer el experimento reproducible
ejecutable="flood"
tamanios_entrada=sorted(range(100,5000)[::35])
def prueba(tamanio_entrada):
cant=int(random()*tamanio_entrada)
w=randint(3,int(2*sqrt(tamanio_entrada)))
h=tamanio_entrada/w
vs=[]
for v in range(cant):
orient=choice(['-','|'])
if orient=='|':
l=randint(1,int(h*.5))
x,y=randint(1,w),randint(1,h-l)
else:
l=randint(1,int(w*.5))
x,y=randint(1,w-l),randint(1,h)
ok=True
for v2 in vs:
if orient=='-':
if v2[2]=='-' and v2[1]==y and (x<v2[0]<x+l or x<v2[0]+v2[3]<x+l or v2[0]<x<v2[0]+v2[3] or v2[0]<x+l<v2[0]+v2[3] or x==v2[0]): ok=False
if orient=='|':
if v2[2]=='|' and v2[0]==x and (y<v2[1]<y+l or y<v2[1]+v2[3]<y+l or v2[1]<y<v2[1]+v2[3] or v2[1]<y+l<v2[1]+v2[3] or y==v2[1]): ok=False
if ok: vs.append((x,y,orient,l,randint(0,10)))
offsx,offsy=randint(0,800),randint(0,800)
return str(randint(0,10))+'\t'+str(len(vs))+'\n'+'\n'.join([str(v[0]+offsx)+' '+str(v[1]+offsy)+' '+v[2]+' '+str(v[3])+' '+str(v[4])+' ' for v in vs])
ender="-1 -1"
pruebas=[(n,prueba(n)) for n in tamanios_entrada]
open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas)) + '\n'+ender)
def runtest(pruebas,args):
fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for prueba in pruebas:
fp.stdin.write(prueba[1]+"\n") # le manda la instancia
r=fp.stdout.readline().rstrip() # recibo el resultado
print "tamanio: ",prueba[0]," ",args[0],"=",r
yield prueba[0],r # lo devuelvo
fp.stdin.write(ender+"\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)
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(pruebas,['time','0.05','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(pruebas,['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.0238,
0.0238,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0476,
0.0238,
0,
0.66,
0.1667,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.0714,
0.0238,
0,
... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed,choice",
"from math import sqrt",
"def prueba(tamanio_entrada):\n\tcant=int(random()*tamanio_entrada)\n\tw=randint(3,int(2*sqrt(tamanio_entrada)))\n\th=tamanio_entrada/w\n\tvs=[]\n\tfor v in range(cant):\n\t\torient=choice(['-... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed,choice
from math import sqrt
seed(1234) # defino el seed para hacer el experimento reproducible
ejecutable="flood"
tamanios_entrada=sorted(range(100,5000)[::35])
def prueba(tamanio_entrada):
cant=int(random()*tamanio_entrada)
w=randint(3,int(2*sqrt(tamanio_entrada)))
h=tamanio_entrada/w
vs=[]
for v in range(cant):
orient=choice(['-','|'])
if orient=='|':
l=randint(1,int(h*.5))
x,y=randint(1,w),randint(1,h-l)
else:
l=randint(1,int(w*.5))
x,y=randint(1,w-l),randint(1,h)
ok=True
for v2 in vs:
if orient=='-':
if v2[2]=='-' and v2[1]==y and (x<v2[0]<x+l or x<v2[0]+v2[3]<x+l or v2[0]<x<v2[0]+v2[3] or v2[0]<x+l<v2[0]+v2[3] or x==v2[0]): ok=False
if orient=='|':
if v2[2]=='|' and v2[0]==x and (y<v2[1]<y+l or y<v2[1]+v2[3]<y+l or v2[1]<y<v2[1]+v2[3] or v2[1]<y+l<v2[1]+v2[3] or y==v2[1]): ok=False
if ok: vs.append((x,y,orient,l,randint(0,10)))
offsx,offsy=randint(0,800),randint(0,800)
return str(randint(0,10))+'\t'+str(len(vs))+'\n'+'\n'.join([str(v[0]+offsx)+' '+str(v[1]+offsy)+' '+v[2]+' '+str(v[3])+' '+str(v[4])+' ' for v in vs])
ender="-1 -1"
pruebas=[(n,prueba(n)) for n in tamanios_entrada]
open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas)) + '\n'+ender)
def runtest(pruebas,args):
fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for prueba in pruebas:
fp.stdin.write(prueba[1]+"\n") # le manda la instancia
r=fp.stdout.readline().rstrip() # recibo el resultado
print "tamanio: ",prueba[0]," ",args[0],"=",r
yield prueba[0],r # lo devuelvo
fp.stdin.write(ender+"\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)
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(pruebas,['time','0.05','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(pruebas,['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.0238,
0.0238,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0476,
0.0238,
0,
0.66,
0.1667,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.0714,
0.0238,
0,
... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed,choice",
"from math import sqrt",
"def prueba(tamanio_entrada):\n\tcant=int(random()*tamanio_entrada)\n\tw=randint(3,int(2*sqrt(tamanio_entrada)))\n\th=tamanio_entrada/w\n\tvs=[]\n\tfor v in range(cant):\n\t\torient=choice(['-... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('time_err.dat')
todo=fin.read().split('\n')
xs=[float(x.split()[0]) for x in todo if x]
ys=[float(x.split()[1]) for x in todo if x]
yerr=[float(x.split()[2]) for x in todo if x]
title("Tiempo de ejecucion de $flood$")
xlabel("Tamano de entrada")
ylabel("Tiempo de ejecucion")
errorbar(xs,ys,yerr,marker='_',color='k',ls='None')
plot(xs,[x*.00000035+.00004 for x in xs],label=r"$c \times n$")
legend(loc=0)
savefig('ej2_times.png',dpi=640./8)
show()
| [
[
1,
0,
0.1765,
0.0588,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2941,
0.0588,
0,
0.66,
0.0769,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3529,
0.0588,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('time_err.dat')",
"todo=fin.read().split('\\n')",
"xs=[float(x.split()[0]) for x in todo if x]",
"ys=[float(x.split()[1]) for x in todo if x]",
"yerr=[float(x.split()[2]) for x in todo if x]",
"title(\"Tiempo de ejecucion de $flood$\")",
"xlabel(\"Tamano de... |
#!/usr/bin/env python
from Tkinter import *
from random import *
from math import sqrt
import subprocess
def prueba(tamanio_entrada):
cant=int(random()*tamanio_entrada)
w=randint(3,int(2*sqrt(tamanio_entrada)))
h=tamanio_entrada/w
vs=[]
for v in range(cant):
orient=choice(['-','|'])
if orient=='|':
l=randint(1,int(h*.5))
x,y=randint(1,w),randint(1,h-l)
else:
l=randint(1,int(w*.5))
x,y=randint(1,w-l),randint(1,h)
ok=True
for v2 in vs:
if orient=='-':
if v2[2]=='-' and v2[1]==y and (x<v2[0]<x+l or x<v2[0]+v2[3]<x+l or v2[0]<x<v2[0]+v2[3] or v2[0]<x+l<v2[0]+v2[3] or x==v2[0]): ok=False
if orient=='|':
if v2[2]=='|' and v2[0]==x and (y<v2[1]<y+l or y<v2[1]+v2[3]<y+l or v2[1]<y<v2[1]+v2[3] or v2[1]<y+l<v2[1]+v2[3] or y==v2[1]): ok=False
if ok: vs.append((x,y,orient,l,randint(0,10)))
offsx,offsy=randint(0,800),randint(0,800)
return str(randint(0,10))+'\t'+str(len(vs))+'\n'+'\n'.join([str(v[0]+offsx)+' '+str(v[1]+offsy)+' '+v[2]+' '+str(v[3])+' '+str(v[4])+' ' for v in vs])
factor=20
maxx,maxy,w=0,0,0
sp=Spinbox(from_=100,to=1000,increment=1)
canvas = Canvas(width=factor+factor*maxx, height=factor+factor*maxy, bg='lightblue')
def change():
global canvas
caso=prueba(int(sp.get()))
print caso
print
vallas=[[int(x[0])]+[int(x[1])]+[x[2]]+[int(x[3])]+[int(x[4])] for x in map(lambda x:x.split(),caso[1:].split('\n')) if len(x)==5]
maxx=max([x[0]+x[3] for x in vallas if x[2]=='-']+[x[0] for x in vallas if x[2]=='|']+[3])
maxy=max([x[1]+x[3] for x in vallas if x[2]=='|']+[x[1] for x in vallas if x[2]=='-']+[3])
w=int(caso.split()[0])
fp=subprocess.Popen(['./floodmapa'], shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
fp.stdin.write(caso+"\n")
r=fp.stdout.read().split()
miny=int(r.pop())
minx=int(r.pop())
canvas.delete("all")
canvas.config(width=factor+factor*(maxx-minx), height=factor+factor*(maxy-miny))
ii,jj=0,0
for i in r:
jj=0
for j in i:
if j=='0': canvas.create_rectangle(jj*factor, ii*factor, jj*factor+factor, ii*factor+factor, fill="white", width=0)
jj+=1
ii+=1
for v in vallas:
v[0]-=minx
v[1]-=miny
canvas.create_line(v[0]*factor,v[1]*factor,(v[0]+(v[2]=='-' and v[3] or 0))*factor,(v[1]+(v[2]=='|' and v[3] or 0))*factor,fill=(v[4]<w and 'gray70' or 'black'))
change()
Button(text="random",command=change).grid(row=0,column=1)
sp.grid(row=0,column=0)
canvas.grid(row=2,columnspan=2)
mainloop()
| [
[
1,
0,
0.0405,
0.0135,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0541,
0.0135,
0,
0.66,
0.0714,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0676,
0.0135,
0,
... | [
"from Tkinter import *",
"from random import *",
"from math import sqrt",
"import subprocess",
"def prueba(tamanio_entrada):\n\tcant=int(random()*tamanio_entrada)\n\tw=randint(3,int(2*sqrt(tamanio_entrada)))\n\th=tamanio_entrada/w\n\tvs=[]\n\tfor v in range(cant):\n\t\torient=choice(['-','|'])\n\t\tif orien... |
#!/usr/bin/env python
# coding: utf-8
from matplotlib.pyplot import *
fin=open('counts.dat')
todo=fin.read().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 $flood$")
xlabel("Tamano de entrada")
ylabel("Cantidad de operaciones")
plot(xs,ys,'kx',label="__nolabel__")
plot(xs,[x*10+2000 for x in xs],label=r"$c \times n$")
legend(loc=0)
savefig('ej2_counts.png',dpi=640./8)
show()
| [
[
1,
0,
0.1875,
0.0625,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.3125,
0.0625,
0,
0.66,
0.0833,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.375,
0.0625,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('counts.dat')",
"todo=fin.read().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 $flood$\")",
"xlabel(\"Tamano de entrada\")",
"ylabel(\"Cantidad de operaciones\")"... |
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.34,
0,
773,
3,
1,
0,
0,
890,
10,
1
],
[
14,
1,
0.1875,
0.0625,
1,
0.34,
... | [
"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.42,
0,
535,
3,
2,
0,
0,
0,
0,
3
],
[
8,
1,
0.1579,
0.0526,
1,
0.42,
... | [
"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.57,
0,
727,
4,
0,
0,
0,
0,
0,
0
],
[
6,
1,
0.5,
0.5,
1,
0.57,
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.93,
0,
51,
0,
0,
0,
0,
0,
8,
2
],
[
14,
1,
0.2308,
0.0769,
1,
0.93,
... | [
"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(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.