code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# -*- coding: utf-8 -*-
from sys import *
class ca:
a = set()
am = set()
def __hash__(self):
return 0
def __repr__(self):
rep = "(ATRIBUTO/S: "
for elem in self.a:
rep += elem+' '
rep += ", CIERRE:"
for elem in self.am:
rep += ' '+elem
rep += ')'
return rep
def __str__(self):
rep = "(ATRIBUTO/S: "
for elem in self.a:
rep += elem+' '
rep += ", CIERRE:"
for elem in self.am:
rep += ' '+elem
rep += ')'
return rep
def __cmp__(self,other):
assert type(other) == type(self)
#hay que retornar la negación aunque paresca loco
return (not(self.a == other.a and self.am == other.am))
def __init__(self,x,y):
assert type(x) == set and type(y) == set
self.a = x.copy()
self.am = y.copy()
| Python |
# -*- coding: utf-8 -*-
from df import *
# Aca vamos a definir todos los atributos, y una funcion nos va a devolver un
# set, que vendria a ser el Esquema universal
# TODO
def getEsquemaUniversal():
return set(['Planilla.Numero', 'Planilla.Fecha', 'Encuestado.Edad', \
'Encuestado.Sexo', 'Encuestado.Ingreso_mensual', \
'Encuestado.Profesion', 'Encuestado.Instruccion', \
'Encuestado.No_C.I.', 'Encuestado.Nombre_y_apellido', \
'Jefe_de_Grupo_Familiar.Fecha_de_nacimiento', \
'Jefe_de_Grupo_Familiar.Forma_de_cobro', \
'Jefe_de_Grupo_Familiar.¿Trabaja_actualmente?', \
'Jefe_de_Grupo_Familiar.Dedicacion_actual', \
'Jefe_de_Grupo_Familiar.E-mail', \
'Jefe_de_Grupo_Familiar.Telefono.Celular', \
'Jefe_de_Grupo_Familiar.Telefono.Habitacion', \
'Jefe_de_Grupo_Familiar.Telefono.Oficina', \
'Situacion_comunidad.Ventajas', \
'Situacion_comunidad.Desventajas', \
'Comunidad.Nombre', \
'Comunidad.Direccion.Nro', 'Comunidad.Direccion.Calle', \
'Sector.CP', \
'Municipio.Nombre', \
'Parroquia.Nombre', 'Estado.Nombre', \
'Situacion_Laboral.Tarjeta', \
'Situacion_Laboral.Ticket', \
'Situacion_Laboral.Cta_banco', \
'Situacion_Laboral.Ingreso_familiar', \
'Situacion_Laboral.Comercio_en_casa', \
'Situacion_Laboral.Trabajo', 'Vivienda.Mascotas', \
'Vivienda.Plagas', \
'Vivienda.Cond_salubridad', 'Vivienda.Enseres', \
'Vivienda.Techo', \
'Vivienda.Paredes', 'Vivienda.Terreno_propio', \
'Vivienda.Forma_tenencia', \
'Vivienda.Tipo', \
'Vivienda.OCV', 'Servicios.Servicios_comunales', \
'Servicios.Recoleccion_basura', \
'Servicios.Transporte', 'Servicios.Medios', \
'Servicios.Telefonia', \
'Servicios.Electricidad', 'Servicios.Gas', \
'Servicios.Aguas_servidas', \
'Servicios.Aguas_blancas', 'Salud.Historia_familiar', \
'Salud.Ayuda_especial', \
'Situacion_de_Exclusion.Tercera_edad', \
'Situacion_de_Exclusion.Discapacitados', \
'Situacion_de_Exclusion.Enfermedades_terminales', \
'Situacion_de_Exclusion.Indigentes', \
'Situacion_de_Exclusion.Niños_calle', \
'Participacion_Comunitaria.Propia', \
'Participacion_Comunitaria.Familia', \
'Participacion_Comunitaria.Org_Comunitarias', \
'Participacion_Comunitaria.Administracion', \
'Participacion_Comunitaria.Constitucion', \
'Participacion_Comunitaria.Sabe', \
'Participacion_Comunitaria.Apoya', \
'Participacion_Comunitaria.Área', \
'Participacion_Comunitaria.Misiones'])
# Funcion que devuelve el conjunto de dependencias funcionales
def getDepFunc ():
s = set ([df(set(['Planilla.Numero']),set(['Situacion_Laboral.Trabajo', \
'Situacion_Laboral.Comercio_en_casa', \
'Situacion_Laboral.Ingreso_familiar', \
'Situacion_Laboral.Cta_banco',\
'Situacion_Laboral.Tarjeta', \
'Situacion_Laboral.Ticket'])), \
df(set(['Planilla.Numero']),set(['Vivienda.Tipo', \
'Vivienda.Forma_tenencia', \
'Vivienda.Terreno_propio', \
'Vivienda.OCV','Vivienda.Techo', \
'Vivienda.Paredes', \
'Vivienda.Enseres', \
'Vivienda.Cond_salubridad', \
'Vivienda.Plagas', \
'Vivienda.Mascotas'])), \
df(set(['Planilla.Numero']),set(['Servicios.Aguas_blancas', \
'Servicios.Aguas_servidas', \
'Servicios.Gas', \
'Servicios.Electricidad', \
'Servicios.Recoleccion_basura', \
'Servicios.Telefonia', \
'Servicios.Transporte', \
'Servicios.Medios', \
'Servicios.Servicios_comunales'])), \
df(set(['Planilla.Numero']),set(['Participacion_Comunitaria.Org_Comunitarias', \
'Participacion_Comunitaria.Administracion', \
'Participacion_Comunitaria.Constitucion', \
'Participacion_Comunitaria.Propia', \
'Participacion_Comunitaria.Familia', \
'Participacion_Comunitaria.Misiones', \
'Participacion_Comunitaria.Sabe', \
'Participacion_Comunitaria.Apoya', \
'Participacion_Comunitaria.Área'])), \
df(set(['Planilla.Numero']),set(['Salud.Ayuda_especial', \
'Salud.Historia_familiar'])), \
df(set(['Planilla.Numero']),set(['Situacion_de_Exclusion.Niños_calle', \
'Situacion_de_Exclusion.Indigentes', \
'Situacion_de_Exclusion.Tercera_edad', \
'Situacion_de_Exclusion.Discapacitados', \
'Situacion_de_Exclusion.Enfermedades_terminales'])), \
df(set(['Encuestado.No_C.I.']),set(['Encuestado.Nombre_y_apellido', \
'Encuestado.Edad', \
'Encuestado.Sexo', \
'Encuestado.Ingreso_mensual', \
'Encuestado.Profesion', \
'Encuestado.Instruccion'])), \
df(set(['Encuestado.No_C.I.']),set(['Jefe_de_Grupo_Familiar.E-mail', \
'Jefe_de_Grupo_Familiar.Telefono.Celular', \
'Jefe_de_Grupo_Familiar.Telefono.Habitacion', \
'Jefe_de_Grupo_Familiar.Telefono.Oficina', \
'Jefe_de_Grupo_Familiar.Dedicacion_actual', \
'Jefe_de_Grupo_Familiar.¿Trabaja_actualmente?', \
'Jefe_de_Grupo_Familiar.Forma_de_cobro', \
'Jefe_de_Grupo_Familiar.Fecha_de_nacimiento'])), \
df(set(['Encuestado.No_C.I.']),set(['Situacion_comunidad.Ventajas', \
'Situacion_comunidad.Desventajas'])), \
df(set(['Planilla.Numero']),set(['Comunidad.Nombre', \
'Comunidad.Direccion.Nro', \
'Comunidad.Direccion.Calle'])), \
df(set(['Comunidad.Nombre']),set(['Sector.CP'])), \
df(set(['Municipio.Nombre']),set(['Estado.Nombre'])), \
# Cambiamos esta, ibamos antes a Municipio.Nombre, ahora a Sector.CP
df(set(['Parroquia.Nombre']),set(['Sector.CP'])), \
df(set(['Planilla.Numero']),set(['Encuestado.No_C.I.'])), \
df(set(['Encuestado.No_C.I.']),set(['Planilla.Numero'])), \
df(set(['Participacion_Comunitaria.Constitucion']),set(['Participacion_Comunitaria.Sabe'])), \
df(set(['Situacion_Laboral.Tarjeta']),set(['Situacion_Laboral.Cta_banco'])), \
# Estas se pasaron por alto!!!!! en la primera entrega
df(set(['Sector.CP']),set(['Municipio.Nombre'])), \
df(set(['Planilla.Numero']),set(['Planilla.Fecha'])), \
df(set(['Planilla.Numero']),set(['Parroquia.Nombre']))
])
return s
| Python |
# -*- coding: utf-8 -*-
from fprima import cierreAtributosAlfa
import copy
def calcular_FNBC (conjRi, Fpri, cierreAtr):
"""Descomposición en la forma normal de Boyce-Codd de un
conjunto de esquemas relacionales, para un F+ dado.
1º parámetro => conjunto de esquemas relacionales
2º parámetro => cierre del conj de dependencias funcionales
3º parametro => conj de cierres de los atributos"""
if (not (type(conjRi) is list)):
return "El 1º parametro debe ser una 'list' de 'sets'"
elif (not (type(Fpri) is set)):
return "El 2º parametro debe ser un 'set' de 'df'"
elif (not (type(cierreAtr) is dict)):
return "El 3º parametro debe ser un 'set' de 'tuplas'"
# ¿Revisamos los tipos del contenido de conjRi y Fpri?
stop = False
# copiamos los parámetros para modificarlos a gusto
F = Fpri.copy()
FNBC = []
FNBC.extend(conjRi)
while (not stop):
stop = True
for dep in F:
Ri = es_violac_FNBC (FNBC, dep, cierreAtr)
if Ri is not None: # Si hay violación en algun Ri
stop = False
print "\nSe halló que dep viola un Ri..."
print "dep = "+str(dep)+'\n'
convertir_FNBC (FNBC, Ri, dep)
return FNBC
def es_violac_FNBC (conjRi, dep, cierreAtr):
""" Indica si dep es violación de la descomposición conjRi.
Si así es devuelve el Ri violado. Sino regresa None """
for Ri in conjRi:
if (viola_FNBC (Ri, dep, cierreAtr)):
return Ri
# si no encontramos violación se retorna 'None'
def viola_FNBC (Ri, dep, cierreAtr):
""" Informa si la d.f. dep es violación FNBC para el esquema Ri """
if (not dep.alfa.issubset(Ri) or not dep.beta.issubset(Ri)):
return False
if (dep.beta.issubset(dep.alfa)):
# dependencia trivial => no hay violación FNBC
return False
for atr in cierreAtr:
# revisamos si la parte izquierda de la dep es superclave
if (dep.alfa == atr and Ri.issubset(cierreAtr[atr].union(atr)) ):
return False # es superclave => no hay violación FNBC
# si llegamos acá la dep no era trivial, ni superclave de Ri
# entonces dep es violación FNBC para Ri
return True
def convertir_FNBC (conjRi, Ri, dep):
""" Descompone Ri según la dependencia dep
para que deje de haber violación FNBC """
print "Descomponiendo Ri: "
conjRi.remove(Ri)
Rj = dep.alfa.union(dep.beta) # {a} U {b}
Ri = Ri.difference(dep.beta) # Ri - {b}
print "Descomposición obtenida:"
print "\tRj1 = "+str(Rj)
print "\tRj2 = "+str(Ri)
conjRi.append(Ri)
conjRi.append(Rj)
def chequear_FNBC (fPrima, conjRi, cierreAtr):
""" Determina si la descomposición conjRi respeta FNBC, según fPrima """
for dep in fPrima:
ri = es_violac_FNBC (conjRi, dep, cierreAtr)
if ri is not None:
#print "\nEl esquema "+str(ri)+" no respeta FNBC y "+str(dep.alfa)+"->"+str(dep.beta)+" es un testigo..."
return False # ri es una violación FNBC
# Si llegamos hasta acá, conjRi respeta FNBC
return True
def chequear_FNBC_df(F,conjR):
""" Determina si la descomposición conjR preserva las df de F """
for df in F: # Chequeamos que la descompoción conserve cada df
res = copy.deepcopy(df.alfa)
c = len(res) - 1
print "Pasada del def " , df
while c < len(res):
c = len(res)
for Ri in conjR:
cierre = cierreAtributosAlfa(res.intersection(Ri),F)
res.update(cierre.intersection(Ri))
print "Res += " , cierre.intersection(Ri)
if not df.beta.issubset(res):# beta no esta en res
return False
# Todos los beta estaban contenidos en res
return True
| Python |
# -*- coding: utf-8 *-*
import sys
import unittest
from tests.dijkstra import *
from tests.prim import *
from tests.kruskal import *
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 *-*
import unittest
from tests_algorithms import *
from tests_graphs import *
from tests_structures import *
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
from graphs.listgraph import *
from graphs.matrixgraph import *
from graphs.generator import *
from timeit import Timer
class Main():
def __init__(self):
self.repeat = 5
def log(self, message):
print message
def measure(self):
start = 500
delta = 100
num = 1
end = start + (num - 1) * delta
outputname = 'results.dense.' + str(start) + '.'
outputname += str(end) + '.txt'
self.logfile = open(outputname, 'w')
filenames = []
for i in range(num):
vertices = start + i * delta
filename = 'inputs/dense.' + str(vertices) + '.txt'
filenames.append(filename)
for i in range(num):
vertices = (i + 1) * delta
filename = 'inputs/sparse.' + str(vertices) + '.txt'
filenames.append(filename)
count = start
for filename in filenames:
output = str(count) + ';'
count += delta
self.log('-------------')
self.log(filename)
self.log('-------------')
# MatrixGraph - ListGraph - Dijkstra
graph_impl = 'MatrixGraph'
time = self.time_dijkstra(graph_impl, filename)
self.log(graph_impl + ' - dijkstra:' + str(time))
output += str(time) + ';'
graph_impl = 'ListGraph'
time = self.time_dijkstra(graph_impl, filename)
self.log(graph_impl + ' - dijkstra:' + str(time))
output += str(time) + ';'
# MatrixGraph - ListGraph - Prim
graph_impl = 'MatrixGraph'
time = self.time_prim(graph_impl, filename)
self.log(graph_impl + ' - prim:' + str(time))
output += str(time) + ';'
graph_impl = 'ListGraph'
time = self.time_prim(graph_impl, filename)
self.log(graph_impl + ' - prim:' + str(time))
output += str(time) + ';'
# MatrixGraph - ListGraph - Kruskal
graph_impl = 'MatrixGraph'
time = self.time_kruskal(graph_impl, filename)
self.log(graph_impl + ' - kruskal:' + str(time))
output += str(time) + ';'
graph_impl = 'ListGraph'
time = self.time_kruskal(graph_impl, filename)
self.log(graph_impl + ' - kruskal:' + str(time))
output += str(time) + ';'
output = output.replace('.', ',')
self.logfile.write(output + '\n')
self.logfile.close()
def time_dijkstra(self, implementation, filename):
setup = self.get_setup(implementation, filename)
setup += "index = graph.vertex_count() - 1\n"
setup += "destination = 'V' + str(index)\n"
code = "graph.run_dijkstra('V0', destination)"
return self.time(code, setup)
def time_kruskal(self, implementation, filename):
setup = self.get_setup(implementation, filename)
code = "graph.run_kruskal()"
return self.time(code, setup)
def time_prim(self, implementation, filename):
setup = self.get_setup(implementation, filename)
code = "graph.run_prim()"
return self.time(code, setup)
def get_setup(self, implementation, filename):
setup = "from graphs." + implementation.lower()
setup += " import " + implementation + "\n"
setup += "graph = " + implementation + "()\n"
setup += "graph.load('" + filename + "')\n"
return setup
def time(self, code, setup):
timer = Timer(code, setup)
return (timer.timeit(self.repeat) / self.repeat)
def generate_graphs(self):
gen = Generator()
densefactor = 0.5
sparsefactor = 0.01
vertices = 50
delta = 50
for i in range(50):
print 'Generating graphs with', vertices, 'vertices...'
filename = 'inputs/dense.' + str(vertices) + '.txt'
gen.generate(vertices, densefactor, filename)
filename = 'inputs/sparse.' + str(vertices) + '.txt'
gen.generate(vertices, sparsefactor, filename)
vertices += delta
def list_vs_array(self):
repeat = 100
setup = "from structures.list import List\n"
setup += "list = List()\n"
setup += "for i in range(100000):\n"
setup += " list.add(i)\n"
code = "for i in list:\n"
code += " pass"
timer = Timer(code, setup)
print 'list:', (timer.timeit(repeat) / repeat)
setup = "list = []\n"
setup += "for i in range(100000):\n"
setup += " list.append(i)\n"
code = "for i in list:\n"
code += " pass"
timer = Timer(code, setup)
print 'array:', (timer.timeit(repeat) / repeat)
def main(self):
self.measure()
# self.list_vs_array()
# self.generate_graphs()
if __name__ == '__main__':
main = Main()
main.main()
| Python |
# -*- coding: utf-8 -*-
import unittest
from structures.unionfind import UnionFind
class UnionFindTest(unittest.TestCase):
def test_create_unionfind(self):
unionfind = UnionFind(['V1', 'V2'])
self.assertEqual(2, unionfind.count())
def test_create_unionfind_union_check_count(self):
unionfind = UnionFind(['V1', 'V2'])
self.assertEqual(2, unionfind.count())
unionfind.union('V1', 'V2')
self.assertEqual(1, unionfind.count())
def test_build_example_from_book_check_count(self):
items = 'ijstuvwxyz'
unionfind = UnionFind(items)
self.assertEqual(len(items), unionfind.count())
unionfind.union(unionfind.find('w'), unionfind.find('u'))
unionfind.union(unionfind.find('s'), unionfind.find('u'))
unionfind.union(unionfind.find('t'), unionfind.find('v'))
unionfind.union(unionfind.find('z'), unionfind.find('v'))
unionfind.union(unionfind.find('i'), unionfind.find('x'))
unionfind.union(unionfind.find('y'), unionfind.find('j'))
unionfind.union(unionfind.find('x'), unionfind.find('j'))
self.assertEqual(3, unionfind.count())
unionfind.union(unionfind.find('u'), unionfind.find('v'))
self.assertEqual(2, unionfind.count())
| Python |
# -*- coding: utf-8 -*-
import unittest
from graphs.matrixgraph import MatrixGraph
class MatrixGraphTest(unittest.TestCase):
def setUp(self):
self.graph = MatrixGraph()
def test_add_two_vertices(self):
self.graph.add_vertex('V1')
self.graph.add_vertex('V2')
self.assertEqual(2, self.graph.vertex_count())
def test_add_fifteen_vertices(self):
n = 15
for i in range(n):
name = 'V' + str(i)
self.graph.add_vertex(name)
self.assertEqual(n, self.graph.vertex_count())
def test_add_vertices_add_edge_check_edge(self):
n = 15
for i in range(n):
name = 'V' + str(i)
self.graph.add_vertex(name)
self.graph.add_edge('V4', 'V5', 1)
weight = self.graph.get_edge('V4', 'V5')
self.assertEqual(1, weight)
def test_load(self):
self.graph.load('inputs/test1.txt')
self.assertEqual(6, self.graph.vertex_count())
self.assertEqual(1, self.graph.get_edge('s', 'u'))
self.assertEqual(2, self.graph.get_edge('s', 'v'))
self.assertEqual(4, self.graph.get_edge('s', 'x'))
self.assertEqual(1, self.graph.get_edge('u', 'x'))
self.assertEqual(3, self.graph.get_edge('u', 'y'))
self.assertEqual(2, self.graph.get_edge('v', 'x'))
self.assertEqual(3, self.graph.get_edge('v', 'z'))
self.assertEqual(1, self.graph.get_edge('x', 'y'))
self.assertEqual(2, self.graph.get_edge('x', 'z'))
| Python |
# -*- coding: utf-8 -*-
import unittest
from structures.hashtable import HashTable
class HashTableTest(unittest.TestCase):
def test_add_and_retrieve_item(self):
hash = HashTable()
key = "one"
hash.set(key, 1)
self.assertEqual(1, hash.get(key))
def test_add_and_retrieve_two_items(self):
pairs = [["one", 1], ["two", 2]]
hash = HashTable()
for pair in pairs:
key = pair[0]
data = pair[1]
hash.set(key, data)
count = 1
for pair in pairs:
key = pair[0]
self.assertEqual(count, hash.get(key))
count += 1
def test_add_and_retrieve_fifteen_items(self):
pairs = [["one", 1], ["two", 2], ["three", 3],
["four", 4], ["five", 5], ["six", 6],
["seven", 7], ["eight", 8], ["nine", 9],
["ten", 10], ["eleven", 11], ["twelve", 12],
["thirteen", 13], ["fourteen", 14], ["fifteen", 15]]
hash = HashTable()
for pair in pairs:
key = pair[0]
data = pair[1]
hash.set(key, data)
count = 1
for pair in pairs:
key = pair[0]
self.assertEqual(count, hash.get(key))
count += 1
def test_add_and_retrieve_fifteen_items_similar_keys(self):
hash = HashTable()
n = 100
for i in range(n):
key = 'V' + str(i)
hash.set(key, i)
for i in range(n):
key = 'V' + str(i)
self.assertEqual(i, hash.get(key))
def test_add__fifteen_items_similar_keys_retrieve_different(self):
hash = HashTable()
n = 100
for i in range(n):
key = 'V' + str(i)
hash.set(key, i)
self.assertEqual(None, hash['does not exist'])
self.assertEqual(None, hash['V101'])
self.assertEqual(None, hash['V1.1'])
def test_add_some_items_and_get_values_list(self):
hash = HashTable()
n = 15
for i in range(n):
key = 'V' + str(i)
hash.set(key, i)
values = hash.get_values()
self.assertEqual(n, len(values))
def test_add_items_to_force_rehashing_and_get_values_list(self):
hash = HashTable()
n = 1000
for i in range(n):
key = 'V' + str(i)
hash.set(key, i)
values = hash.get_values()
self.assertEqual(n, len(values))
| Python |
# -*- coding: utf-8 -*-
import unittest
from structures.list import List
class ListTest(unittest.TestCase):
def test_create_list_check_empty(self):
list = List()
self.assertTrue(list.empty())
def test_create_list_add_element_check_emtpy(self):
list = List()
list.add(1)
self.assertFalse(list.empty())
def test_add_two_items_pop_them_check_values_check_empty(self):
list = List()
list.add(1)
list.add(2)
value = list.pop()
self.assertEqual(2, value)
value = list.pop()
self.assertEqual(1, value)
self.assertTrue(list.empty())
def test_add_items_first_pop_them_check_values_check_empty(self):
list = List()
list.add_first(1)
list.add_first(2)
value = list.pop()
self.assertEqual(1, value)
value = list.pop()
self.assertEqual(2, value)
self.assertTrue(list.empty())
def test_add_items_use_iterator(self):
list = List()
list.add_first(1)
list.add_first(2)
list.add_first(3)
count = 0
for item in list:
count += 1
self.assertEqual(3, count)
| Python |
# -*- coding: utf-8 -*-
import unittest
from graphs.listgraph import ListGraph
class ListGraphTest(unittest.TestCase):
def setUp(self):
self.graph = ListGraph()
def test_add_two_vertices(self):
self.graph.add_vertex('V1')
self.graph.add_vertex('V2')
self.assertEqual(2, self.graph.vertex_count())
def test_add_fifteen_vertices(self):
n = 15
for i in range(n):
name = 'V' + str(i)
self.graph.add_vertex(name)
self.assertEqual(n, self.graph.vertex_count())
def test_add_vertices_add_edge_check_edge(self):
n = 15
for i in range(n):
name = 'V' + str(i)
self.graph.add_vertex(name)
self.graph.add_edge('V4', 'V5', 1)
weight = self.graph.get_edge('V4', 'V5')
self.assertEqual(1, weight)
self.assertEqual(1, self.graph.edge_count())
def test_load(self):
self.graph.load('inputs/test1.txt')
self.assertEqual(6, self.graph.vertex_count())
self.assertEqual(1, self.graph.get_edge('s', 'u'))
self.assertEqual(2, self.graph.get_edge('s', 'v'))
self.assertEqual(4, self.graph.get_edge('s', 'x'))
self.assertEqual(1, self.graph.get_edge('u', 'x'))
self.assertEqual(3, self.graph.get_edge('u', 'y'))
self.assertEqual(2, self.graph.get_edge('v', 'x'))
self.assertEqual(3, self.graph.get_edge('v', 'z'))
self.assertEqual(1, self.graph.get_edge('x', 'y'))
self.assertEqual(2, self.graph.get_edge('x', 'z'))
| Python |
# -*- coding: utf-8 *-*
import unittest
from graphs.listgraph import ListGraph
from graphs.matrixgraph import MatrixGraph
class DijkstraTest(unittest.TestCase):
def test_dijkstra_matrix(self):
self.run_test1(MatrixGraph())
self.run_test2(MatrixGraph())
self.run_test3(MatrixGraph())
def test_dijkstra_list(self):
self.run_test1(ListGraph())
self.run_test2(ListGraph())
self.run_test3(ListGraph())
def run_test1(self, graph):
graph.load('inputs/test1.txt')
path = graph.run_dijkstra('s', 'z')
self.assertEqual('s', path.pop_first())
self.assertEqual('u', path.pop_first())
self.assertEqual('x', path.pop_first())
self.assertEqual('z', path.pop_first())
def run_test2(self, graph):
graph.load('inputs/test2.txt')
path = graph.run_dijkstra('s', 'z')
self.assertEqual('s', path.pop_first())
self.assertEqual('u', path.pop_first())
self.assertEqual('v', path.pop_first())
self.assertEqual('x', path.pop_first())
self.assertEqual('y', path.pop_first())
self.assertEqual('z', path.pop_first())
def run_test3(self, graph):
graph = ListGraph()
graph.load('inputs/test3.txt')
path = graph.run_dijkstra('a', 'e')
self.assertEqual('a', path.pop_first())
self.assertEqual('c', path.pop_first())
self.assertEqual('e', path.pop_first())
| Python |
# -*- coding: utf-8 *-*
import unittest
from graphs.listgraph import ListGraph
from graphs.matrixgraph import MatrixGraph
class KruskalTest(unittest.TestCase):
def test_kruskal_matrix(self):
self.run_test1(MatrixGraph())
self.run_test2(MatrixGraph())
self.run_test3(MatrixGraph())
def test_kruskal_list(self):
self.run_test1(ListGraph())
self.run_test2(ListGraph())
self.run_test3(ListGraph())
def run_test1(self, graph):
graph.load('inputs/test1.txt')
count = graph.vertex_count() - 1
self.edges = graph.run_kruskal()
self.assertEqual(count, self.edges.count())
self.assertTrue(self.contains('s', 'u'))
self.assertTrue(self.contains('u', 'x'))
self.assertTrue(self.contains('x', 'y'))
self.assertTrue(self.contains('x', 'z'))
self.assertTrue(self.contains('s', 'v') or self.contains('v', 'x'))
def run_test2(self, graph):
graph.load('inputs/test2.txt')
count = graph.vertex_count() - 1
self.edges = graph.run_kruskal()
self.assertEqual(count, self.edges.count())
self.assertTrue(self.contains('s', 'u'))
self.assertTrue(self.contains('u', 'v'))
self.assertTrue(self.contains('v', 'x'))
self.assertTrue(self.contains('x', 'y'))
self.assertTrue(self.contains('y', 'z'))
def run_test3(self, graph):
graph.load('inputs/test3.txt')
count = graph.vertex_count() - 1
self.edges = graph.run_kruskal()
self.assertEqual(count, self.edges.count())
self.assertTrue(self.contains('a', 'b'))
self.assertTrue(self.contains('a', 'c'))
self.assertTrue(self.contains('c', 'd'))
self.assertTrue(self.contains('d', 'e'))
def contains(self, src, dest):
for edge in self.edges:
source = edge[0]
destination = edge[1]
if ((source == src and destination == dest) or
(source == dest and destination == src)):
return True
return False
| Python |
# -*- coding: utf-8 *-*
import unittest
from graphs.listgraph import ListGraph
from graphs.matrixgraph import MatrixGraph
class PrimTest(unittest.TestCase):
def test_prim_matrix(self):
self.run_test1(MatrixGraph())
self.run_test2(MatrixGraph())
self.run_test3(MatrixGraph())
def test_prim_list(self):
self.run_test1(ListGraph())
self.run_test2(ListGraph())
self.run_test3(ListGraph())
def run_test1(self, graph):
graph.load('inputs/test1.txt')
count = graph.vertex_count() - 1
self.edges = graph.run_prim()
self.assertEqual(count, self.edges.count())
self.assertTrue(self.contains('s', 'u'))
self.assertTrue(self.contains('u', 'x'))
self.assertTrue(self.contains('x', 'y'))
self.assertTrue(self.contains('x', 'z'))
self.assertTrue(self.contains('s', 'v') or self.contains('v', 'x'))
def run_test2(self, graph):
graph.load('inputs/test2.txt')
count = graph.vertex_count() - 1
self.edges = graph.run_prim()
self.assertEqual(count, self.edges.count())
self.assertTrue(self.contains('s', 'u'))
self.assertTrue(self.contains('u', 'v'))
self.assertTrue(self.contains('v', 'x'))
self.assertTrue(self.contains('x', 'y'))
self.assertTrue(self.contains('y', 'z'))
def run_test3(self, graph):
graph.load('inputs/test3.txt')
count = graph.vertex_count() - 1
self.edges = graph.run_prim()
self.assertEqual(count, self.edges.count())
self.assertTrue(self.contains('a', 'b'))
self.assertTrue(self.contains('a', 'c'))
self.assertTrue(self.contains('c', 'd'))
self.assertTrue(self.contains('d', 'e'))
def contains(self, src, dest):
for edge in self.edges:
source = edge[0]
destination = edge[1]
if ((source == src and destination == dest) or
(source == dest and destination == src)):
return True
return False
| Python |
# -*- coding: utf-8 -*-
import unittest
from structures.heap import Heap
class HeapTest(unittest.TestCase):
def test_add_n_elements_verify_order(self):
heap = Heap()
n = 65
#Insert elements in reverse order
for i in range(n):
heap.insert(n - i, n - i)
#Then verify they are extracted from min to max
min = None
while not heap.empty():
newmin = heap.extract_min()
if min is not None:
self.assertLessEqual(min, newmin)
min = newmin
def test_add_3_elements_change_key_verify_heap_order(self):
heap = Heap()
n = 3
#Insert elements in reverse order
for i in range(n):
heap.insert(n - i, n - i)
heap.change_data(0, 4)
heap.change_key(0, 4)
#Then verify they are extracted from min to max
min = None
while not heap.empty():
newmin = heap.extract_min()
if min is not None:
self.assertLessEqual(min, newmin)
min = newmin
| Python |
# -*- coding: utf-8 -*-
from structures.hashtable import HashTable
from structures.list import List
from structures.heap import Heap
from structures.unionfind import UnionFind
from graphs.graph import *
class MatrixGraph(Graph):
def __init__(self):
self.__adjacency = []
self.__vertices = HashTable()
def add_vertex(self, name):
self.__vertices[name] = self.__length()
self.__adjacency.append([None] * self.__length())
for i in range(self.__length()):
self.__adjacency[i].append(None)
def add_edge(self, source, dest, weight):
indexsource = self.__vertices[source]
indexdest = self.__vertices[dest]
if indexsource is not None and indexdest is not None:
self.__adjacency[indexsource][indexdest] = weight
else:
name = source
if indexdest is None:
name = dest
raise Exception("Vertex '" + name + "' doesn't exist")
def vertex_count(self):
return self.__length()
def edge_count(self):
count = 0
length = self.__length() - 1
for i in range(length):
for j in range(length):
if self.__adjacency[i][j] is not None:
count += 1
return count
def get_edge(self, source, dest):
indexsource = self.__vertices[source]
indexdest = self.__vertices[dest]
return self.__adjacency[indexsource][indexdest]
def __length(self):
return len(self.__adjacency)
def run_dijkstra(self, source, destination):
if self.__vertices[source] is None:
raise Exception('Source vertex does not exist!')
if self.__vertices[destination] is None:
raise Exception('Destination vertex does not exist!')
# Stores the name of the previous node for the key
previous = HashTable()
# Stores the calculated cost so far for each node
# from the source
cost = HashTable()
# Prority Queue
heap = Heap()
# Represents the value infinity
infinity = float("inf")
# Initialize all costs to infinity
for name in self.__vertices.get_keys():
cost[name] = infinity
# Set cost to source node to zero
# and add to heap
cost[source] = 0
heap.insert(cost[source], source)
# Count how many nodes have been added to S so far
count = 0
# While there are nodes missing
# and the heap is not empty (this condition is added
# in case the graph is not connected)
while count < self.vertex_count() and not heap.empty():
name = heap.extract_min()
count += 1
# Get index for vertex in matrix
index = self.__vertices[name]
# Look for adjacent nodes
for i in range(self.__length()):
weight = self.__adjacency[index][i]
if weight is not None:
# Calculate new cost
dest = self.__vertices.get_key(i)
newcost = cost[name] + weight
# Update cost if it's smaller and is not in S
if newcost < cost[dest]:
cost[dest] = newcost
previous[dest] = name
heap.insert(newcost, dest)
# Build path from registered previous vertices
path = List()
current = destination
while previous[current] is not None:
path.add_first(current)
current = previous[current]
#Add path source
path.add_first(source)
return path
def run_kruskal(self):
edges = List()
union = UnionFind(self.__vertices.get_keys())
heap = Heap()
#Add all edges to the priority queue
for name in self.__vertices.get_keys():
i = self.__vertices[name]
for j in range(self.__length()):
weight = self.__adjacency[i][j]
if weight is not None:
heap.insert(weight, [i, j, weight])
count = self.vertex_count() - 1
# While there is more than one component
# and the heap is not empty (this condition is added
# in case the graph is not connected)
edges = 0
while edges < count and not heap.empty():
edge = heap.extract_min()
source = self.__vertices.get_key(edge[0])
dest = self.__vertices.get_key(edge[1])
setsource = union.find(source)
setdest = union.find(dest)
if setsource != setdest:
union.union(setsource, setdest)
#edges.add([source, dest])
edges += 1
return edges
def run_prim(self):
edges = List()
cost = HashTable()
heap = Heap()
previous = HashTable()
infinity = float("inf")
for name in self.__vertices.get_keys():
cost[name] = infinity
source = self.__vertices.get_keys()[0]
cost[source] = 0
heap.insert(cost[source], source)
count = 0
while count < self.vertex_count() and not heap.empty():
name = heap.extract_min()
index = self.__vertices[name]
count += 1
# Look for adjacent nodes
for i in range(self.__length()):
weight = self.__adjacency[index][i]
if weight is not None:
dest = self.__vertices.get_key(i)
newcost = weight
if newcost < cost[dest]:
cost[dest] = newcost
previous[dest] = [name, dest]
heap.insert(newcost, dest)
for name in self.__vertices.get_keys():
if previous[name] is not None:
edges.add(previous[name])
return edges
def to_string(self):
output = ''
for i in range(self.__length()):
output += self.__vertices.get_keys()[i] + ': '
for j in range(self.__length()):
edge = self.__adjacency[i][j]
destination = edge[1]
weight = edge[2]
if edge is not None:
output += '(' + destination + ', '
output += str(weight) + ') '
output += '\n'
return output
def save(self, filename):
file = open(filename, 'w')
for name in self.__vertices.get_keys():
rowIndex = self.__vertices.get_key_index(name)
file.write(name + Graph.NAME_SEPARATOR)
count = 0
for colIndex in range(self.__length()):
weight = self.__adjacency[rowIndex][colIndex]
if weight is not None:
if count != 0:
file.write(Graph.ADJ_LIST_SEPARATOR)
file.write(str(colIndex) + Graph.WEIGHT_SEPARATOR)
file.write(str(weight))
count += 1
file.write('\n')
file.close()
def load(self, filename):
file = open(filename)
adj = HashTable()
for line in file:
pair = line.split(Graph.NAME_SEPARATOR)
name = pair[0].strip()
adjlist = pair[1].strip()
self.add_vertex(name)
adj[name] = adjlist
for name in self.__vertices.get_keys():
list = adj[name]
edges = list.split(Graph.ADJ_LIST_SEPARATOR)
for edge in edges:
edge = edge.strip()
if len(edge) > 0:
words = edge.split(Graph.WEIGHT_SEPARATOR)
destIndex = int(words[0].strip())
dest = self.__vertices.get_key(destIndex)
weight = None
weight = int(words[1])
self.add_edge(name, dest, weight)
file.close()
| Python |
# -*- coding: utf-8 -*-
from structures.list import List
from structures.heap import Heap
from structures.unionfind import UnionFind
from graphs.graph import *
class ListGraph(Graph):
def __init__(self, size=None):
self.__vertices = HashTable(size)
def add_vertex(self, name):
self.__vertices[name] = List()
def add_edge(self, src, dest, weight=None):
adjacents = self.__vertices[src]
exists = False
for edge in adjacents:
edgeDest = self.__vertices.get_key(edge[0])
if dest == edgeDest:
exists = True
break
if not exists:
destIndex = self.__vertices.get_key_index(dest)
edge = [destIndex, weight]
adjacents.add(edge)
def get_edge(self, src, dest):
adjacents = self.__vertices[src]
for edge in adjacents:
edgeDest = self.__vertices.get_key(edge[0])
if edgeDest == dest:
return edge[1]
return None
def vertex_count(self):
return self.__vertices.count()
def edge_count(self):
count = 0
for name in self.__vertices.get_keys():
adjacents = self.__vertices[name]
count += adjacents.count()
return count
def get_vertex(self, index):
return self.__vertices.get_key(index)
def run_dijkstra(self, source, destination):
if self.__vertices[source] is None:
raise Exception('Source vertex does not exist!')
if self.__vertices[destination] is None:
raise Exception('Destination vertex does not exist!')
# Stores the name of the previous node for the key
previous = HashTable()
# Stores the calculated distance so far for each node
# from the source
cost = HashTable()
# Prority Queue
heap = Heap()
# Represents the value infinity
infinity = float("inf")
# Initialize all costs to infinity
for name in self.__vertices.get_keys():
cost[name] = infinity
# Set the cost to source node to zero
# and add to heap
cost[source] = 0
heap.insert(cost[source], source)
# Count how many nodes have been added to S so far
count = 0
# While there are nodes missing
# and the heap is not empty (this condition is added
# in case the graph is not connected)
while count < self.vertex_count() and not heap.empty():
name = heap.extract_min()
count += 1
# Get vertex
adjacents = self.__vertices[name]
# Look for adjacent nodes
for edge in adjacents:
# Calculate new cost
dest = self.__vertices.get_key(edge[0])
weight = edge[1]
newcost = cost[name] + weight
# Update cost if it's smaller
if newcost < cost[dest]:
cost[dest] = newcost
previous[dest] = name
heap.insert(newcost, dest)
# Build path from registered previous vertices
path = List()
current = destination
while previous[current] is not None:
path.add_first(current)
current = previous[current]
path.add_first(source)
return path
def run_kruskal(self):
edges = List()
union = UnionFind(self.__vertices.get_keys())
heap = Heap()
#Add all edges to the priority queue
indexSrc = 0
for name in self.__vertices.get_keys():
adjacents = self.__vertices[name]
for edge in adjacents:
weight = edge[1]
indexDest = edge[0]
heap.insert(weight, [indexSrc, indexDest])
indexSrc += 1
count = self.vertex_count() - 1
edges = 0
# While there is more than one component
# and the heap is not empty (this condition is added
# in case the graph is not connected)
while edges < count and not heap.empty():
edge = heap.extract_min()
source = self.__vertices.get_key(edge[0])
destination = self.__vertices.get_key(edge[1])
setsource = union.find(source)
setdest = union.find(destination)
if setsource != setdest:
union.union(setsource, setdest)
#edges.add(edge)
edges += 1
return edges
def run_prim(self):
edges = List()
cost = HashTable()
heap = Heap()
previous = HashTable()
infinity = float("inf")
for name in self.__vertices.get_keys():
cost[name] = infinity
source = self.__vertices.get_keys()[0]
cost[source] = 0
heap.insert(cost[source], source)
count = 0
while count < self.vertex_count() and not heap.empty():
name = heap.extract_min()
adjacents = self.__vertices[name]
count += 1
for edge in adjacents:
newcost = edge[1]
dest = self.__vertices.get_key(edge[0])
if newcost < cost[dest]:
cost[dest] = newcost
previous[dest] = [name, dest]
heap.insert(newcost, dest)
for name in self.__vertices.get_keys():
if previous[name] is not None:
edges.add(previous[name])
return edges
def to_string(self):
output = ''
for name in self.__vertices.get_keys():
adjacents = self.__vertices[name]
output += name + ':'
if adjacents.count() > 0:
for edge in adjacents:
output += '(' + edge[0] + ', '
output += str(edge[1]) + ') '
output += '\n'
return output
def save(self, filename):
file = open(filename, 'w')
for name in self.__vertices.get_keys():
adjacents = self.__vertices[name]
file.write(name + Graph.NAME_SEPARATOR)
if adjacents.count() > 0:
count = 0
for edge in adjacents:
destinationIndex = edge[0]
weight = edge[1]
if count != 0:
file.write(Graph.ADJ_LIST_SEPARATOR)
file.write(str(destinationIndex) + Graph.WEIGHT_SEPARATOR)
file.write(str(weight))
count += 1
file.write('\n')
file.close()
def load(self, filename):
file = open(filename)
for line in file:
pair = line.split(Graph.NAME_SEPARATOR)
name = pair[0].strip()
list = pair[1].strip()
self.add_vertex(name)
edges = list.split(Graph.ADJ_LIST_SEPARATOR)
for edge in edges:
edge = edge.strip()
if len(edge) > 0:
words = edge.split(Graph.WEIGHT_SEPARATOR)
index = int(words[0].strip())
weight = int(words[1])
self.__vertices[name].add([index, weight])
file.close()
| Python |
# -*- coding: utf-8 -*-
from graphs.matrixgraph import MatrixGraph
import random
import math
class Generator():
def __init__(self):
pass
def generate(self, vcount, factor, filename):
if factor > 1:
raise Exception('Invalid density factor.')
maxedges = (vcount - 1) * vcount
ecount = int(maxedges * factor)
if ecount < vcount:
ecount = vcount
# if ecount > 10000:
# ecount = 10000
# print 'Going for', ecount, 'edges.'
graph = MatrixGraph()
for i in range(vcount):
name = 'V' + str(i)
graph.add_vertex(name)
#self.random_generation(graph, vcount, ecount)
self.secuential_generation(graph, vcount, ecount)
graph.save(filename)
def random_generation(self, graph, vcount, ecount):
for i in range(ecount):
while True:
edge = self.random_edge(vcount)
if graph.get_edge(edge[0], edge[1]) is None:
graph.add_edge(edge[0], edge[1], edge[2])
break
else:
print 'This edge already exists. Try again.'
print edge[0], edge[1], graph.edge_count()
def secuential_generation(self, graph, vcount, ecount):
edgespervertex = int(math.ceil(ecount / vcount))
vdelta = int(vcount / edgespervertex)
for src in range(vcount):
if src % 100 == 0:
print src
for dest in range(src + 1, vcount + src + 1, vdelta):
if dest >= vcount:
dest = dest - vcount
if src != dest:
weight = random.randint(0, 10)
source = 'V' + str(src)
destination = 'V' + str(dest)
#print source, '-', destination, ':', weight
graph.add_edge(source, destination, weight)
def random_edge(self, vcount, src=None):
if src is None:
src = random.randint(0, vcount - 1)
dest = src
while dest == src:
dest = random.randint(0, vcount - 1)
weight = random.randint(0, 10)
src = 'V' + str(src)
dest = 'V' + str(dest)
return [src, dest, weight]
| Python |
# -*- coding: utf-8 -*-
from structures.hashtable import HashTable
class Graph():
NAME_SEPARATOR = '->'
ADJ_LIST_SEPARATOR = '||'
WEIGHT_SEPARATOR = ';'
def __init__(self):
pass
def load(self, filename):
pass
def save(self, filename):
raise Exception('save() not implemented.')
def show(self):
print self.to_string()
def add_vertex(self, name):
pass
def add_edge(self, source, destination, weight):
pass
def vertex_count(self):
pass
def edge_count(self):
pass
def run_kruskal(self):
pass
def run_prim(self):
pass
def run_dijkstra(self, source, destination):
pass
| Python |
# -*- coding: utf-8 -*-
import sys
import unittest
from tests.matrixgraph import *
from tests.listgraph import *
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
import sys
import unittest
from tests.hashtable import *
from tests.heap import *
from tests.unionfind import *
from tests.list import *
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
from structures.hashtable import HashTable
class UnionFind():
def __init__(self, items):
self.sets = HashTable()
for item in items:
node = [item, None, 1]
self.sets[item] = node
self.__count = len(items)
def find(self, item):
node = self.sets[item]
while node[1] is not None:
node = node[1]
return node[0]
def union(self, item1, item2):
if item1 != item2:
node1 = self.sets[item1]
node2 = self.sets[item2]
if node1[2] < node2[2]:
node1[1] = node2
node2[2] += node1[2]
else:
node2[1] = node1
node1[2] += node2[2]
self.__count -= 1
def count(self):
return self.__count
#class UnionFindNode():
#
# def __init__(self, item):
# self.item = item
# self.set = None
# self.size = 1
| Python |
# -*- coding: utf-8 -*-
class HashTable():
__initial_size = 10000
def __init__(self, size=None):
self.__size = size
if size is None:
self.__size = HashTable.__initial_size
self.items = [None] * self.__size
self.__keys = []
def count(self):
return len(self.__keys)
def set(self, key, value):
keyIndex = self.count()
self.__keys.append(key)
if self.count() > 0.7 * self.__size:
self.__rehash()
index = self.__get_index(key)
item = self.items[index]
if item is None:
self.items[index] = [keyIndex, value]
elif self.__keys[item[0]] == key:
item[1] = value
def get(self, key):
index = self.__get_index(key)
value = None
if index is not None and self.items[index] is not None:
value = self.items[index][1]
return value
def get_values(self):
values = []
for item in self.items:
if item is not None:
values.append(item[1])
return values
def get_keys(self):
return self.__keys
def get_key(self, index):
return self.__keys[index]
def get_key_index(self, key):
index = self.__get_index(key)
item = self.items[index]
return item[0]
def __get_index(self, key):
"Used linear probing."
index = self.__primary_hash(key) % self.__size
if self.__collision(key, index):
index = self.__secondary_hash(key) % self.__size
pos = 0
while self.__collision(key, index):
index += 1
index %= self.__size
pos += 1
return index
def __collision(self, key, index):
item = self.items[index]
return (item is not None and self.__keys[item[0]] != key)
def __get_hash(self, key, pos=0):
hash = self.__primary_hash(key)
hash += pos * self.__secondary_hash(key)
return hash
def __primary_hash(self, key):
"Used FNV hash function"
key = str(key)
h = 2166136261
for letter in key:
h = (h * 16777619) ^ ord(letter)
return h
def __secondary_hash(self, key):
"Shift-Add-XOR hash function"
key = str(key)
h = 0
for letter in key:
h ^= (h << 5) + (h >> 2) + ord(letter)
return h
def __rehash(self):
max_capacity = self.__size
occupied = self.count() * 100 / self.__size
# print self.count(), 'items of total capacity', max_capacity
# print 'percentage:', occupied
olditems = self.items
factor = 2
if self.count() < 50000:
factor = 4
self.__size = int(factor * self.__size)
self.items = [None] * self.__size
# print 'rehashing to', self.__size, 'buckets'
for item in olditems:
if item is not None:
itemKey = self.__keys[item[0]]
index = self.__get_index(itemKey)
self.items[index] = item
# print 'finished rehashing'
# print '--------------------------'
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
| Python |
# -*- coding: utf-8 -*-
class List():
def __init__(self):
self.__begin = None
self.__end = None
self.__current = None
self.__size = 0
def empty(self):
return self.__size == 0
def pop(self):
return self.pop_last()
def pop_last(self):
item = None
if self.__end is not None:
self.__size -= 1
item = self.__end[0]
if self.__end[1] is not None:
prev = self.__end[1]
prev[2] = None
self.__end = prev
elif self.__begin is None:
self.__end = None
self.__begin = None
return item
def pop_first(self):
item = None
if self.__begin is not None:
self.__size -= 1
item = self.__begin[0]
if self.__begin[2] is not None:
next = self.__begin[2]
next[1] = None
self.__begin = next
else:
self.__end = None
self.__begin = None
return item
def add(self, item):
self.add_last(item)
def add_first(self, item):
self.__size += 1
node = [item, None, None]
if self.__begin is None:
self.__begin = node
self.__end = node
else:
node[2] = self.__begin
node[1] = None
self.__begin[1] = node
self.__begin = node
def add_last(self, item):
self.__size += 1
node = [item, None, None]
if self.__end is None:
self.__begin = node
self.__end = node
else:
node[1] = self.__end
node[2] = None
self.__end[2] = node
self.__end = node
def get_first(self):
return self.__begin
def get_last(self):
return self.__end
def next(self):
if self.__current is not None:
self.__current = self.__current[2]
return self.__current
def prev(self):
if self.__current is not None:
this.__current = self.__current[1]
return self.__current
def current(self):
return self.__current
def count(self):
return self.__size
def reset(self):
self.__current = self.__begin
def __iter__(self):
return ListIterator(self)
def to_string(self):
output = ''
for item in self:
value = str(item[0])
if value is None:
value = ''
output += value + ';'
return output
#class ListNode:
#
# def __init__(self, item):
# self.item = item
# self.next = None
# self.prev = None
class ListIterator:
def __init__(self, list):
self.list = list
self.list.reset()
def next(self):
node = self.list.current()
item = None
if node is not None:
item = node[0]
else:
raise StopIteration
self.list.next()
return item
def __iter__(self):
return self
| Python |
# -*- coding: utf-8 -*-
class Heap():
__maxSize = 100
def __init__(self):
self.items = []
def insert(self, key, data):
item = [key, data]
self.items.append(item)
index = len(self.items) - 1
self.__heapify_up(index)
def change_key(self, index, key):
self.items[index][0] = key
self.__heapify(index)
def change_data(self, index, data):
self.items[index][1] = data
self.__heapify(index)
def extract_min(self):
min = self.items[0]
self.__delete(0)
return min[1]
def empty(self):
return self.__length() == 0
def __delete(self, index):
item = self.items.pop()
if index < self.__length():
self.items[index] = item
self.__heapify(index)
def __heapify(self, index):
parent = self.__parent(index)
if self.items[index][0] < self.items[parent][0]:
self.__heapify_up(index)
else:
self.__heapify_down(index)
def __heapify_up(self, index):
if index > 0:
parent = self.__parent(index)
if self.items[index][0] < self.items[parent][0]:
self.__swap(index, parent)
self.__heapify_up(parent)
def __heapify_down(self, index):
length = self.__length()
left = self.__left(index)
right = self.__right(index)
#Verify if current has children
if left >= length:
return
#Verify if current has right child
elif right < length:
leftChild = self.items[left]
rightChild = self.items[right]
if leftChild[0] < rightChild[0]:
min = left
else:
min = right
#Then only left child exists
elif left == length - 1:
min = left
else:
raise Exception('There something wrong!')
item = self.items[index]
child = self.items[min]
if child[0] < item[0]:
self.__swap(index, min)
self.__heapify_down(min)
def __swap(self, i, j):
"Swaps nodes in the heap"
temp = self.items[i]
self.items[i] = self.items[j]
self.items[j] = temp
def __length(self):
"Returns the number of elements in the heap"
return len(self.items)
def __item(self, index):
item = None
if index < self.__length():
item = self.items[index]
return item
def __left(self, index):
return (2 * index) + 1
def __right(self, index):
return (2 * index) + 2
def __parent(self, index):
if index == 0:
return 0
elif index % 2 == 0:
return index / 2 - 1
else:
return index / 2
def size(self):
return self.__length()
def show(self):
for index in range(self.__length()):
item = self.__item(index)
left = self.__item(self.__left(index))
right = self.__item(self.__right(index))
output = str(item[0])
if left is not None:
output += ' (left=' + str(left[0]) + ')'
if right is not None:
output += ' (right=' + str(right[0]) + ')'
print output
print '---------------------------'
| Python |
# -*- coding: utf-8 *-*
class DBActors():
def __init__(self, filename):
self.filename = filename
self.file = None
self.currentline = None
def open(self):
if self.file is None:
self.file = open(self.filename)
# Read file until the start of actor/actress list
while self.currentline != '---- ------\n':
self.currentline = self.file.readline()
else:
raise Exception('Already opened!')
def close(self):
self.file.close()
self.file = None
def next(self):
self.currentline = self.file.readline()
if self.finished():
return None, None
parts = self.currentline.split('\t')
actor = None
title = None
if self.is_actor_line():
actor = parts[0].strip()
title = self.get_movie_name(parts, 1)
elif self.is_movie_line():
title = self.get_movie_name(parts)
return actor, title
def finished(self):
return self.end_of_db() or self.end_of_list()
def end_of_db(self):
return self.currentline == ''
def end_of_list(self):
return self.currentline.startswith('---------------------------------')
def is_actor_line(self):
first = self.currentline[0]
return first != '\t' and first != '\n'
def is_movie_line(self):
return self.currentline[0] == '\t'
def find_non_empty(self, parts, startat=0):
for index in range(startat, len(parts)):
part = parts[index]
if part != '':
return part
def get_movie_name(self, parts, startat=0):
title = self.find_non_empty(parts, startat)
characterStart = title.find('[')
creditStart = title.find('<')
if characterStart > 0:
title = title[:characterStart]
elif creditStart > 0:
title = title[:creditStart]
return title.strip()
| Python |
# -*- coding: utf-8 *-*
from structures.hashtable import HashTable
class Actor():
def __init__(self, name):
self.name = name
self.__titlesHash = HashTable()
self.titles = []
def add_title(self, title):
if self.__titlesHash[title] is None:
self.__titlesHash[title] = True
self.titles.append(title)
def to_string(self):
output = self.name + ':'
for title in self.titles:
output += ' ' + title + ';'
return output
| Python |
# -*- coding: utf-8 *-*
from structures.hashtable import HashTable
class Movie():
def __init__(self, title):
self.title = title
self.actors = HashTable()
def add_actor(self, actor):
if self.actors[actor] is None:
self.actors[actor] = True
| Python |
# -*- coding: utf-8 *-*
from graphs.listgraph import *
def add_edge(g, src, dest):
g.add_edge(src, dest, 1)
g.add_edge(dest, src, 1)
def generate_test1():
graph = ListGraph()
graph.add_vertex('A')
graph.add_vertex('B')
graph.add_vertex('C')
graph.add_vertex('D')
graph.add_vertex('E')
graph.add_vertex('F')
graph.add_vertex('G')
add_edge(graph, 'A', 'B')
add_edge(graph, 'A', 'C')
add_edge(graph, 'A', 'D')
add_edge(graph, 'B', 'E')
add_edge(graph, 'C', 'F')
add_edge(graph, 'F', 'G')
graph.save('inputs/test1.txt')
def generate_test2():
graph = ListGraph()
graph.add_vertex('A')
graph.add_vertex('B')
graph.add_vertex('C')
graph.add_vertex('D')
add_edge(graph, 'A', 'B')
add_edge(graph, 'A', 'C')
add_edge(graph, 'A', 'D')
add_edge(graph, 'B', 'C')
add_edge(graph, 'B', 'D')
add_edge(graph, 'C', 'D')
graph.save('inputs/test2.txt')
def generate_test3():
graph = ListGraph()
graph.add_vertex('A')
graph.add_vertex('B')
graph.add_vertex('C')
graph.add_vertex('D')
add_edge(graph, 'B', 'C')
add_edge(graph, 'B', 'D')
add_edge(graph, 'C', 'D')
graph.save('inputs/test3.txt')
def generate_test4():
graph = ListGraph()
graph.add_vertex('A')
graph.add_vertex('B')
graph.add_vertex('C')
graph.add_vertex('D')
add_edge(graph, 'A', 'B')
add_edge(graph, 'B', 'C')
add_edge(graph, 'C', 'D')
graph.save('inputs/test4.txt')
generate_test1()
generate_test2()
generate_test3()
generate_test4()
| Python |
# -*- coding: utf-8 *-*
import sys
import unittest
from tests.dijkstra import *
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 *-*
import unittest
from tests_algorithms import *
from tests_graphs import *
from tests_structures import *
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 *-*
from graphs.matrixgraph import *
from graphs.listgraph import *
from structures.hashtable import HashTable
from imdb.dbactors import DBActors
# Total
# Around 1450000 actors
# Around 819000 actresses
# RAM: 524.8 MB
class Main():
def __init__(self):
pass
def main(self):
filenames = ['C:/Juan/imdb/actors.list', 'C:/Juan/imdb/actresses.list']
graphfilename = 'C:/Juan/imdb/imdb.graph.txt'
# self.generate_graph(filenames, graphfilename)
self.query_graph(graphfilename)
def query_graph(self, graphfilename):
print 'Loading graph', graphfilename, '...'
graph = ListGraph(3000000)
graph.load(graphfilename)
input = None
while input != 'quit':
print '------------------------------------------------'
input = raw_input("Enter action ['query' or 'quit']: ")
print '------------------------------------------------'
if input == 'query':
actor = raw_input("Enter actors name: ")
distance = raw_input("Enter minimum distance: ")
d = int(distance)
try:
print 'Processing, please wait...'
actors = graph.run_dijkstra(actor, d)
result = 'There are ' + str(actors.count()) + ' actors'
result += ' farther than ' + distance
result += ' from ' + actor
print result
except Exception:
print 'Invalid actors.'
print 'Thank you, come back soon!'
def generate_graph(self, filenames, outputfilename):
print 'Generating graph...'
graph = ListGraph(3000000)
movies = HashTable(3000000)
for filename in filenames:
print "Processing ", filename
dbactors = DBActors(filename)
dbactors.open()
currentactor = None
num = 0
while not dbactors.finished():
# Get actor and movie from line
actor, title = dbactors.next()
if actor is not None:
indexcurrentactor = graph.vertex_count()
graph.add_vertex(actor)
# Print counter and verify if maximum reached
num += 1
if num % 1000 == 0:
print num
if num > 1000 * 100:
break
if title is not None:
movie = movies[title]
if movie is None:
movie = HashTable()
movies[title] = movie
if indexcurrentactor is not None:
movie[indexcurrentactor] = None
else:
raise Exception('Oh no! Current actor is null!')
dbactors.close()
for movie in movies.get_values():
actors = movie.get_keys()
for indexsrc in actors:
for indexdest in actors:
if indexsrc != indexdest:
src = graph.get_vertex(indexsrc)
dest = graph.get_vertex(indexdest)
graph.add_edge(src, dest, 1)
graph.save(outputfilename)
def generate_list(self, filename):
actors = open(filename + '.txt', 'w+')
dbactors = DBActors(filename)
dbactors.open()
while not dbactors.finished():
actor, title = dbactors.next()
if actor is not None:
actors.write('\n')
actors.write(actor + ': ')
if title is not None:
actors.write(title + '; ')
actors.close()
def preview(self, filename, numlines=1000):
file = open(filename)
for i in range(numlines):
print file.readline()
file.close()
if __name__ == '__main__':
main = Main()
main.main()
| Python |
# -*- coding: utf-8 -*-
import unittest
from structures.unionfind import UnionFind
class UnionFindTest(unittest.TestCase):
def test_create_unionfind(self):
unionfind = UnionFind(['V1', 'V2'])
self.assertEqual(2, unionfind.count())
def test_create_unionfind_union_check_count(self):
unionfind = UnionFind(['V1', 'V2'])
self.assertEqual(2, unionfind.count())
unionfind.union('V1', 'V2')
self.assertEqual(1, unionfind.count())
def test_build_example_from_book_check_count(self):
items = 'ijstuvwxyz'
unionfind = UnionFind(items)
self.assertEqual(len(items), unionfind.count())
unionfind.union(unionfind.find('w'), unionfind.find('u'))
unionfind.union(unionfind.find('s'), unionfind.find('u'))
unionfind.union(unionfind.find('t'), unionfind.find('v'))
unionfind.union(unionfind.find('z'), unionfind.find('v'))
unionfind.union(unionfind.find('i'), unionfind.find('x'))
unionfind.union(unionfind.find('y'), unionfind.find('j'))
unionfind.union(unionfind.find('x'), unionfind.find('j'))
self.assertEqual(3, unionfind.count())
unionfind.union(unionfind.find('u'), unionfind.find('v'))
self.assertEqual(2, unionfind.count())
| Python |
# -*- coding: utf-8 -*-
import unittest
from graphs.matrixgraph import MatrixGraph
class MatrixGraphTest(unittest.TestCase):
def setUp(self):
self.graph = MatrixGraph()
def test_add_two_vertices(self):
self.graph.add_vertex('V1')
self.graph.add_vertex('V2')
self.assertEqual(2, self.graph.vertex_count())
def test_add_fifteen_vertices(self):
n = 15
for i in range(n):
name = 'V' + str(i)
self.graph.add_vertex(name)
self.assertEqual(n, self.graph.vertex_count())
def test_add_vertices_add_edge_check_edge(self):
n = 15
for i in range(n):
name = 'V' + str(i)
self.graph.add_vertex(name)
self.graph.add_edge('V4', 'V5', 1)
weight = self.graph.get_edge('V4', 'V5')
self.assertEqual(1, weight)
def test_load(self):
self.graph.load('inputs/test1.txt')
self.assertEqual(7, self.graph.vertex_count())
self.assertEqual(1, self.graph.get_edge('A', 'B'))
self.assertEqual(1, self.graph.get_edge('A', 'C'))
self.assertEqual(1, self.graph.get_edge('A', 'D'))
self.assertEqual(1, self.graph.get_edge('B', 'A'))
self.assertEqual(1, self.graph.get_edge('B', 'E'))
self.assertEqual(1, self.graph.get_edge('C', 'A'))
self.assertEqual(1, self.graph.get_edge('C', 'F'))
self.assertEqual(1, self.graph.get_edge('D', 'A'))
self.assertEqual(1, self.graph.get_edge('E', 'B'))
| Python |
# -*- coding: utf-8 -*-
import unittest
from structures.hashtable import HashTable
class HashTableTest(unittest.TestCase):
def test_add_and_retrieve_item(self):
hash = HashTable()
key = "one"
hash.set(key, 1)
self.assertEqual(1, hash.get(key))
def test_add_and_retrieve_two_items(self):
pairs = [["one", 1], ["two", 2]]
hash = HashTable()
for pair in pairs:
key = pair[0]
data = pair[1]
hash.set(key, data)
count = 1
for pair in pairs:
key = pair[0]
self.assertEqual(count, hash.get(key))
count += 1
def test_add_and_retrieve_fifteen_items(self):
pairs = [["one", 1], ["two", 2], ["three", 3],
["four", 4], ["five", 5], ["six", 6],
["seven", 7], ["eight", 8], ["nine", 9],
["ten", 10], ["eleven", 11], ["twelve", 12],
["thirteen", 13], ["fourteen", 14], ["fifteen", 15]]
hash = HashTable()
for pair in pairs:
key = pair[0]
data = pair[1]
hash.set(key, data)
count = 1
for pair in pairs:
key = pair[0]
self.assertEqual(count, hash.get(key))
count += 1
def test_add_and_retrieve_fifteen_items_similar_keys(self):
hash = HashTable()
n = 100
for i in range(n):
key = 'V' + str(i)
hash.set(key, i)
for i in range(n):
key = 'V' + str(i)
self.assertEqual(i, hash.get(key))
def test_add__fifteen_items_similar_keys_retrieve_different(self):
hash = HashTable()
n = 100
for i in range(n):
key = 'V' + str(i)
hash[key] = i
self.assertEqual(None, hash['does not exist'])
self.assertEqual(None, hash['V101'])
self.assertEqual(None, hash['V1.1'])
def test_add_some_items_and_get_values_list(self):
hash = HashTable()
n = 15
for i in range(n):
key = 'V' + str(i)
hash.set(key, i)
values = hash.get_values()
self.assertEqual(n, len(values))
def test_add_items_to_force_rehashing_and_get_values_list(self):
hash = HashTable()
n = 1000
for i in range(n):
key = 'V' + str(i)
hash[key] = i
values = hash.get_values()
self.assertEqual(n, len(values))
| Python |
# -*- coding: utf-8 -*-
import unittest
from structures.list import List
class ListTest(unittest.TestCase):
def test_create_list_check_empty(self):
list = List()
self.assertTrue(list.empty())
def test_create_list_add_element_check_emtpy(self):
list = List()
list.add(1)
self.assertFalse(list.empty())
def test_add_two_items_pop_them_check_values_check_empty(self):
list = List()
list.add(1)
list.add(2)
value = list.pop()
self.assertEqual(2, value)
value = list.pop()
self.assertEqual(1, value)
self.assertTrue(list.empty())
def test_add_items_first_pop_them_check_values_check_empty(self):
list = List()
list.add_first(1)
list.add_first(2)
value = list.pop()
self.assertEqual(1, value)
value = list.pop()
self.assertEqual(2, value)
self.assertTrue(list.empty())
def test_add_items_use_iterator(self):
list = List()
list.add_first(1)
list.add_first(2)
list.add_first(3)
count = 0
for item in list:
count += 1
self.assertEqual(3, count)
| Python |
# -*- coding: utf-8 -*-
import unittest
from graphs.listgraph import ListGraph
class ListGraphTest(unittest.TestCase):
def setUp(self):
self.graph = ListGraph()
def test_add_two_vertices(self):
self.graph.add_vertex('V1')
self.graph.add_vertex('V2')
self.assertEqual(2, self.graph.vertex_count())
def test_add_fifteen_vertices(self):
n = 15
for i in range(n):
name = 'V' + str(i)
self.graph.add_vertex(name)
self.assertEqual(n, self.graph.vertex_count())
def test_add_vertices_add_edge_check_edge(self):
n = 15
for i in range(n):
name = 'V' + str(i)
self.graph.add_vertex(name)
self.graph.add_edge('V4', 'V5', 1)
weight = self.graph.get_edge('V4', 'V5')
self.assertEqual(1, weight)
self.assertEqual(1, self.graph.edge_count())
def test_load(self):
self.graph.load('inputs/test1.txt')
self.assertEqual(7, self.graph.vertex_count())
self.assertEqual(1, self.graph.get_edge('A', 'B'))
self.assertEqual(1, self.graph.get_edge('A', 'C'))
self.assertEqual(1, self.graph.get_edge('A', 'D'))
self.assertEqual(1, self.graph.get_edge('B', 'A'))
self.assertEqual(1, self.graph.get_edge('B', 'E'))
self.assertEqual(1, self.graph.get_edge('C', 'A'))
self.assertEqual(1, self.graph.get_edge('C', 'F'))
self.assertEqual(1, self.graph.get_edge('D', 'A'))
self.assertEqual(1, self.graph.get_edge('E', 'B'))
| Python |
# -*- coding: utf-8 *-*
import unittest
from graphs.listgraph import ListGraph
from graphs.matrixgraph import MatrixGraph
class DijkstraTest(unittest.TestCase):
def test_dijkstra_matrix(self):
self.run_test1(MatrixGraph())
self.run_test2(MatrixGraph())
self.run_test3(MatrixGraph())
self.run_test4(MatrixGraph())
def test_dijkstra_list(self):
self.run_test1(ListGraph())
self.run_test2(ListGraph())
self.run_test3(ListGraph())
self.run_test4(ListGraph())
def run_test1(self, graph):
graph.load('inputs/test1.txt')
items = graph.run_dijkstra('A', 1)
self.assertEqual(6, items.count())
items = graph.run_dijkstra('A', 2)
self.assertEqual(3, items.count())
items = graph.run_dijkstra('A', 3)
self.assertEqual(1, items.count())
def run_test2(self, graph):
graph.load('inputs/test2.txt')
items = graph.run_dijkstra('A', 1)
self.assertEqual(3, items.count())
items = graph.run_dijkstra('A', 2)
self.assertEqual(0, items.count())
def run_test3(self, graph):
graph.load('inputs/test3.txt')
items = graph.run_dijkstra('A', 1)
self.assertEqual(3, items.count())
def run_test4(self, graph):
graph.load('inputs/test4.txt')
items = graph.run_dijkstra('A', 1)
self.assertEqual(3, items.count())
items = graph.run_dijkstra('A', 2)
self.assertEqual(2, items.count())
items = graph.run_dijkstra('A', 3)
self.assertEqual(1, items.count())
items = graph.run_dijkstra('A', 4)
self.assertEqual(0, items.count())
| Python |
# -*- coding: utf-8 -*-
import unittest
from structures.heap import Heap
class HeapTest(unittest.TestCase):
def test_add_n_elements_verify_order(self):
heap = Heap()
n = 65
#Insert elements in reverse order
for i in range(n):
heap.insert(n - i, n - i)
#Then verify they are extracted from min to max
min = None
while not heap.empty():
newmin = heap.extract_min()
if min is not None:
self.assertLessEqual(min, newmin)
min = newmin
def test_add_3_elements_change_key_verify_heap_order(self):
heap = Heap()
n = 3
#Insert elements in reverse order
for i in range(n):
heap.insert(n - i, n - i)
heap.change_data(0, 4)
heap.change_key(0, 4)
#Then verify they are extracted from min to max
min = None
while not heap.empty():
newmin = heap.extract_min()
if min is not None:
self.assertLessEqual(min, newmin)
min = newmin
| Python |
# -*- coding: utf-8 -*-
from structures.hashtable import HashTable
from structures.list import List
from structures.heap import Heap
from structures.unionfind import UnionFind
from graphs.graph import *
class MatrixGraph(Graph):
def __init__(self):
self.__adjacency = []
self.__vertices = HashTable()
def add_vertex(self, name):
self.__vertices[name] = self.__length()
self.__adjacency.append([None] * self.__length())
for i in range(self.__length()):
self.__adjacency[i].append(None)
def add_edge(self, source, dest, weight):
edge = [source, dest, weight]
indexsource = self.__vertices[source]
indexdest = self.__vertices[dest]
if indexsource is not None and indexdest is not None:
self.__adjacency[indexsource][indexdest] = edge
else:
name = source
if indexdest is None:
name = dest
raise Exception("Vertex '" + name + "' doesn't exist")
def vertex_count(self):
return self.__length()
def edge_count(self):
count = 0
length = self.__length() - 1
for i in range(length):
for j in range(length):
if self.__adjacency[i][j] is not None:
count += 1
return count
def get_edge(self, source, dest):
indexsource = self.__vertices[source]
indexdest = self.__vertices[dest]
return self.__adjacency[indexsource][indexdest][2]
def __length(self):
return len(self.__adjacency)
def run_dijkstra(self, source, distance):
if self.__vertices[source] is None:
raise Exception('Source vertex does not exist!')
# Stores the name of the previous node for the key
previous = HashTable()
# Stores the calculated cost so far for each node
# from the source
cost = HashTable()
# Prority Queue
heap = Heap()
# Represents the value infinity
infinity = float("inf")
# Initialize all costs to infinity
for name in self.__vertices.get_keys():
cost[name] = infinity
# Set cost to source node to zero
# and add to heap
cost[source] = 0
heap.insert(cost[source], source)
# Count how many nodes have been added to S so far
count = 0
# While there are nodes missing
# and the heap is not empty (this condition is added
# in case the graph is not connected)
while count < self.vertex_count() and not heap.empty():
name = heap.extract_min()
count += 1
# Get index for vertex in matrix
index = self.__vertices[name]
# Look for adjacent nodes
for i in range(self.__length()):
edge = self.__adjacency[index][i]
if edge is not None:
# Calculate new cost
weight = edge[2]
dest = edge[1]
newcost = cost[name] + weight
# Update cost if it's smaller and is not in S
if newcost < cost[dest]:
cost[dest] = newcost
previous[dest] = name
heap.insert(newcost, dest)
# Get all vertex that are at least distance
# from source
actors = List()
for name in self.__vertices.get_keys():
if distance <= cost[name]:
actors.add(name)
return actors
def to_string(self):
output = ''
for i in range(self.__length()):
output += self.__vertices.get_keys()[i] + ': '
for j in range(self.__length()):
edge = self.__adjacency[i][j]
destination = edge[1]
weight = edge[2]
if edge is not None:
output += '(' + destination + ', '
output += str(weight) + ') '
output += '\n'
return output
def load(self, filename):
file = open(filename)
adj = HashTable()
for line in file:
pair = line.split(Graph.NAME_SEPARATOR)
name = pair[0].strip()
adjlist = pair[1].strip()
self.add_vertex(name)
adj[name] = adjlist
for name in self.__vertices.get_keys():
list = adj[name]
edges = list.split(Graph.ADJ_LIST_SEPARATOR)
for edge in edges:
edge = edge.strip()
if len(edge) > 0:
words = edge.split(Graph.WEIGHT_SEPARATOR)
destIndex = int(words[0].strip())
dest = self.__vertices.get_key(destIndex)
weight = None
weight = int(words[1])
self.add_edge(name, dest, weight)
file.close()
| Python |
# -*- coding: utf-8 -*-
from structures.list import List
from structures.heap import Heap
from structures.unionfind import UnionFind
from graphs.graph import *
class ListGraph(Graph):
def __init__(self, size=None):
self.__vertices = HashTable(size)
def add_vertex(self, name):
self.__vertices[name] = List()
def add_edge(self, src, dest, weight=None):
adjacents = self.__vertices[src]
exists = False
for edge in adjacents:
edgeDest = self.__vertices.get_key(edge[0])
if dest == edgeDest:
exists = True
break
if not exists:
destIndex = self.__vertices.get_key_index(dest)
edge = [destIndex, weight]
adjacents.add(edge)
def get_edge(self, src, dest):
adjacents = self.__vertices[src]
for edge in adjacents:
edgeDest = self.__vertices.get_key(edge[0])
if edgeDest == dest:
return edge[1]
return None
def vertex_count(self):
return self.__vertices.count()
def edge_count(self):
count = 0
for name in self.__vertices.get_keys():
adjacents = self.__vertices[name]
count += adjacents.count()
return count
def get_vertex(self, index):
return self.__vertices.get_key(index)
def run_dijkstra(self, source, distance):
if self.__vertices[source] is None:
raise Exception('Source vertex does not exist!')
# Stores the name of the previous node for the key
previous = HashTable()
# Stores the calculated distance so far for each node
# from the source
cost = HashTable()
# Prority Queue
heap = Heap()
# Represents the value infinity
infinity = float("inf")
# Initialize all costs to infinity
for name in self.__vertices.get_keys():
cost[name] = infinity
# Set the cost to source node to zero
# and add to heap
cost[source] = 0
heap.insert(cost[source], source)
# Count how many nodes have been added to S so far
count = 0
# While there are nodes missing
# and the heap is not empty (this condition is added
# in case the graph is not connected)
while count < self.vertex_count() and not heap.empty():
name = heap.extract_min()
count += 1
# Get vertex
adjacents = self.__vertices[name]
# Look for adjacent nodes
for edge in adjacents:
# Calculate new cost
dest = self.__vertices.get_key(edge[0])
weight = edge[1]
newcost = cost[name] + weight
# Update cost if it's smaller
if newcost < cost[dest]:
cost[dest] = newcost
previous[dest] = name
heap.insert(newcost, dest)
# Get all vertex that are at least distance
# from source
actors = List()
for name in self.__vertices.get_keys():
if distance <= cost[name]:
actors.add(name)
return actors
def to_string(self):
output = ''
for name in self.__vertices.get_keys():
adjacents = self.__vertices[name]
output += name + ':'
if adjacents.count() > 0:
for edge in adjacents:
output += '(' + edge[0] + ', '
output += str(edge[1]) + ') '
output += '\n'
return output
def save(self, filename):
file = open(filename, 'w')
for name in self.__vertices.get_keys():
adjacents = self.__vertices[name]
file.write(name + Graph.NAME_SEPARATOR)
if adjacents.count() > 0:
count = 0
for edge in adjacents:
destinationIndex = edge[0]
weight = edge[1]
if count != 0:
file.write(Graph.ADJ_LIST_SEPARATOR)
file.write(str(destinationIndex) + Graph.WEIGHT_SEPARATOR)
file.write(str(weight))
count += 1
file.write('\n')
file.close()
def load(self, filename):
file = open(filename)
for line in file:
pair = line.split(Graph.NAME_SEPARATOR)
name = pair[0].strip()
list = pair[1].strip()
self.add_vertex(name)
edges = list.split(Graph.ADJ_LIST_SEPARATOR)
for edge in edges:
edge = edge.strip()
if len(edge) > 0:
words = edge.split(Graph.WEIGHT_SEPARATOR)
index = int(words[0].strip())
weight = int(words[1])
self.__vertices[name].add([index, weight])
file.close()
| Python |
# -*- coding: utf-8 -*-
from graphs.matrixgraph import MatrixGraph
from graphs.graph import Edge
import random
import math
class Generator():
def __init__(self):
pass
def generate(self, vcount, factor, filename):
if factor > 1:
raise Exception('Invalid density factor.')
maxedges = (vcount - 1) * vcount
ecount = int(maxedges * factor)
if ecount < vcount:
ecount = vcount
# if ecount > 10000:
# ecount = 10000
# print 'Going for', ecount, 'edges.'
graph = MatrixGraph()
for i in range(vcount):
name = 'V' + str(i)
graph.add_vertex(name)
#self.random_generation(graph, vcount, ecount)
self.secuential_generation(graph, vcount, ecount)
graph.save(filename)
def random_generation(self, graph, vcount, ecount):
for i in range(ecount):
while True:
edge = self.random_edge(vcount)
if graph.get_edge(edge.source, edge.destination) is None:
graph.add_edge(edge.source, edge.destination, edge.weight)
break
else:
print 'This edge already exists. Try again.'
print edge.source, edge.destination, graph.edge_count()
def secuential_generation(self, graph, vcount, ecount):
edgespervertex = int(math.ceil(ecount / vcount))
vdelta = int(vcount / edgespervertex)
for src in range(vcount):
for dest in range(src + 1, vcount + src + 1, vdelta):
if dest >= vcount:
dest = dest - vcount
if src != dest:
weight = random.randint(0, 10)
source = 'V' + str(src)
destination = 'V' + str(dest)
#print source, '-', destination, ':', weight
graph.add_edge(source, destination, weight)
def random_edge(self, vcount, src=None):
if src is None:
src = random.randint(0, vcount - 1)
dest = src
while dest == src:
dest = random.randint(0, vcount - 1)
weight = random.randint(0, 10)
src = 'V' + str(src)
dest = 'V' + str(dest)
return Edge(src, dest, weight)
| Python |
# -*- coding: utf-8 -*-
from structures.hashtable import HashTable
class Graph():
NAME_SEPARATOR = '->'
ADJ_LIST_SEPARATOR = '||'
WEIGHT_SEPARATOR = ';'
def __init__(self):
pass
def load(self, filename):
pass
def save(self, filename):
raise Exception('save() not implemented.')
def show(self):
print self.to_string()
def add_vertex(self, name):
pass
def add_edge(self, source, destination, weight):
pass
def vertex_count(self):
pass
def edge_count(self):
pass
def run_kruskal(self):
pass
def run_prim(self):
pass
def run_dijkstra(self, source, destination):
pass
| Python |
# -*- coding: utf-8 -*-
import sys
import unittest
from tests.matrixgraph import *
from tests.listgraph import *
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
import sys
import unittest
from tests.hashtable import *
from tests.heap import *
from tests.unionfind import *
from tests.list import *
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
from structures.hashtable import HashTable
class UnionFind():
def __init__(self, items):
self.sets = HashTable()
for item in items:
node = UnionFindNode(item)
self.sets.set(item, node)
self.__count = len(items)
def find(self, item):
node = self.sets.get(item)
while node.set is not None:
node = node.set
return node.item
def union(self, item1, item2):
if item1 != item2:
node1 = self.sets.get(item1)
node2 = self.sets.get(item2)
if node1.size < node2.size:
node1.set = node2
node2.size += node1.size
else:
node2.set = node1
node1.size += node2.size
self.__count -= 1
def count(self):
return self.__count
class UnionFindNode():
def __init__(self, item):
self.item = item
self.set = None
self.size = 1
| Python |
# -*- coding: utf-8 -*-
class HashTable():
__initial_size = 32
def __init__(self, size=None):
self.__size = size
if size is None:
self.__size = HashTable.__initial_size
self.items = [None] * self.__size
self.__keys = []
def count(self):
return len(self.__keys)
def set(self, key, value):
keyIndex = self.count()
self.__keys.append(key)
if self.count() > 0.7 * self.__size:
self.__rehash()
index = self.__get_index(key)
item = self.items[index]
if item is None:
self.items[index] = [keyIndex, value]
elif self.__keys[item[0]] == key:
item[1] = value
def get(self, key):
index = self.__get_index(key)
value = None
if index is not None and self.items[index] is not None:
value = self.items[index][1]
return value
def get_values(self):
values = []
for item in self.items:
if item is not None:
values.append(item[1])
return values
def get_keys(self):
return self.__keys
def get_key(self, index):
return self.__keys[index]
def get_key_index(self, key):
index = self.__get_index(key)
item = self.items[index]
return item[0]
def __get_index(self, key):
"Used linear probing."
index = self.__primary_hash(key) % self.__size
if self.__collision(key, index):
index = self.__secondary_hash(key) % self.__size
pos = 0
while self.__collision(key, index):
index += 1
index %= self.__size
pos += 1
return index
def __collision(self, key, index):
item = self.items[index]
return (item is not None and self.__keys[item[0]] != key)
def __get_hash(self, key, pos=0):
hash = self.__primary_hash(key)
hash += pos * self.__secondary_hash(key)
return hash
def __primary_hash(self, key):
"Used FNV hash function"
key = str(key)
h = 2166136261
for letter in key:
h = (h * 16777619) ^ ord(letter)
return h
def __secondary_hash(self, key):
"Shift-Add-XOR hash function"
key = str(key)
h = 0
for letter in key:
h ^= (h << 5) + (h >> 2) + ord(letter)
return h
def __rehash(self):
max_capacity = self.__size
occupied = self.count() * 100 / self.__size
# print self.count(), 'items of total capacity', max_capacity
# print 'percentage:', occupied
olditems = self.items
factor = 2
if self.count() < 50000:
factor = 4
self.__size = int(factor * self.__size)
self.items = [None] * self.__size
# print 'rehashing to', self.__size, 'buckets'
for item in olditems:
if item is not None:
itemKey = self.__keys[item[0]]
index = self.__get_index(itemKey)
self.items[index] = item
# print 'finished rehashing'
# print '--------------------------'
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
| Python |
# -*- coding: utf-8 -*-
class List():
def __init__(self):
self.__begin = None
self.__end = None
self.__current = None
self.__size = 0
def empty(self):
return self.__size == 0
def pop(self):
return self.pop_last()
def pop_last(self):
item = None
if self.__end is not None:
self.__size -= 1
item = self.__end[0]
if self.__end[1] is not None:
prev = self.__end[1]
prev[2] = None
self.__end = prev
elif self.__begin is None:
self.__end = None
self.__begin = None
return item
def pop_first(self):
item = None
if self.__begin is not None:
self.__size -= 1
item = self.__begin[0]
if self.__begin[2] is not None:
next = self.__begin[2]
next[1] = None
self.__begin = next
else:
self.__end = None
self.__begin = None
return item
def add(self, item):
self.add_last(item)
def add_first(self, item):
self.__size += 1
node = [item, None, None]
if self.__begin is None:
self.__begin = node
self.__end = node
else:
node[2] = self.__begin
node[1] = None
self.__begin[1] = node
self.__begin = node
def add_last(self, item):
self.__size += 1
node = [item, None, None]
if self.__end is None:
self.__begin = node
self.__end = node
else:
node[1] = self.__end
node[2] = None
self.__end[2] = node
self.__end = node
def get_first(self):
return self.__begin
def get_last(self):
return self.__end
def next(self):
if self.__current is not None:
self.__current = self.__current[2]
return self.__current
def prev(self):
if self.__current is not None:
this.__current = self.__current[1]
return self.__current
def current(self):
return self.__current
def count(self):
return self.__size
def reset(self):
self.__current = self.__begin
def __iter__(self):
return ListIterator(self)
def to_string(self):
output = ''
for item in self:
value = str(item[0])
if value is None:
value = ''
output += value + ';'
return output
#class ListNode:
#
# def __init__(self, item):
# self.item = item
# self.next = None
# self.prev = None
class ListIterator:
def __init__(self, list):
self.list = list
self.list.reset()
def next(self):
node = self.list.current()
item = None
if node is not None:
item = node[0]
else:
raise StopIteration
self.list.next()
return item
def __iter__(self):
return self
| Python |
# -*- coding: utf-8 -*-
class Heap():
__maxSize = 100
def __init__(self):
self.items = []
def insert(self, key, data):
item = HeapItem(key, data)
self.items.append(item)
index = len(self.items) - 1
self.__heapify_up(index)
def change_key(self, index, key):
self.items[index].key = key
self.__heapify(index)
def change_data(self, index, data):
self.items[index].data = data
self.__heapify(index)
def extract_min(self):
min = self.items[0]
self.__delete(0)
return min.data
def empty(self):
return self.__length() == 0
def __delete(self, index):
item = self.items.pop()
if index < self.__length():
self.items[index] = item
self.__heapify(index)
def __heapify(self, index):
parent = self.__parent(index)
if self.items[index].key < self.items[parent].key:
self.__heapify_up(index)
else:
self.__heapify_down(index)
def __heapify_up(self, index):
if index > 0:
parent = self.__parent(index)
if self.items[index].key < self.items[parent].key:
self.__swap(index, parent)
self.__heapify_up(parent)
def __heapify_down(self, index):
length = self.__length()
left = self.__left(index)
right = self.__right(index)
#Verify if current has children
if left >= length:
return
#Verify if current has right child
elif right < length:
leftChild = self.items[left]
rightChild = self.items[right]
if leftChild.key < rightChild.key:
min = left
else:
min = right
#Then only left child exists
elif left == length - 1:
min = left
else:
raise Exception('There something wrong!')
item = self.items[index]
child = self.items[min]
if child.key < item.key:
self.__swap(index, min)
self.__heapify_down(min)
def __swap(self, i, j):
"Swaps nodes in the heap"
temp = self.items[i]
self.items[i] = self.items[j]
self.items[j] = temp
def __length(self):
"Returns the number of elements in the heap"
return len(self.items)
def __item(self, index):
item = None
if index < self.__length():
item = self.items[index]
return item
def __left(self, index):
return (2 * index) + 1
def __right(self, index):
return (2 * index) + 2
def __parent(self, index):
if index == 0:
return 0
elif index % 2 == 0:
return index / 2 - 1
else:
return index / 2
def size(self):
return self.__length()
def show(self):
for index in range(self.__length()):
item = self.__item(index)
left = self.__item(self.__left(index))
right = self.__item(self.__right(index))
output = str(item.key)
if left is not None:
output += ' (left=' + str(left.key) + ')'
if right is not None:
output += ' (right=' + str(right.key) + ')'
print output
print '---------------------------'
class HeapItem():
def __init__(self, key, data):
self.key = key
self.data = data
| Python |
# -*- coding: utf-8 -*-
###############################################################################
# Import Modules
###############################################################################
import sys
import unittest
from backtracking import backtracking
from galeshapley import galeshapley
class TdaTP1(unittest.TestCase):
def getOutput(self, filename):
outputFile = file(filename)
return outputFile.read()
def getGaleShapley(self, filename):
gs = galeshapley.GaleShapley(filename)
gs.match()
return gs.toString()
def getBacktracking(self, filename):
b = backtracking.Backtracking(filename)
b.match()
return b.solution
def testGaleShapleyInput1(self):
result = self.getGaleShapley('input1.txt')
expected = self.getOutput('output1.gs.txt')
self.assertEqual(result, expected)
def testGaleShapleyInput2(self):
result = self.getGaleShapley('input2.txt')
expected = self.getOutput('output2.gs.txt')
self.assertEqual(result, expected)
def testGaleShapleyInput3(self):
result = self.getGaleShapley('input3.txt')
expected = self.getOutput('output3.gs.txt')
self.assertEqual(result, expected)
def testBacktrackingInput1(self):
result = self.getBacktracking('input1.txt')
expected = self.getOutput('output1.bt.txt')
self.assertEqual(result, expected)
def testBacktrackingInput2(self):
result = self.getBacktracking('input2.txt')
expected = self.getOutput('output2.bt.txt')
self.assertEqual(result, expected)
def testBacktrackingInput3(self):
result = self.getBacktracking('input3.txt')
expected = self.getOutput('output3.bt.txt')
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
###############################################################################
# Import Modules
###############################################################################
import sys
from backtracking import backtracking
from galeshapley import galeshapley
def compareResult(filename, resultStr):
outputFile = file(filename)
outputStr = outputFile.read()
if outputStr == resultStr:
print "Sucess! The result matches the file contents for:", filename
else:
print "Fail! The result doesn't match the file contents for:", filename
def errormsg():
print "Error. Script usage:"
print " $ python tdatp1.py [-gs|-bt] [inputFilename] [outputFilename]"
def main():
if len(sys.argv) == 4:
algorithm = sys.argv[1]
inputFilename = sys.argv[2]
outputFilename = sys.argv[3]
resultStr = ''
if algorithm == '-gs':
print "------------------------------------"
print "Gale & Shapley"
print "------------------------------------"
gs = galeshapley.GaleShapley(inputFilename)
gs.match()
resultStr = gs.toString()
elif algorithm == '-bt':
print "------------------------------------"
print "Backtracking"
print "------------------------------------"
b = backtracking.Backtracking(inputFilename)
b.match()
resultStr = b.solution
else:
errormsg()
if resultStr != '':
print resultStr
compareResult(outputFilename, resultStr)
else:
errormsg()
if __name__ == '__main__':
main()
| Python |
# -*- coding: utf-8 -*-
from collections import deque
from model.person import Person
from model.solution import Solution
class Backtracking:
def __init__(self, filename):
self.men = deque()
self.women = []
self.solution = None
self.__temp = Solution()
self.load_data(filename)
def load_data(self, filename):
"""Loads men and women [O(n)] and their preference lists [O(n)]
O(n^2)"""
file = open(filename)
genre = 'Male'
for line in file:
words = line.split(":")
if line == '\n':
genre = 'Female'
else:
name = words[0]
preferences = words[1]
person = Person(name, preferences)
if genre == 'Male':
self.men.append(person)
else:
self.women.append(person)
file.close()
def match(self):
"""Finds all stable matchings
O(n^n)"""
# If there are still
if len(self.men) != 0:
#Take the first man in the list
m = self.men.pop()
#Check for women without commitment
for w in self.women:
if w.fiancee is None:
#Build pair
pair = [m, w]
m.engage(w)
#Verify that the new pair doesn't create instability
if self.__temp.is_stable(pair):
self.__temp.push(pair)
self.match()
self.__temp.pop()
m.break_up()
# Get the man back in the stack
self.men.append(m)
else:
if self.solution is None:
self.solution = self.__temp.toString()
| Python |
# -*- coding: utf-8 -*-
from collections import deque
from model.person import Person
from model.solution import Solution
class GaleShapley:
def __init__(self, filename):
self.singles = deque()
self.men = []
self.women = dict()
self.load_data(filename)
def load_data(self, filename):
"""Loads men and women [O(n)] and their preference lists [O(n)]
O(n^2)"""
file = open(filename)
genre = 'Male'
for line in file:
words = line.split(":")
if line == '\n':
genre = 'Female'
else:
name = words[0]
preferences = words[1]
person = Person(name, preferences)
if genre == 'Male':
self.men.append(person)
else:
self.women[name] = person
file.close()
self.singles = deque(self.men)
def match(self):
"""Finds a stable matching in O(n^2)"""
# If there are still single men
while len(self.singles) > 0:
#Take a single man
m = self.singles.pop()
#Get next woman's name in the preference list
name = m.get_prospect()
if name is None:
raise Exception("This shouldn't be happening!")
#Get woman by name
w = self.women[name]
#Check who the woman prefers
if w.prefers(m):
if w.fiancee is not None:
self.singles.appendleft(w.fiancee)
w.break_up()
m.engage(w)
else:
self.singles.appendleft(m)
def toString(self):
str = ''
for m in self.men:
str += "(" + m.name + ", " + m.fiancee.name + ")\n"
return str
| Python |
# -*- coding: utf-8 -*-
from collections import deque
class Solution:
def __init__(self):
self.__pairs = deque()
def is_stable(self, pair):
for p in self.__pairs:
m1 = p[0]
w1 = p[1]
m2 = pair[0]
w2 = pair[1]
if ((m1.prefers(w2) and w2.prefers(m1))
or (m2.prefers(w1) and w1.prefers(m2))):
return False
return True
def push(self, pair):
self.__pairs.append(pair)
def pop(self):
pair = self.__pairs.pop()
return pair
def show(self):
print self.toString()
def toString(self):
str = ''
for p in self.__pairs:
str += "(" + p[0].name + ", " + p[1].name + ")\n"
return str
| Python |
# -*- coding: utf-8 -*-
from collections import deque
class Person:
def __init__(self, name, preferences=[]):
"""Initializes the preferences hashtable.
O(n)"""
self.prefnames = deque()
self.name = name
self.fiancee = None
self.prefs = dict()
i = 0
for prospectname in preferences.split(","):
prospectname = prospectname.strip()
self.prefs[prospectname] = i
self.prefnames.appendleft(prospectname)
i = i + 1
def prefers(self, p1):
"""Determins wheter this person prefers its current
fiancee or the one specified in the parameter.
O(1)"""
result = True
if self.fiancee is not None:
result = self.prefs[p1.name] > self.prefs[self.fiancee.name]
return result
def engage(self, p):
self.fiancee = p
p.fiancee = self
def break_up(self):
if self.fiancee is not None:
self.fiancee.fiancee = None
self.fiancee = None
def get_prospect(self):
if len(self.prefnames) > 0:
return self.prefnames.pop()
return None
| Python |
__author__="Sergey Karakovskiy, sergey at idsia fullstop ch"
__date__ ="$Feb 18, 2009 1:01:12 AM$"
class SimplePyAgent:
# class MarioAgent(Agent):
""" example of usage of AmiCo
"""
def getAction(self, obs):
ret = (0, 1, 0, 0, 0)
return ret
def giveReward(self, reward):
pass
def _getName(self):
if self._name is None:
self._name = self.__class__.__name__
return self._name
def _setName(self, newname):
"""Change name to newname. Uniqueness is not guaranteed anymore."""
self._name = newname
_name = None
name = property(_getName, _setName)
def __repr__(self):
""" The default representation of a named object is its name. """
return "<%s '%s'>" % (self.__class__.__name__, self.name)
def newEpisode(self):
pass
| Python |
import numpy
__author__ = "Sergey Karakovskiy, sergey at idsia fullstop ch"
__date__ = "$May 1, 2009 2:46:34 AM$"
from marioagent import MarioAgent
class ForwardAgent(MarioAgent):
""" In fact the Python twin of the
corresponding Java ForwardAgent.
"""
action = None
actionStr = None
KEY_JUMP = 3
KEY_SPEED = 4
levelScene = None
mayMarioJump = None
isMarioOnGround = None
marioFloats = None
enemiesFloats = None
isEpisodeOver = False
trueJumpCounter = 0
trueSpeedCounter = 0
def reset(self):
self.isEpisodeOver = False
self.trueJumpCounter = 0
self.trueSpeedCounter = 0
def __init__(self):
"""Constructor"""
self.trueJumpCounter = 0
self.trueSpeedCounter = 0
self.action = numpy.zeros(5, int)
self.action[1] = 1
self.actionStr = ""
def _dangerOfGap(self):
for x in range(9, 13):
f = True
for y in range(12, 22):
if (self.levelScene[y, x] != 0):
f = False
if (f and self.levelScene[12, 11] != 0):
return True
return False
def _a2(self):
""" Interesting, sometimes very useful behaviour which might prevent falling down into a gap!
Just substitue getAction by this method and see how it behaves.
"""
if (self.mayMarioJump):
print "m: %d, %s, %s, 12: %d, 13: %d, j: %d" \
% (self.levelScene[11, 11], self.mayMarioJump, self.isMarioOnGround, \
self.levelScene[11, 12], self.levelScene[11, 12], self.trueJumpCounter)
else:
if self.levelScene == None:
print "Bad news....."
print "m: %d, 12: %d, 13: %d, j: %d" \
% (self.levelScene[11, 11], \
self.levelScene[11, 12], self.levelScene[11, 12], self.trueJumpCounter)
a = numpy.zeros(5, int)
a[1] = 1
danger = self._dangerOfGap()
if (self.levelScene[11, 12] != 0 or \
self.levelScene[11, 13] != 0 or danger):
if (self.mayMarioJump or \
(not self.isMarioOnGround and a[self.KEY_JUMP] == 1)):
a[self.KEY_JUMP] = 1
self.trueJumpCounter += 1
else:
a[self.KEY_JUMP] = 0
self.trueJumpCounter = 0
if (self.trueJumpCounter > 16):
self.trueJumpCounter = 0
self.action[self.KEY_JUMP] = 0
a[self.KEY_SPEED] = danger
actionStr = ""
for i in range(5):
if a[i] == 1:
actionStr += '1'
elif a[i] == 0:
actionStr += '0'
else:
print "something very dangerous happen...."
actionStr += "\r\n"
print "action: " , actionStr
return actionStr
def getAction(self):
""" Possible analysis of current observation and sending an action back
"""
# print "M: mayJump: %s, onGround: %s, level[11,12]: %d, level[11,13]: %d, jc: %d" \
# % (self.isMarioAbleToJump, self.isMarioOnGround, self.levelScene[11,12], \
# self.levelScene[11,13], self.trueJumpCounter)
# if (self.isEpisodeOver):
# return numpy.ones(5, int)
danger = self._dangerOfGap()
if (self.levelScene[11, 12] != 0 or \
self.levelScene[11, 13] != 0 or danger):
if (self.mayMarioJump or \
(not self.isMarioOnGround and self.action[self.KEY_JUMP] == 1)):
self.action[self.KEY_JUMP] = 1
self.trueJumpCounter += 1
else:
self.action[self.KEY_JUMP] = 0
self.trueJumpCounter = 0
if (self.trueJumpCounter > 16):
self.trueJumpCounter = 0
self.action[self.KEY_JUMP] = 0
self.action[self.KEY_SPEED] = danger
return self.action
def integrateObservation(self, obs):
"""This method stores the observation inside the agent"""
if (len(obs) != 6):
self.isEpisodeOver = True
else:
self.mayMarioJump, self.isMarioOnGround, self.marioFloats, self.enemiesFloats, self.levelScene, dummy = obs
# self.printLevelScene()
def printLevelScene(self):
ret = ""
for x in range(22):
tmpData = ""
for y in range(22):
tmpData += self.mapElToStr(self.levelScene[x][y])
ret += "\n%s" % tmpData
print ret
def mapElToStr(self, el):
"""maps element of levelScene to str representation"""
s = ""
if (el == 0):
s = "##"
s += "#MM#" if (el == 95) else str(el)
while (len(s) < 4):
s += "#"
return s + " "
def printObs(self):
"""for debug"""
print repr(self.observation)
| Python |
__author__="Sergey Karakovskiy, sergey at idsia fullstop ch"
__date__ ="$May 2, 2009 7:54:12 PM$"
class MarioAgent:
# class MarioAgent(Agent):
""" An agent is an entity capable of producing actions, based on previous observations.
Generally it will also learn from experience. It can interact directly with a Task.
"""
def integrateObservation(self, obs):
raise "Not implemented"
def getAction(self):
raise "Not implemented"
def giveReward(self, reward):
pass
def _getName(self):
if self._name is None:
self._name = self.__class__.__name__
return self._name
def _setName(self, newname):
"""Change name to newname. Uniqueness is not guaranteed anymore."""
self._name = newname
_name = None
name = property(_getName, _setName)
def __repr__(self):
""" The default representation of a named object is its name. """
return "<%s '%s'>" % (self.__class__.__name__, self.name)
def newEpisode(self):
pass
| Python |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| Python |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| Python |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "colombianCrush.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Python |
"""
Django settings for prueba project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1wo%qk-6ws%7zt7ld_vfgk9v7w5!#@%i415knk2ip)lr4cjn(@'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
DJANGO_STATIC = True
ALLOWED_HOSTS = []#"//colombianCrush.com",]
#DJANGO_STATIC_MEDIA_URL = ALLOWED_HOSTS[0]
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_static',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'web').replace('\\','/'),
)
ROOT_URLCONF = 'colombianCrush.urls'
WSGI_APPLICATION = 'colombianCrush.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'es'
TIME_ZONE = 'America/Bogota'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = 'https://201320-modelos-2.googlecode.com/svn/trunk/colombian%20crush/static/'
MEDIA_URL = 'https://201320-modelos-2.googlecode.com/svn/trunk/colombian%20crush/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\','/')
| Python |
'''
Created on 2/12/2013
@author: Juanpa y Yami
'''
from colombianCrush.core import *
class Figura(object):
"""Clase que representa a una figura que se puede ver en pantalla"""
def __init__(self, imagen):
self.id = imagen
self.imagen = Generador.cargarImagen(imagen)
def dibujar(self):
"""Retorna la url de la imagen de la figura para que sea dibujada"""
return self.imagen
def __unicode__(self):
return self.id
class Contenedor(object):
"""Clase que contiene la matriz de figuras que se ve en pantalla"""
def __init__(self, filas=10, columnas=10):
self.contenido = [[Figura(Generador.siguienteFigura()) for i in xrange(filas)] for y in xrange(columnas)]
self.espacios = 0
def darContenido(self):
"""Retorna la matriz de figuras para que se muestre en pantalla"""
return self.contenido
def establecerContenido(self, cont):
"""Guarda la matriz obtenida del request de la pagina"""
self.contenido = cont
def agregarFigura(self):
for figura in self.contenido[0]:
if figura is VACIO:
figura = Figura(Generador.siguienteFigura())
self.espacios-=1
def bajarFigura(self):
self.espacios = 0
for fila in xrange(len(self.contenido)):
for fig in xrange(len(self.contenido[0])):
try:
if self.contenido[fila+1][fig] is VACIO:
self.contenido[fila+1][fig]=self.contenido[fila][fig]
self.contenido[fila][fig]=VACIO
self.espacios+=1
except IndexError:
break;
class Controlador(object):
"""Clase que controla el flujo del juego"""
def __init__(self):
self.tablero = Contenedor()
self.estado = ACTIVO
self.preconsulta = []
self.consultor = None
self.respuesta = 0
self.puntaje = 0
def controlJuego(self):
if self.estado is ACTIVO:
self.tablero.bajarFigura()
while self.tablero.espacios>0:
self.tablero.bajarFigura()
self.tablero.agregarFigura()
if self.tablero.espacios<=0:
self.estado = PASIVO
elif self.estado is PASIVO:
pass # turno del jugador
elif self.estado is DESTRUCCION:
for i in xrange(len(self.tablero.contenido)):
for j in xrange(len(self.tablero.contenido[0])):
try:
self.preconsulta.append(self.tablero.contenido[i][j])
except IndexError:
self.preconsulta.append(200)
try:
self.preconsulta.append(self.tablero.contenido[i-1][j])
except IndexError:
self.preconsulta.append(200)
try:
self.preconsulta.append(self.tablero.contenido[i-2][j])
except IndexError:
self.preconsulta.append(200)
try:
self.preconsulta.append(self.tablero.contenido[i][j-1])
except IndexError:
self.preconsulta.append(200)
try:
self.preconsulta.append(self.tablero.contenido[i][j-2])
except IndexError:
self.preconsulta.append(200)
try:
self.preconsulta.append(self.tablero.contenido[i+1][j])
except IndexError:
self.preconsulta.append(200)
try:
self.preconsulta.append(self.tablero.contenido[i+2][j])
except IndexError:
self.preconsulta.append(200)
try:
self.preconsulta.append(self.tablero.contenido[i][j+1])
except IndexError:
self.preconsulta.append(200)
try:
self.preconsulta.append(self.tablero.contenido[i][j+2])
except IndexError:
self.preconsulta.append(200)
self.consultor = Consultor(Generador.arbolConsultar(self.preconsulta))
self.respuesta = self.consultor.buscarPosibilidad()
if self.respuesta is PASIVO:
self.estado = PASIVO
elif self.respuesta is LINEA_5H:
self.tablero.contenido[i][j] = Figura(BOMBA_COLOR)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.tablero.contenido[i][j-2] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.tablero.contenido[i][j+2] = Figura(VACIO)
self.puntaje += 100
self.estado = ACTIVO
elif self.respuesta is LINEA_5V:
self.tablero.contenido[i][j] = Figura(BOMBA_COLOR)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.tablero.contenido[i-2][j] = Figura(VACIO)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.tablero.contenido[i+2][j] = Figura(VACIO)
self.puntaje += 100
self.estado = ACTIVO
elif self.respuesta is L_ARRIBA_IZQ:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+20)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.tablero.contenido[i-2][j] = Figura(VACIO)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.tablero.contenido[i][j-2] = Figura(VACIO)
self.puntaje += 50
self.estado = ACTIVO
elif self.respuesta is L_ABAJO_IZQ:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+20)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.tablero.contenido[i+2][j] = Figura(VACIO)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.tablero.contenido[i][j-2] = Figura(VACIO)
self.puntaje += 50
self.estado = ACTIVO
elif self.respuesta is L_ABAJO_DER:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+20)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.tablero.contenido[i+2][j] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.tablero.contenido[i][j+2] = Figura(VACIO)
self.puntaje += 50
self.estado = ACTIVO
elif self.respuesta is L_ARRIBA_DER:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+20)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.tablero.contenido[i-2][j] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.tablero.contenido[i][j+2] = Figura(VACIO)
self.puntaje += 50
self.estado = ACTIVO
elif self.respuesta is T_ARRIBA:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+20)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.tablero.contenido[i-2][j] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.puntaje += 50
self.estado = ACTIVO
elif self.respuesta is T_IZQUIERDA:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+20)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.tablero.contenido[i][j-2] = Figura(VACIO)
self.puntaje += 50
self.estado = ACTIVO
elif self.respuesta is T_ABAJO:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+20)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.tablero.contenido[i+2][j] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.puntaje += 50
self.estado = ACTIVO
elif self.respuesta is T_DERECHA:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+20)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.tablero.contenido[i][j+2] = Figura(VACIO)
self.puntaje += 50
self.estado = ACTIVO
elif self.respuesta is LINEA_ARRIBA_4:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+10)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.tablero.contenido[i-2][j] = Figura(VACIO)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.puntaje += 40
self.estado = ACTIVO
elif self.respuesta is LINEA_ABAJO_4:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+10)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.tablero.contenido[i+2][j] = Figura(VACIO)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.puntaje += 40
self.estado = ACTIVO
elif self.respuesta is LINEA_IZQ_4:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+10)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.tablero.contenido[i][j-2] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.puntaje += 40
self.estado = ACTIVO
elif self.respuesta is LINEA_DER_4:
self.tablero.contenido[i][j] = Figura(self.tablero.contenido[i][j]+10)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.tablero.contenido[i][j+2] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.puntaje += 40
self.estado = ACTIVO
elif self.respuesta is LINEA_ARRIBA_3:
self.tablero.contenido[i][j] = Figura(VACIO)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.tablero.contenido[i-2][j] = Figura(VACIO)
self.puntaje += 30
self.estado = ACTIVO
elif self.respuesta is LINEA_IZQ_3:
self.tablero.contenido[i][j] = Figura(VACIO)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.tablero.contenido[i][j-2] = Figura(VACIO)
self.puntaje += 30
self.estado = ACTIVO
elif self.respuesta is LINEA_ABAJO_3:
self.tablero.contenido[i][j] = Figura(VACIO)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.tablero.contenido[i+2][j] = Figura(VACIO)
self.puntaje += 30
self.estado = ACTIVO
elif self.respuesta is LINEA_DER_3:
self.tablero.contenido[i][j] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.tablero.contenido[i][j+2] = Figura(VACIO)
self.puntaje += 30
self.estado = ACTIVO
elif self.respuesta is LINEA_3V:
self.tablero.contenido[i][j] = Figura(VACIO)
self.tablero.contenido[i+1][j] = Figura(VACIO)
self.tablero.contenido[i-1][j] = Figura(VACIO)
self.puntaje += 30
self.estado = ACTIVO
elif self.respuesta is LINEA_3H:
self.tablero.contenido[i][j] = Figura(VACIO)
self.tablero.contenido[i][j+1] = Figura(VACIO)
self.tablero.contenido[i][j-1] = Figura(VACIO)
self.puntaje += 30
self.estado = ACTIVO
elif self.estado is INACTIVO:
pass
| Python |
from elementos import Figura, Controlador | Python |
from django.conf.urls import patterns, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('colombianCrush.views',
# Examples:
# url(r'^$', 'prueba.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'inicio'),
url(r'^game/$', 'juego'),
url(r'^fin/$', 'fin'),
) | Python |
import os
from pyswip import Prolog
from random import randint
from django.conf import settings
#CONSTANTES DE IDENTIFICACION DE LOS ESTADOS DEL JUEGO
PASIVO = 0
#Estado en el que el jugador puede hacer su movimiento
ACTIVO = 1
#Estado en el que se reacomodan las fichas
DESTRUCCION = 2
#Estado en el que se consulta la base de conocimiento para obtener
#las posibilidades de eliminacion de elementos y se eliminan las fichas posibles
INACTIVO = 3
#Estado en el que se genera una sugerencia para el jugador
#CONSTANTES DE IDENTIFICACION DE LAS FIGURAS
BOMBA_COLOR = 500
VERDE_NORMAL = 501
NARANJA_NORMAL = 502
AMARILLO_NORMAL = 503
MORADO_NORMAL = 504
ROJO_NORMAL = 505
AZUL_NORMAL = 506
#FIGURAS BASICAS RELLENAS
VERDE_RAYAS = 511
NARANJA_RAYAS = 512
AMARILLO_RAYAS = 513
MORADO_RAYAS = 514
ROJO_RAYAS = 515
AZUL_RAYAS = 516
#FIGURAS A RAYAS
VERDE_EMPAQUE = 521
NARANJA_EMPAQUE = 522
AMARILLO_EMPAQUE = 523
MORADO_EMPAQUE = 524
ROJO_EMPAQUE = 525
AZUL_EMPAQUE = 526
#FIGURAS CON EMPAQUE
VACIO = 600
LINEA_5H = 1001
LINEA_5V = 1002
L_ARRIBA_IZQ = 1003
L_ABAJO_IZQ = 1004
L_ABAJO_DER = 1005
L_ARRIBA_DER = 1006
T_ARRIBA = 1007
T_IZQUIERDA = 1008
T_ABAJO = 1009
T_DERECHA = 1010
LINEA_ARRIBA_4 = 1011
LINEA_ABAJO_4 = 1012
LINEA_IZQ_4 = 1013
LINEA_DER_4 = 1014
LINEA_ARRIBA_3 = 1015
LINEA_IZQ_3 = 1016
LINEA_ABAJO_3 = 1017
LINEA_DER_3 = 1018
LINEA_3V = 1019
LINEA_3H = 1020
#CONSTANTES DE IDENTIFICACION DE EVENTOS DE DESTRUCCION DE FIGURAS
SUG_ARRIBA_1 = 2001
SUG_ARRIBA_2 = 2002
SUG_ARRIBA_3 = 2003
SUG_IZQ_1 = 2004
SUG_IZQ_2 = 2005
SUG_IZQ_3 = 2006
SUG_ABAJO_1 = 2007
SUG_ABAJO_2 = 2008
SUG_ABAJO_3 = 2009
SUG_DER_1 = 2010
SUG_DER_2 = 2011
SUG_DER_3 = 2012
SUG_CENT_V1 = 2013
SUG_CENT_V2 = 2014
SUG_CENT_H1 = 2015
SUG_CENT_H2 = 2016
#CONSTANTES DE IDENTIFICACION DE SUGERENCIAS DE MOVIMIENTOS
class Consultor(object):
"""Clase que implementa el mecanismo de consultas a la base de conocimientos usando Prolog"""
def __init__(self, consulta):
self.consultor = Prolog()
self.consultor.consult(os.path.join(settings.MEDIA_ROOT, 'colombianCrush.pl').replace('\\','/'))
self.consulta = consulta
self.resultado = []
def buscarSugerencia(self):
"""Genera la respuesta a la consulta de una sugerencia de movimiento para el jugador"""
return self._validarConsulta(self.consultor.query("buscarSugerencia(X, " + self.consulta + ")"))
def buscarPosibilidad(self):
"""Genera la respuesta a la consulta de una posibilidad de destruccion de figuras"""
return self._validarConsulta(self.consultor.query("buscarPosibilidad(X, " + self.consulta + ")"))
def _validarConsulta(self, consulta):
"""Metodo interno que extrae el menor valor obtenido de Prolog al consultar la base de conocimiento"""
for valor in consulta:
self.resultado.append(valor["X"])
if len(self.resultado)>PASIVO:
return min(self.resultado)
else:
return PASIVO
class Generador:
"""
clase que implemente el cargado de imagenes y aleatorizacion de las figuras
"""
def cargarImagen(cls, ubicacion):
"""Genera la url de la imagen en el repositorio a partir del id dado"""
try:
imagen = (settings.STATIC_URL + str(ubicacion)+'.png')
except IOError:
imagen = ubicacion
return imagen
cargarImagen = classmethod(cargarImagen)
def siguienteFigura(cls):
"""Genera un numero aleatorio que corresponde con el id de la figura a crear"""
return randint(VERDE_NORMAL, AZUL_NORMAL)
siguienteFigura = classmethod(siguienteFigura)
def arbolConsultar(cls, args):
"""Retorna la cadena que representa la consulta que se le va a realizar a Prolog"""
return "arbol(%s, arbol(%s, arbol(%s)), arbol(%s, arbol(%s)), \
arbol(%s, arbol(%s)), arbol(%s, arbol(%s)))" % tuple(args) # 9 argumentos
arbolConsultar = classmethod(arbolConsultar)
#Seccion de pruebas
def _test1():
consulta = "arbol(1, arbol(1, arbol(1)), arbol(1, arbol(2)), arbol(3, arbol(4)), arbol(1, arbol(2)))"
obj = Consultor(consulta)
print obj.buscarPosibilidad()
def _test2():
consulta = Generador.siguienteFigura()
#obj = Generador.cargarImagen(consulta)
print consulta
if __name__ == '__main__':
_test1()
_test2() | Python |
from constantes import *
del(Prolog)
del(os)
del(randint)
del(settings) | Python |
"""
WSGI config for prueba project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "colombianCrush.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
| Python |
'''
Created on 23/11/2013
@author: Juanpa y Yami
'''
from django.template import Context, RequestContext
from django.template.loader import get_template
from django.http import HttpResponse, HttpResponseRedirect
from colombianCrush.crush import Controlador, Figura
from django.views.decorators.csrf import csrf_protect
contenido = Controlador()
def inicio(request):
"""Metodo que envia la pagina principal del juego"""
titulo = "COLOMBIAN CRUSH"
imagen = Figura(500)
t = get_template("paginaPrincipal.html")
salida = t.render(Context({'imagen':imagen.dibujar(), 'titulo':titulo}))
return HttpResponse(salida)
@csrf_protect
def juego(request):
"""Metodo que envia el contenido del juego a la ventana"""
if request.method == 'POST':
contenido.tablero.establecerContenido(request.POST.getlist('tablero[]'))
contenido.estado = 2
contenido.controlJuego()
t = get_template("colombianCrushGame.html")
salida = t.render(RequestContext(request, {'tabla':contenido.tablero.darContenido(), 'puntaje':contenido.puntaje}))
return HttpResponse(salida)
if contenido.puntaje>=1000:
return HttpResponseRedirect('/fin')
def fin(request):
t = get_template("despedida.html")
salida = t.render(Context({'puntaje':contenido.puntaje}))
return HttpResponse(salida)
| Python |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "colombianCrush.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Python |
#!/usr/bin/env python
"""Branch and bound code for a 30 variable cardinality problem.
Written by Jacob Mattingley, March 2007, for EE364b Convex Optimization II,
Stanford University, Professor Stephen Boyd.
This file solves a (random) instance of the problem:
minimize card(x)
subject to Ax <= b
using branch and bound, where x is the optimization variable and is in
{0,1}^30, A is in R^(100x30) and b is in R^(100x1).
"""
from __future__ import division
from pylab import *
from cvxopt import random, lapack, solvers
from cvxopt.base import matrix
from cvxopt.modeling import variable, op, max, sum
inf = float('inf')
def sign(x):
"""Returns the sign of an object by comparing with <= 0, with 0
arbitrarily assigned a sign of -1."""
if x <= 0:
return -1
else:
return 1
def rtz(x, tol=1e-3):
"""Rounds within-tol objects or entries of a matrix to exactly zero."""
if isinstance(x, matrix):
return matrix([rtz(y,tol) for y in x], x.size)
elif abs(x) <= tol:
return 0
else:
return x
def argmin(x, avoid=[]):
"""Returns the index of the minimum item in x with index not in the set
avoid."""
for i in range(len(x)):
if i in avoid:
x[i] = inf
for i in range(len(x)):
if x[i] == min(x):
return i
def card(x):
"""Returns the cardinality (number of non-zero entries) of x."""
return len([1 for y in rtz(x) if y != 0])
def funcfeas(x, tol=1e-3):
"""Determines if x is in the feasible set Ax <= b (with tolerance)."""
y = A*x
for i in range(len(y)):
if y[i] - b[i] > tol:
return False
return True
class node:
"""node([n[, zeros[, ones[, parent]]]]) -> node object
Create node of a branch-and-bound tree with size n. Known-zero or
known-one elements should be set using zeros and ones. Specify the
optional parent if the node is not at the top of the tree.
"""
def __init__(self, n, zeros=[], ones=[], parent=None):
if (set(zeros) & set(ones)):
raise Exception, 'cannot have item fixed to zero and fixed to one'
zeros.sort()
ones.sort()
self.zeros = zeros
self.ones = ones
self.parent = parent
self.left = None
self.right = None
self.n = n
self.alive = True
self.lower = inf
self.upper = inf
self.prunedmass = 0
def solve(self):
"""Find upper and lower bounds of the sub-problem belonging to
this node."""
x = variable(self.n)
z = variable(self.n)
constr = [z <= 1, z >= 0, x >= min_mat*z, x <= max_mat*z, A*x <= b]
for i in self.ones:
constr.append(z[i] == 1)
for i in self.zeros:
constr.append(z[i] == 0)
# Use cvxopt to solve the problem.
o = op(sum(z), constr)
o.solve()
if x.value is None:
# We couldn't find a solution.
self.raw = None
self.rounded = None
self.lower = inf
self.upper = inf
return inf
# Use heuristic to choose which variable we should split on next. Don't
# choose a variable we have already set.
self.picknext = argmin(list(rtz(abs(z.value - 0.5))), self.zeros + self.ones)
self.lower = sum(z.value)
if funcfeas(x.value):
self.upper = card(x.value)
else:
self.upper = inf
return self.upper
def mass(self, fullonly=True):
"""Find the number of nodes which could live below this node."""
p = self.n - len(self.zeros) - len(self.ones)
return 2**p
def addleft(self):
"""Add a node to the left-hand side of the tree and solve."""
if self.left is None:
self.left = node(self.n, self.zeros + [self.picknext], self.ones, self)
self.left.solve()
return self.left
def addright(self):
"""Add a node to the right-hand side of the tree and solve."""
if self.right is None:
self.right = node(self.n, self.zeros, self.ones + [self.picknext], self)
self.right.solve()
return self.right
def potential(self):
"""Returns the number of nodes that could still be added below this node."""
return self.mass() - self.taken()
def taken(self):
"""Returns the number of nodes that live below this node."""
t = 0
if self.left is not None:
t += 1
if self.left.alive:
t += self.left.taken()
else:
t += self.left.mass()
if self.right is not None:
t += 1
if self.right.alive:
t += self.right.taken()
else:
t += self.right.mass()
return t
def __repr__(self):
return '<node: mass=%d, zeros=%s, ones=%s>' % (self.mass(),
str(self.zeros), str(self.ones))
def nodes(self, all=False):
"""Returns a list of all nodes that live at, or below, this point.
If all is False, return nodes only if they are stil alive.
"""
coll = []
if self.alive or all:
coll += [self]
if self.left is not None and (self.left.alive or all):
coll += self.left.nodes(all)
if self.right is not None and (self.right.alive or all):
coll += self.right.nodes(all)
return coll
def prune(self, upper):
"""Sets alive to False for any nodes in the tree with their lower less
than upper.
"""
# Note that we can use ceil(lower) instead of lower, because if we know
# that cardinality is > 18.3, say, we know it must be 19 or more.
if ceil(self.lower) > upper:
p = self.parent
while p is not None:
p.prunedmass += self.mass() + 1
p = p.parent
self.alive = False
else:
if self.left is not None and self.left.alive:
self.left.prune(upper)
if self.right is not None and self.right.alive:
self.right.prune(upper)
def argminl(nodes, Uglob):
"""Returns the node with lowest lower bound, from a list of nodes.
Only considers nodes which can still be expanded.
"""
m = min([x.lower for x in nodes if x.potential() > 0])
for x in nodes:
if x.lower == m:
return x
if __name__ == "__main__":
solvers.options['show_progress'] = False
# Randomly generate data.
random.setseed(3)
m,n = 100,30
A = random.normal(m,n)
x0 = random.normal(n,1)
b = A*x0 + 2*random.uniform(m,1)
# Find lower and upper bounds on each element of x. If we have that for a
# particular x_i, x_i > 0 or x_i < 0, we cannot hope to reduce the cardinality
# by setting that x_i to 0, so exclude index i from consideration by adding it
# to defones.
defones = []
mins = [0]*n
maxes = [0]*n
x = variable(n)
for i in range(n):
op(x[i], A*x <= b).solve()
if x.value[i] <= 0:
x.value[i] *= 1.0001
else:
x.value[i] *= 1/1.0001
mins[i] = x.value[i]
op(-x[i], A*x <= b).solve()
if x.value[i] <= 0:
x.value[i] *= 1/1.0001
else:
x.value[i] *= 1.0001
maxes[i] = x.value[i]
if mins[i] > 0:
defones.append(i)
if maxes[i] < 0:
defones.append(i)
# Later it is helpful to have these bounds stored in matrices.
min_mat = matrix(0, (n,n), tc='d')
min_mat[range(0, n**2, n+1)] = matrix(mins)
max_mat = matrix(0, (n,n), tc='d')
max_mat[range(0, n**2, n+1)] = matrix(maxes)
# Various data structures for later plotting.
uppers = []
lowers = []
masses = []
# Create the top node in the tree.
top = node(n, ones=defones)
top.stillplotted = False
Uglob = top.solve()
Lglob = -inf
nodes = [top]
leaves = [top]
masses = []
leavenums = []
massesind = []
oldline = None
iter = 0
# Expand the tree until the gap has disappeared.
while Uglob - Lglob > 1:
iter += 1
# Expand the leaf with lowest lower bound.
l = argminl(leaves, Uglob)
left = l.addleft()
right = l.addright()
leaves.remove(l)
leaves += [left, right]
Lglob = min([x.lower for x in leaves])
Uglob = min(Uglob, left.upper, right.upper)
lowers.append(Lglob)
uppers.append(Uglob)
for x in top.nodes():
# Prune anything except the currently optimal solution. Doesn't
# actually affect the progress of the algorithm.
if x.lower > Uglob and x.upper != Uglob:
x.alive = False
print "iter %3d. lower bound: %.5f, upper bound: %.0f" % (iter, Lglob, Uglob)
massesind.append(len(lowers))
masses.append(top.potential()/top.mass())
leavenums.append(len([1 for x in leaves if x.alive]))
print "done."
figure(1)
cla()
plot(uppers)
plot(lowers)
plot(ceil(lowers), 'g--')
legend(('upper bound', 'lower bound', 'ceiling (lower bound)'), loc='lower right')
axis((0,123,12,21.2))
xlabel('iteration')
ylabel('cardinality')
title('Global lower and upper bounds')
figure(2)
cla()
semilogy(massesind, masses)
xlabel('iteration')
ylabel('portion of non-pruned Boolean values')
title('Portion of non-pruned sparsity patterns')
axis((0,123,0.01,1.1))
figure(3)
cla()
plot(leavenums)
xlabel('iteration')
ylabel('number of leaves on tree')
title('Number of active leaves on tree')
axis((0,123,0,60))
show()
| Python |
#!/usr/bin/env python
"""Branch and bound code for a 30 variable cardinality problem.
Written by Jacob Mattingley, March 2007, for EE364b Convex Optimization II,
Stanford University, Professor Stephen Boyd.
This file solves a (random) instance of the problem:
minimize card(x)
subject to Ax <= b
using branch and bound, where x is the optimization variable and is in
{0,1}^30, A is in R^(100x30) and b is in R^(100x1).
"""
from __future__ import division
from pylab import *
from cvxopt import random, lapack, solvers
from cvxopt.base import matrix
from cvxopt.modeling import variable, op, max, sum
inf = float('inf')
def sign(x):
"""Returns the sign of an object by comparing with <= 0, with 0
arbitrarily assigned a sign of -1."""
if x <= 0:
return -1
else:
return 1
def rtz(x, tol=1e-3):
"""Rounds within-tol objects or entries of a matrix to exactly zero."""
if isinstance(x, matrix):
return matrix([rtz(y,tol) for y in x], x.size)
elif abs(x) <= tol:
return 0
else:
return x
def argmin(x, avoid=[]):
"""Returns the index of the minimum item in x with index not in the set
avoid."""
for i in range(len(x)):
if i in avoid:
x[i] = inf
for i in range(len(x)):
if x[i] == min(x):
return i
def card(x):
"""Returns the cardinality (number of non-zero entries) of x."""
return len([1 for y in rtz(x) if y != 0])
def funcfeas(x, tol=1e-3):
"""Determines if x is in the feasible set Ax <= b (with tolerance)."""
y = A*x
for i in range(len(y)):
if y[i] - b[i] > tol:
return False
return True
class node:
"""node([n[, zeros[, ones[, parent]]]]) -> node object
Create node of a branch-and-bound tree with size n. Known-zero or
known-one elements should be set using zeros and ones. Specify the
optional parent if the node is not at the top of the tree.
"""
def __init__(self, n, zeros=[], ones=[], parent=None):
if (set(zeros) & set(ones)):
raise Exception, 'cannot have item fixed to zero and fixed to one'
zeros.sort()
ones.sort()
self.zeros = zeros
self.ones = ones
self.parent = parent
self.left = None
self.right = None
self.n = n
self.alive = True
self.lower = inf
self.upper = inf
self.prunedmass = 0
def solve(self):
"""Find upper and lower bounds of the sub-problem belonging to
this node."""
x = variable(self.n)
z = variable(self.n)
constr = [z <= 1, z >= 0, x >= min_mat*z, x <= max_mat*z, A*x <= b]
for i in self.ones:
constr.append(z[i] == 1)
for i in self.zeros:
constr.append(z[i] == 0)
# Use cvxopt to solve the problem.
o = op(sum(z), constr)
o.solve()
if x.value is None:
# We couldn't find a solution.
self.raw = None
self.rounded = None
self.lower = inf
self.upper = inf
return inf
# Use heuristic to choose which variable we should split on next. Don't
# choose a variable we have already set.
self.picknext = argmin(list(rtz(abs(z.value - 0.5))), self.zeros + self.ones)
self.lower = sum(z.value)
if funcfeas(x.value):
self.upper = card(x.value)
else:
self.upper = inf
return self.upper
def mass(self, fullonly=True):
"""Find the number of nodes which could live below this node."""
p = self.n - len(self.zeros) - len(self.ones)
return 2**p
def addleft(self):
"""Add a node to the left-hand side of the tree and solve."""
if self.left is None:
self.left = node(self.n, self.zeros + [self.picknext], self.ones, self)
self.left.solve()
return self.left
def addright(self):
"""Add a node to the right-hand side of the tree and solve."""
if self.right is None:
self.right = node(self.n, self.zeros, self.ones + [self.picknext], self)
self.right.solve()
return self.right
def potential(self):
"""Returns the number of nodes that could still be added below this node."""
return self.mass() - self.taken()
def taken(self):
"""Returns the number of nodes that live below this node."""
t = 0
if self.left is not None:
t += 1
if self.left.alive:
t += self.left.taken()
else:
t += self.left.mass()
if self.right is not None:
t += 1
if self.right.alive:
t += self.right.taken()
else:
t += self.right.mass()
return t
def __repr__(self):
return '<node: mass=%d, zeros=%s, ones=%s>' % (self.mass(),
str(self.zeros), str(self.ones))
def nodes(self, all=False):
"""Returns a list of all nodes that live at, or below, this point.
If all is False, return nodes only if they are stil alive.
"""
coll = []
if self.alive or all:
coll += [self]
if self.left is not None and (self.left.alive or all):
coll += self.left.nodes(all)
if self.right is not None and (self.right.alive or all):
coll += self.right.nodes(all)
return coll
def prune(self, upper):
"""Sets alive to False for any nodes in the tree with their lower less
than upper.
"""
# Note that we can use ceil(lower) instead of lower, because if we know
# that cardinality is > 18.3, say, we know it must be 19 or more.
if ceil(self.lower) > upper:
p = self.parent
while p is not None:
p.prunedmass += self.mass() + 1
p = p.parent
self.alive = False
else:
if self.left is not None and self.left.alive:
self.left.prune(upper)
if self.right is not None and self.right.alive:
self.right.prune(upper)
def argminl(nodes, Uglob):
"""Returns the node with lowest lower bound, from a list of nodes.
Only considers nodes which can still be expanded.
"""
m = min([x.lower for x in nodes if x.potential() > 0])
for x in nodes:
if x.lower == m:
return x
if __name__ == "__main__":
solvers.options['show_progress'] = False
# Randomly generate data.
random.setseed(3)
m,n = 100,30
A = random.normal(m,n)
x0 = random.normal(n,1)
b = A*x0 + 2*random.uniform(m,1)
# Find lower and upper bounds on each element of x. If we have that for a
# particular x_i, x_i > 0 or x_i < 0, we cannot hope to reduce the cardinality
# by setting that x_i to 0, so exclude index i from consideration by adding it
# to defones.
defones = []
mins = [0]*n
maxes = [0]*n
x = variable(n)
for i in range(n):
op(x[i], A*x <= b).solve()
if x.value[i] <= 0:
x.value[i] *= 1.0001
else:
x.value[i] *= 1/1.0001
mins[i] = x.value[i]
op(-x[i], A*x <= b).solve()
if x.value[i] <= 0:
x.value[i] *= 1/1.0001
else:
x.value[i] *= 1.0001
maxes[i] = x.value[i]
if mins[i] > 0:
defones.append(i)
if maxes[i] < 0:
defones.append(i)
# Later it is helpful to have these bounds stored in matrices.
min_mat = matrix(0, (n,n), tc='d')
min_mat[range(0, n**2, n+1)] = matrix(mins)
max_mat = matrix(0, (n,n), tc='d')
max_mat[range(0, n**2, n+1)] = matrix(maxes)
# Various data structures for later plotting.
uppers = []
lowers = []
masses = []
# Create the top node in the tree.
top = node(n, ones=defones)
top.stillplotted = False
Uglob = top.solve()
Lglob = -inf
nodes = [top]
leaves = [top]
masses = []
leavenums = []
massesind = []
oldline = None
iter = 0
# Expand the tree until the gap has disappeared.
while Uglob - Lglob > 1:
iter += 1
# Expand the leaf with lowest lower bound.
l = argminl(leaves, Uglob)
left = l.addleft()
right = l.addright()
leaves.remove(l)
leaves += [left, right]
Lglob = min([x.lower for x in leaves])
Uglob = min(Uglob, left.upper, right.upper)
lowers.append(Lglob)
uppers.append(Uglob)
for x in top.nodes():
# Prune anything except the currently optimal solution. Doesn't
# actually affect the progress of the algorithm.
if x.lower > Uglob and x.upper != Uglob:
x.alive = False
print "iter %3d. lower bound: %.5f, upper bound: %.0f" % (iter, Lglob, Uglob)
massesind.append(len(lowers))
masses.append(top.potential()/top.mass())
leavenums.append(len([1 for x in leaves if x.alive]))
print "done."
figure(1)
cla()
plot(uppers)
plot(lowers)
plot(ceil(lowers), 'g--')
legend(('upper bound', 'lower bound', 'ceiling (lower bound)'), loc='lower right')
axis((0,123,12,21.2))
xlabel('iteration')
ylabel('cardinality')
title('Global lower and upper bounds')
figure(2)
cla()
semilogy(massesind, masses)
xlabel('iteration')
ylabel('portion of non-pruned Boolean values')
title('Portion of non-pruned sparsity patterns')
axis((0,123,0.01,1.1))
figure(3)
cla()
plot(leavenums)
xlabel('iteration')
ylabel('number of leaves on tree')
title('Number of active leaves on tree')
axis((0,123,0,60))
show()
| Python |
import sys
import numpy as np
import tree
import node
import cplex
#from cplex.exceptions import CplexError
def branchbound(c):
c.parameters.output.writelevel.set(0)
c.parameters.simplex.display.set(0)
rt = node.root(c)
tr = tree.tree(rt)
#tr.setup()
iter = 0
while True:
#-- we need to check limit
if iter >= 200:
break
if len(tr.nodeq) == 0:
print "node q is empty"
break
iter = iter + 1
#-- get node from the tree
nd = tr.pop()
#-- solve the node LP
nd.solve_lp()
# need better log information
print
print "--------------"
print "Iteration ", iter
print "node index", nd.node_ind
#print "node counts", nd.node_cnt[0]
print "objvalue", nd.z
print "current bound", nd.global_info["bound"]
print "current incumbent", nd.global_info["incumbent"]
print "objsolution", nd.lp.solution.get_values()
print "depth", nd.depth
print "lower bounds", nd.lo_bnds
print "lower bounds varialbes", nd.lo_vars
print "Upper bounds", nd.up_bnds
print "Upper bounds variables", nd.up_vars
print "Queue length", len(tr.nodeq)
print "--------------"
if nd.fathom_by_feasibility():
print "fathom by feasibility"
continue
elif nd.fathom_by_optimality():
print "fathom by optimality"
continue
elif nd.fathom_by_bound():
print "fathom by bound"
continue
else:
# nd.update_global_bound()
tr.branch(nd)
print "Optimal solution is", nd.global_info["incumbent"]
"""
if not nd.test_feasibility():
#tree.update_global_bounds (nd)
nd.fathom()
#continue
elif nd.test_integer():
#tr.update_global_bounds (nd)
nd.fathom()
#continue
elif nd.test_bound():
# tr.update_global_bounds (nd)
# nd.fathom()
# continue
else:
tr.branch(nd)
"""
#-- (we can check the bound here, but for simplicity today
#-- we go strait to branching)
#-- acoordinng to the status flag of the node
#-- three states
#-- 1. Infeasible: node.update
#-- 2. Integer feasible
#-- 3. Optimal noninteger
#-- 3.1 fathom by bound
#-- 3.2 branch
#-- node.status
#-- tree.update_xxx
#-- tree.update_incumbent(node)
#-- tree.update_bound(node)
#-- tree.branch(node)
#
#print
# check the solution status
#if c.solution.get_status() == 3:
# fathom by infeasibility
# get solution at node LP
#-- test integer feasibility
#End of while loop
def branchbound_batch(c):
c.parameters.output.writelevel.set(0)
c.parameters.simplex.display.set(0)
rt = node.root(c)
tr = tree.tree(rt)
iter = 0
while True:
if iter >= 500:
break
if len(tr.nodeq) == 0:
break
iter = iter + 1
nd = tr.pop()
nd.solve_lp()
if nd.fathom_by_feasibility():
continue
elif nd.fathom_by_optimality():
continue
elif nd.fathom_by_bound():
continue
else:
#tr.branch(nd)
nd.branch(tr)
return nd.global_info, iter
def report(solution, iter):
print "%20s " % solution["problem"],
print "%18.6f" % solution["incumbent"],
print "%10i" % solution["nodecnt"],
print "%10i" % iter
#print "Optimal solution is", nd.global_info["incumbent"]
#c = cplex.Cplex(" ")
#branchbound()
| Python |
#This example shows how to formulate the wyndor glass co. problem
#The way that we model this problem can be altered to use modeling language
#But We still need to be clear about the model to be able to manipulate it
import cplex
from cplex.exceptions import CplexError
import sys
import numpy as np
c = cplex.Cplex()
#c.parameters.simplex.display.set(2)
#set objective sense
c.objective.set_sense(c.objective.sense.maximize)
#set variables
c.variables.add(names=["x1","x2"],
lb = [0,0],
ub = [cplex.infinity, cplex.infinity],
obj = [3, 5])
rhss = np.random.uniform(size=3)
#set constraints
c.linear_constraints.add(lin_expr = [[[0],[1.0]],
[[1],[2.0]],
[[0,1],[3.0, 2.0]]],
senses = ["L","L","L"],
rhs = rhss,
names = ["c1","c2","c3"])
#rhs = [4.0, 12.0, 18.0],
#[cplex.SparsePair(ind=["x1"], val=[1.0]),
# cplex.SparsePair(ind=["x2"], val=[2.0]),
# cplex.SparsePair(ind=["x1","x2"], val=[3.0, 2.0])],
c.solve()
sol = c.solution
print
# print out problem info
#print c.linear_constraints.get_rows()
# solution.get_status() returns an integer code
print "Solution status = " , sol.get_status(), ":",
# the following line prints the corresponding string
print sol.status[sol.get_status()]
# get solutions
print "Solutions: ", sol.get_values()
# get objective values
print "Objective values: " , sol.get_objective_value()
| Python |
#This example shows how to formulate the wyndor glass co. problem
#The way that we model this problem can be altered to use modeling language
#But We still need to be clear about the model to be able to manipulate it
import cplex
from cplex.exceptions import CplexError
import sys
import numpy as np
c = cplex.Cplex()
#c.parameters.simplex.display.set(2)
#set objective sense
c.objective.set_sense(c.objective.sense.maximize)
#set variables
c.variables.add(names=["x1","x2"],
lb = [0,0],
ub = [cplex.infinity, cplex.infinity],
obj = [3, 5])
rhss = np.random.uniform(size=3)
#set constraints
c.linear_constraints.add(lin_expr = [[[0],[1.0]],
[[1],[2.0]],
[[0,1],[3.0, 2.0]]],
senses = ["L","L","L"],
rhs = rhss,
names = ["c1","c2","c3"])
#rhs = [4.0, 12.0, 18.0],
#[cplex.SparsePair(ind=["x1"], val=[1.0]),
# cplex.SparsePair(ind=["x2"], val=[2.0]),
# cplex.SparsePair(ind=["x1","x2"], val=[3.0, 2.0])],
c.solve()
sol = c.solution
print
# print out problem info
#print c.linear_constraints.get_rows()
# solution.get_status() returns an integer code
print "Solution status = " , sol.get_status(), ":",
# the following line prints the corresponding string
print sol.status[sol.get_status()]
# get solutions
print "Solutions: ", sol.get_values()
# get objective values
print "Objective values: " , sol.get_objective_value()
| Python |
import cplex
import sys
def cpxsol(c):
c.parameters.mip.display.set(0)
c.parameters.preprocessing.presolve.set(0)
c.solve()
return c.solution.get_objective_value()
#cpxsol(c)
| Python |
import heapq
import cplex
import node
class tree:
def __init__(self, root):
self.global_up_bnd = 0
self.global_z = 0
# store the nodes in a priority queue
self.nodeq = []
heapq.heappush(self.nodeq, root)
def pop(self):
# pop the node with least priority
node = heapq.heappop(self.nodeq)
return node
def branch(self, parent):
#generate two child node and then push them into the tree
parent.set_branch_var()
child1 = node.node(parent, "UP")
child2 = node.node(parent, "DOWN")
heapq.heappush(self.nodeq, child1)
heapq.heappush(self.nodeq, child2)
# or node.remove(bbtree)
#def update_bound(self, node):
#compare node.z and tree.global_z
#def update_incumbent(self, ):
| Python |
import sys
import numpy as np
import heapq
from copy import copy, deepcopy
from math import ceil, floor
import cplex
class root:
def __init__(self, mip = None):
#need to organize the attributes
self.lp = mip
self.rootlp = cplex.Cplex( mip )
# convert the mip problem to lp problem
if self.lp.get_problem_type() == 1:
self.lp.set_problem_type(type = 0)
elif self.lp.get_problem_type() == 0:
print "Entered a LP program, solved at the root node"
else :
print "Not processing a mip problem"
sys.exit()
# convert the sense to minimization here
self.sense = self.lp.objective.get_sense()
# 1 minimization
# -1 minimization
#self.up_bnd = self.lp.variables.get_upper_bounds()
#self.lo_bnd = self.lp.variables.get_lower_bounds()
self.org_up_bnds = self.lp.variables.get_upper_bounds()
self.org_lo_bnds = self.lp.variables.get_lower_bounds()
# indices of variables to be fixed
self.lo_vars = []
self.up_vars = []
# values of the bounds
self.lo_bnds = []
self.up_bnds = []
# local node info
self.bound = 0 # bound inherited from the parent node
self.depth = 0 # depth in the branch and bound tree
self.z = 0.0 # lp optimal solution
self.bvar_ind = 0 #index of branching variable
self.bvar_val = 0.0 #value of branching variable
self.cmp_method = "depth"
#self.cmp_method = "bound"
self.status =""
# global info
if self.sense == 1: # min
self.global_info = {'bound':1000000000,
'incumbent':100000000,
'nodecnt':1,
'problem':self.lp.get_problem_name()}
else: # max
self.global_info = {'bound':-1000000000,
'incumbent':-100000000,
'nodecnt':1,
'problem':self.lp.get_problem_name()}
self.node_ind = self.global_info['nodecnt']
def solve_lp(self):
self.lp.solve()
#update attributes of the object
if self.sense == 1: # min
self.z = ceil( self.lp.solution.get_objective_value() )
else: #max
self.z = floor( self.lp.solution.get_objective_value() )
# self.z = self.lp.solution.get_objective_value()
#heapq.heappush(self.bound_queue, self.z)
# Another bounding options are Lagragian relaxation
# or column generation. Both will give better bound
# but takes more time to finish
# def bound_by_lr(self):
# def bound_by_cg(self):
def fathom_by_feasibility(self):
# infeasible
if self.lp.solution.get_status() == 3:
self.revert_variable_bounds()
return True
else:
return False
def fathom_by_optimality(self):
x = np.array( self.lp.solution.get_values() )
#consider the numerical issues
for i in range(len(x)):
if abs(x[i] - round(x[i])) < 0.000001:
x[i] = round(x[i])
#the efficiency can be improved here
if not (x - np.floor(x)).any():
# integer feasible then update the node optimal value
# print 'fathom by optimality'
self.status = "optimality"
# update incumbent
if self.sense == 1: # minimization
self.global_info['incumbent']= min(self.z, self.global_info['incumbent'])
else: # maximization
self.global_info['incumbent']= max(self.z, self.global_info['incumbent'])
self.revert_variable_bounds()
return True
else:
return False
def fathom_by_bound(self):
if self.z >= self.global_info['incumbent'] and \
self.sense == 1: #minimization
self.revert_variable_bounds()
return True
elif self.z <= self.global_info['incumbent'] and \
self.sense == -1: #maximization
self.revert_variable_bounds()
return True
else:
return False
def revert_variable_bounds(self):
#Revert the bounds before removal of each node
if len(self.lo_vars) != 0:
org_lo_bnds = self.rootlp.variables.get_lower_bounds(self.lo_vars)
self.lp.variables.set_lower_bounds( zip(self.lo_vars, org_lo_bnds) )
if len(self.up_vars) != 0:
org_up_bnds = self.rootlp.variables.get_upper_bounds(self.up_vars)
self.lp.variables.set_upper_bounds( zip(self.up_vars, org_up_bnds) )
def set_branch_var(self):
# find the branching variable if needed
x = np.array( self.lp.solution.get_values() )
x_int_frac_min = np.minimum( x - np.floor(x) , np.ceil(x) - x)
self.bvar_ind = np.argmax( x_int_frac_min )
self.bvar_val = x[self.bvar_ind]
#print "branching variable index", self.bvar_ind
#print "branching variable value", self.bvar_val
self.revert_variable_bounds()
# this branch method does the samething as the branch method in tree class
def branch(self, tree):
self.set_branch_var()
child1 = node(self, "UP")
child2 = node(self, "DOWN")
heapq.heappush(tree.nodeq, child1)
heapq.heappush(tree.nodeq, child2)
class node(root):
# overload the constructor
def __init__(self, parent, bdir = None):
# copy parent info
# the lists bounds
self.lo_vars = copy(parent.lo_vars)
self.up_vars = copy(parent.up_vars)
self.lo_bnds= copy(parent.lo_bnds)
self.up_bnds= copy(parent.up_bnds)
# modify global info
self.global_info = parent.global_info
self.global_info['nodecnt'] += 1 #increase node counts
self.node_ind = self.global_info['nodecnt']
# copy the lp problem
self.lp = parent.lp
self.rootlp = parent.rootlp
# copy a few other attributes
self.cmp_method = parent.cmp_method
self.bound = parent.z
self.depth = parent.depth+1
self.sense = parent.sense
# initiate local variables
self.z = 0.0
self.bvar_ind = 0
self.bvar_val = 0.0
self.status = ""
# Expand the fixed variable lists according to branching directions
if bdir == "UP":
#self.node_ind = parent.node_ind + 1
self.dir = 1
#self.lo_bnd[parent.bvar_ind] = ceil(parent.bvar_val)
self.lo_vars.append( parent.bvar_ind )
self.lo_bnds.append( ceil(parent.bvar_val) )
else:
#self.node_ind = parent.node_ind + 2
self.dir = -1
#self.up_bnd[parent.bvar_ind] = floor(parent.bvar_val)
self.up_vars.append( parent.bvar_ind )
self.up_bnds.append( floor(parent.bvar_val) )
def __lt__(self, other):
#compare the two objects by its depth or bound
if self.cmp_method == "depth":
return (self.depth, self.dir) > \
(other.depth, other.dir)
elif self.cmp_method == "bound":
return (self.bound, self.depth) > \
(other.bound, other.depth)
def solve_lp(self):
var = self.lp.variables.get_names()
#print "self.vars", self.vars
#print "self.lo_bnd", self.lo_bnds
#print "self.up_bnd", self.up_bnds
# fix the variables
if len(self.lo_vars) != 0:
self.lp.variables.set_lower_bounds( zip(self.lo_vars, self.lo_bnds) )
if len(self.up_vars) != 0:
self.lp.variables.set_upper_bounds( zip(self.up_vars, self.up_bnds) )
# solve the lp relaxation
self.lp.solve()
# record the optimal value for bounding
self.z = self.lp.solution.get_objective_value()
# def heur_dive_and_fix(self)
# def heur_cut_and_fix(self)
# def heur_relax_and_fix(self)
| Python |
import sys
import cplex
import numpy as np
from cplex.exceptions import CplexError
# c.variables.set_lower_bounds to fix values at 0 or 1
# c.solution.get_status() to know the status for logical control
# 1. optimal
# 2. unbounded
# 3. infeasible
# This function is going to be called over again
#--
def backtrack(c, P, S, V, lb, ub):
#print 'Starting backtrack'
#print 'P', P, 'S', S, 'V', V
idx = 0
if len(P) == 0:
# print 'Already at the root'
return []
# check the sign last elements of P
while P[-1] > 0:
# skip through all fathomed nodes
idx = abs(P[-1]) - 1
# mMdify the node bounds
if S[-1] == -1:
c.variables.set_upper_bounds( idx, ub[idx] ) #relax the upper bound
else:
c.variables.set_lower_bounds( idx, lb[idx] ) #relax the lower bound
# Modify the tree
P.pop()
S.pop()
V.pop()
#print 'backtrack one level'
#print 'P', P, 'S', S, 'V', V
if len(P) == 0:
break
# if back to the root, return
if len(P) == 0:
return []
# now the idx is changed
idx = abs(P[-1]) - 1
# then change the sign of S
if S[-1] == -1:
c.variables.set_upper_bounds( idx, ub[idx] )
c.variables.set_lower_bounds( idx, V[-1] + 1 )
V[-1] = V[-1] + 1
else:
c.variables.set_lower_bounds( idx, lb[idx] )
c.variables.set_upper_bounds( idx, V[-1] - 1 )
V[-1] = V[-1] - 1
P[-1] = -P[-1]
S[-1] = -S[-1]
#print 'Finish backtracking'
#print 'P', P, 'S', S, 'V', V
return []
#End of backtrack function
def branchbound(c):
c.parameters.output.writelevel.set(0)
# record index of binary variables
int_var_idx = []
con_var_idx = []
for i in range(c.variables.get_num()):
if c.variables.get_types(i) != 'C':
int_var_idx.append(i)
else:
con_var_idx.append(i)
# change the type from MILP into LP (0:LP, 1:MILP)
c.set_problem_type(type=0)
# store the original bounds
ub = c.variables.get_upper_bounds()
lb = c.variables.get_lower_bounds()
sense = c.objective.get_sense()
# three vectors to track the progress of tree search process
# use three list to store the information
#-- information here can be packed into the tree object
P = [] # P: path vector
S = [] # S: sign vector (the sign indicate the bound value)
V = [] # V: value vector
s = 0
v = 0.0
v_up = 0.0
v_lo = 0.0
v_fr = 0.0
branch_var = 0
branch_dir = 0
# consider min and max problem
# declare global z and node z
if sense == -1: #maximization
z_global = -10000000
else: #minimization
z_global = 10000000
z_node = 0
iter = 0
c.parameters.simplex.display.set(0)
while True:
#-- we need to check limit
iter = iter + 1
#-- get node from the tree
#-- node = bbtree.pop()
#-- solve the node LP
#-- node.solveLP()
c.solve()
#-- acoordinng to the status flag of the node
#-- three states
#-- 1. Infeasible: node.update
#-- 2. Integer feasible
#-- 3. Optimal noninteger
#-- 3.1 fathom by bound
#-- 3.2 branch
#-- node.status
#-- tree.update_xxx
#-- tree.update_incumbent(node)
#-- tree.update_bound(node)
#-- tree.branch(node)
#
#--
#-- child1, child2 = node.branch()
#print
#print 'Iteratation', iter
#print 'status', c.solution.get_status_string(), c.solution.get_status()
# check the solution status
if c.solution.get_status() == 3:
# fathom by infeasibility
# update P and S and add modify c
# print 'fathom by infeasiblity'
backtrack(c, P, S, V, lb, ub)
else:
# get solution at node LP
x = np.array( c.solution.get_values() )
if not (x - np.floor(x))[int_var_idx].any():
# integer feasible then update the node optimal value
# print 'fathom by optimality'
z_node = c.solution.get_objective_value()
if sense == -1: #maximization
z_global = max(z_node, z_global)
else: #minimization
z_global = min(z_node, z_global)
# fathom by integrality and then backtrack
backtrack(c, P, S, V, lb, ub)
else:
# integer infeasible then check the bounds
z_node = c.solution.get_objective_value()
if z_node <= z_global and sense == -1: #maximization
# fathom by bounds and backtrack
# print 'fathom by bounds'
backtrack(c, P, S, V, lb, ub)
elif z_node >= z_global and sense == 1: #minimization
# print 'fathom by bounds'
backtrack(c, P, S, V, lb, ub)
else:
#-- Apply branching variable selection
# select branch variable
x_int_frac_min = np.minimum( x - np.floor(x) , np.ceil(x) - x)
# set the value of continuous variable to be zero
x_int_frac_min[con_var_idx] = 0
s = np.argmax( x_int_frac_min )
# v = c.solution.get_values(s)
v = x[s]
v_up = np.ceil(v)
v_lo = np.floor(v)
v_fr = v - v_lo
### update P and S and modify c and go the next node always go left
P.append(-s - 1)
# print 's', s
#-- Apply branch direction selection
branch_var = s
if v_fr <= 0.5:
# go left
S.append(-1)
V.append(v_lo)
c.variables.set_upper_bounds(s, v_lo)
branch_dir = -1
else:
#go right
S.append(1)
V.append(v_up)
c.variables.set_lower_bounds(s, v_up)
branch_dir = +1
# print c.variables.get_lower_bounds()
#print 'branching variable:', branch_var, 'branching direction', branch_dir
#print '----------------'
#print 'z_node' , z_node
#print 'z_global', z_global
if len(P) == 0:
break
#End of while loop
#print
#print 'Final solution:'
#print 'z_node', z_node
#print 'z_global', z_global
print z_global
#branchbound()
| Python |
import sys
import cplex
import numpy as np
from cplex.exceptions import CplexError
# c.variables.set_lower_bounds to fix values at 0 or 1
# c.solution.get_status() to know the status for logical control
# 1. optimal
# 2. unbounded
# 3. infeasible
# This function is going to be called over again
def backtrack(c, P, S, V, lb, ub):
print 'Starting backtrack'
print 'P', P, 'S', S, 'V', V
idx = 0
if len(P) == 0:
print 'Already at the root'
return []
# check the sign last elements of P
while P[-1] > 0:
# skip through all fathomed nodes
idx = abs(P[-1]) - 1
if S[-1] == -1:
c.variables.set_upper_bounds( idx, ub[idx] ) #relax the upper bound
else:
c.variables.set_lower_bounds( idx, lb[idx] ) #relax the lower bound
P.pop()
S.pop()
V.pop()
print 'backtrack one level'
print 'P', P, 'S', S, 'V', V
if len(P) == 0:
break
# if back to the root, return
if len(P) == 0:
return []
# now the idx is changed
idx = abs(P[-1]) - 1
# then change the sign of S
if S[-1] == -1:
c.variables.set_upper_bounds( idx, ub[idx] )
c.variables.set_lower_bounds( idx, V[-1] + 1 )
V[-1] = V[-1] + 1
else:
c.variables.set_lower_bounds( idx, lb[idx] )
c.variables.set_upper_bounds( idx, V[-1] - 1 )
V[-1] = V[-1] - 1
P[-1] = -P[-1]
S[-1] = -S[-1]
print 'Finish backtracking'
print 'P', P, 'S', S, 'V', V
return []
#End of backtrack function
def branchbound():
ca = cplex.Cplex()
ca.read(sys.argv[1])
#copy ca to c for self processing
c = cplex.Cplex(ca)
c.parameters.output.writelevel.set(0)
# record index of binary variables
int_var_idx = []
con_var_idx = []
for i in range(c.variables.get_num()):
if c.variables.get_types(i) != 'C':
int_var_idx.append(i)
else:
con_var_idx.append(i)
# change the type from MILP into LP (0:LP, 1:MILP)
c.set_problem_type(type=0)
ub = c.variables.get_upper_bounds()
lb = c.variables.get_lower_bounds()
sense = c.objective.get_sense()
# three vectors to track the progress of tree search process
# use three list to store the information
P = [] # P: path vector
S = [] # S: sign vector (the sign indicate the bound value)
V = [] # V: value vector
s = 0
v = 0.0
v_up = 0.0
v_lo = 0.0
v_fr = 0.0
branch_var = 0
branch_dir = 0
# consider min and max problem
# declare global z and node z
if sense == -1: #maximization
z_global = -10000000
else: #minimization
z_global = 10000000
z_node = 0
iter = 0
c.parameters.simplex.display.set(0)
while True:
# be ready to solve the node LP
iter = iter + 1
c.solve()
print
print 'Iteratation', iter
print 'status', c.solution.get_status_string(), c.solution.get_status()
# check the solution status
if c.solution.get_status() == 3:
# fathom by infeasibility
# update P and S and add modify c
print 'fathom by infeasiblity'
backtrack(c, P, S, V, lb, ub)
else:
# get solution at node LP
x = np.array( c.solution.get_values() )
if not (x - np.floor(x))[int_var_idx].any():
# integer feasible then update the node optimal value
print 'fathom by optimality'
z_node = c.solution.get_objective_value()
if sense == -1: #maximization
z_global = max(z_node, z_global)
else: #minimization
z_global = min(z_node, z_global)
# fathom by integrality and then backtrack
backtrack(c, P, S, V, lb, ub)
else:
# integer infeasible then check the bounds
z_node = c.solution.get_objective_value()
if z_node <= z_global and sense == -1: #maximization
# fathom by bounds and backtrack
print 'fathom by bounds'
backtrack(c, P, S, V, lb, ub)
elif z_node >= z_global and sense == 1: #minimization
print 'fathom by bounds'
backtrack(c, P, S, V, lb, ub)
else:
# select branch variable
x_int_frac_min = np.minimum( x - np.floor(x) , np.ceil(x) - x)
x_int_frac_min[con_var_idx] = 0
s = np.argmax( x_int_frac_min )
# v = c.solution.get_values(s)
v = x[s]
v_up = np.ceil(v)
v_lo = np.floor(v)
v_fr = v - v_lo
### update P and S and modify c and go the next node always go left
P.append(-s - 1)
# print 's', s
branch_var = s
if v_fr <= 0.5:
# go left
S.append(-1)
V.append(v_lo)
c.variables.set_upper_bounds(s, v_lo)
branch_dir = -1
else:
#go right
S.append(1)
V.append(v_up)
c.variables.set_lower_bounds(s, v_up)
branch_dir = +1
# print c.variables.get_lower_bounds()
print 'branching variable:', branch_var, 'branching direction', branch_dir
print '----------------'
print 'z_node' , z_node
print 'z_global', z_global
if len(P) == 0:
break
#End of while loop
print
print 'Final solution:'
print 'z_node', z_node
print 'z_global', z_global
branchbound()
| Python |
import sys
import cplex
import numpy as np
from cplex.exceptions import CplexError
ca = cplex.Cplex()
ca.read(sys.argv[1])
#ca.read("bell5.mps")
#copy ca to c for self processing
c = cplex.Cplex(ca)
# change the type from MILP into LP (0:LP, 1:MILP)
c.set_problem_type(type=0)
# c.solve()
# d.solve()
# three vectors to track the progress of tree search process
# use three list to store the information
# P: path vector
# S: sign vector (the sign indicate the bound value)
P = []
S = []
s = 0
# declare global z and node z
z_global = -10000000
z_node = 0
# c.variables.set_lower_bounds to fix values at 0 or 1
# c.solution.get_status() to know the status for logical control
# 1. optimal
# 2. unbounded
# 3. infeasible
#
#
# convert output from cplex into numpy ndarray format
# x = np.array(x)
#
# Branching variable selection:
# For branching on the most fractional variable
# Test whether solution of LP is integer feasible
# if yes, fathom the node by integrality
# if false, we should trace the index of most fractional
# variable
#
# s = argmax(np.minimum( x - np.floor(x) , np.ceil(x) - x) )
#
# then branch up by modifying upper bound of x_s
#
# c.variables.set_upper_bounds(s, 1)
#
# or branch down by modifying lower bound of x_s
#
# c.variables.set_lower_bounds(s, 0)
def backtrack(c, P, S):
#print len(P), len(S)
#print P[-1], S[-1]
if len(P) == 0:
return []
# check the sign last elements of P
while P[-1] > 0:
# skip through all fathomed nodes
if S[-1] == -1:
c.variables.set_upper_bounds( abs(P[-1]) - 1, 1 )
else:
c.variables.set_lower_bounds( abs(P[-1]) - 1, 0 )
P.pop()
S.pop()
if len(P) == 0:
break
# if back to the root, return
if len(P) == 0:
return []
# then change the sign of S
if S[-1] == -1:
c.variables.set_upper_bounds( abs(P[-1]) - 1, 1 )
c.variables.set_lower_bounds( abs(P[-1]) - 1, 1 )
else:
c.variables.set_lower_bounds( abs(P[-1]) - 1, 0 )
c.variables.set_upper_bounds( abs(P[-1]) - 1, 0 )
P[-1] = -P[-1]
S[-1] = -S[-1]
print 'P', P, 'S', S
return
#End of backtrack function
iter = 0
while True:
# be ready to solve the node LP
iter = iter + 1
c.solve()
print 'Iteratation', iter
print 'status', c.solution.get_status_string(), c.solution.get_status()
# check the solution status
if c.solution.get_status() == 3:
# fathom by infeasibility
# update P and S and add modify c
backtrack(c, P, S)
print 'visit here'
else:
# get solution at node LP
x = np.array(c.solution.get_values())
# check integer feasibility
if (x - np.floor(x)).any():
# integer infeasible then check the bounds
z_node = c.solution.get_objective_value()
if z_node <= z_global:
# fathom by bounds and then backtrack
backtrack(c, P, S)
# then choose the branching variable
s = np.argmax(np.minimum( x - np.floor(x) , np.ceil(x) - x) )
### update P and S and modify c and go the next node always go left
P.append(-s - 1)
c.variables.get_lower_bounds()
print 's', s
# go left
# S.append(-1)
# c.variables.set_upper_bounds(s, 0)
#go right
S.append(1)
c.variables.set_lower_bounds(s, 1)
else:
# integer feasible then update the node optimal value
z_node = c.solution.get_objective_value()
z_global = max(z_node, z_global)
# fathom by integrality
backtrack(c, P, S)
print P
print S
print x
print 'z_node', z_node
print 'z_global', z_global
if len(P) == 0:
break
# post processing
#sol = c.solution
#print
# print out problem info
#print c.linear_constraints.get_rows()
# solution.get_status() returns an integer code
#print "Solution status = " , sol.get_status(), ":",
#print sol.status[sol.get_status()]
#print "Solutions: ", sol.get_values()
#print "Objective values: " , sol.get_objective_value()
| Python |
import sys
import cplex
import numpy as np
from cplex.exceptions import CplexError
ca = cplex.Cplex()
ca.read(sys.argv[1])
#copy ca to c for self processing
c = cplex.Cplex(ca)
c.parameters.output.writelevel.set(0)
# record index of binary variables
int_var_idx = []
con_var_idx = []
for i in range(c.variables.get_num()):
if c.variables.get_types(i) != 'C':
int_var_idx.append(i)
else:
con_var_idx.append(i)
# change the type from MILP into LP (0:LP, 1:MILP)
c.set_problem_type(type=0)
ub = c.variables.get_upper_bounds()
lb = c.variables.get_lower_bounds()
sense = c.objective.get_sense()
# three vectors to track the progress of tree search process
# use three list to store the information
P = [] # P: path vector
S = [] # S: sign vector (the sign indicate the bound value)
V = [] # V: value vector
s = 0
v = 0.0
v_up = 0.0
v_lo = 0.0
v_fr = 0.0
branch_var = 0
branch_dir = 0
# consider min and max problem
# declare global z and node z
if sense == -1: #maximization
z_global = -10000000
else: #minimization
z_global = 10000000
z_node = 0
# c.variables.set_lower_bounds to fix values at 0 or 1
# c.solution.get_status() to know the status for logical control
# 1. optimal
# 2. unbounded
# 3. infeasible
# convert output from cplex into numpy ndarray format
# x = np.array(x)
#
# Branching variable selection:
# For branching on the most fractional variable
# Test whether solution of LP is integer feasible
# if yes, fathom the node by integrality
# if false, we should trace the index of most fractional
# variable
#
# s = argmax(np.minimum( x - np.floor(x) , np.ceil(x) - x) )
#
# then branch up by modifying upper bound of x_s
#
# c.variables.set_upper_bounds(s, 1)
#
# or branch down by modifying lower bound of x_s
#
# c.variables.set_lower_bounds(s, 0)
def backtrack(c, P, S, V, lb, ub):
print 'Starting backtrack'
print 'P', P, 'S', S, 'V', V
idx = 0
if len(P) == 0:
print 'Already at the root'
return []
# check the sign last elements of P
while P[-1] > 0:
# skip through all fathomed nodes
idx = abs(P[-1]) - 1
if S[-1] == -1:
c.variables.set_upper_bounds( idx, ub[idx] ) #relax the upper bound
else:
c.variables.set_lower_bounds( idx, lb[idx] ) #relax the lower bound
P.pop()
S.pop()
V.pop()
print 'backtrack one level'
print 'P', P, 'S', S, 'V', V
if len(P) == 0:
break
# if back to the root, return
if len(P) == 0:
return []
# now the idx is changed
idx = abs(P[-1]) - 1
# then change the sign of S
if S[-1] == -1:
c.variables.set_upper_bounds( idx, ub[idx] )
c.variables.set_lower_bounds( idx, V[-1] + 1 )
V[-1] = V[-1] + 1
else:
c.variables.set_lower_bounds( idx, lb[idx] )
c.variables.set_upper_bounds( idx, V[-1] - 1 )
V[-1] = V[-1] - 1
P[-1] = -P[-1]
S[-1] = -S[-1]
print 'Finish backtracking'
print 'P', P, 'S', S, 'V', V
return []
#End of backtrack function
iter = 0
c.parameters.simplex.display.set(0)
while True:
# be ready to solve the node LP
iter = iter + 1
c.solve()
print
print 'Iteratation', iter
print 'status', c.solution.get_status_string(), c.solution.get_status()
#print 'current upper bound', c.variables.get_lower_bounds()
#print 'cuurent lower bound', c.variables.get_upper_bounds()
# check the solution status
if c.solution.get_status() == 3:
# fathom by infeasibility
# update P and S and add modify c
print 'fathom by infeasiblity'
backtrack(c, P, S, V, lb, ub)
else:
# get solution at node LP
x = np.array( c.solution.get_values() )
if not (x - np.floor(x))[int_var_idx].any():
# integer feasible then update the node optimal value
print 'fathom by optimality'
z_node = c.solution.get_objective_value()
if sense == -1: #maximization
z_global = max(z_node, z_global)
else: #minimization
z_global = min(z_node, z_global)
# fathom by integrality and then backtrack
backtrack(c, P, S, V, lb, ub)
else:
# integer infeasible then check the bounds
z_node = c.solution.get_objective_value()
if z_node <= z_global and sense == -1: #maximization
# fathom by bounds and backtrack
print 'fathom by bounds'
backtrack(c, P, S, V, lb, ub)
elif z_node >= z_global and sense == 1: #minimization
print 'fathom by bounds'
backtrack(c, P, S, V, lb, ub)
else:
# select branch variable
x_int_frac_min = np.minimum( x - np.floor(x) , np.ceil(x) - x)
x_int_frac_min[con_var_idx] = 0
s = np.argmax( x_int_frac_min )
# v = c.solution.get_values(s)
v = x[s]
v_up = np.ceil(v)
v_lo = np.floor(v)
v_fr = v - v_lo
### update P and S and modify c and go the next node always go left
P.append(-s - 1)
# print 's', s
branch_var = s
if v_fr <= 0.5:
# go left
S.append(-1)
V.append(v_lo)
c.variables.set_upper_bounds(s, v_lo)
branch_dir = -1
else:
#go right
S.append(1)
V.append(v_up)
c.variables.set_lower_bounds(s, v_up)
branch_dir = +1
# print c.variables.get_lower_bounds()
print 'branching variable:', branch_var, 'branching direction', branch_dir
print '----------------'
print 'z_node' , z_node
print 'z_global', z_global
if len(P) == 0:
break
#End of while loop
print
print 'Final solution:'
print 'z_node', z_node
print 'z_global', z_global
# post processing
#sol = c.solution
#print
# print out problem info
# solution.get_status() returns an integer code
#print "Solution status = " , sol.get_status(), ":",
#print sol.status[sol.get_status()]
#print "Solutions: ", sol.get_values()
#print "Objective values: " , sol.get_objective_value()
| Python |
import sys
import cplex
import numpy as np
from cplex.exceptions import CplexError
# c.variables.set_lower_bounds to fix values at 0 or 1
# c.solution.get_status() to know the status for logical control
# 1. optimal
# 2. unbounded
# 3. infeasible
# This function is going to be called over again
def backtrack_v(c, P, S, V, lb, ub):
print 'Starting backtrack'
print 'P', P, 'S', S, 'V', V
idx = 0
if len(P) == 0:
print 'Already at the root'
return []
# check the sign last elements of P
while P[-1] > 0:
# skip through all fathomed nodes
idx = abs(P[-1]) - 1
if S[-1] == -1:
c.variables.set_upper_bounds( idx, ub[idx] ) #relax the upper bound
else:
c.variables.set_lower_bounds( idx, lb[idx] ) #relax the lower bound
P.pop()
S.pop()
V.pop()
print 'backtrack one level'
print 'P', P, 'S', S, 'V', V
if len(P) == 0:
break
# if back to the root, return
if len(P) == 0:
return []
# now the idx is changed
idx = abs(P[-1]) - 1
# then change the sign of S
if S[-1] == -1:
c.variables.set_upper_bounds( idx, ub[idx] )
c.variables.set_lower_bounds( idx, V[-1] + 1 )
V[-1] = V[-1] + 1
else:
c.variables.set_lower_bounds( idx, lb[idx] )
c.variables.set_upper_bounds( idx, V[-1] - 1 )
V[-1] = V[-1] - 1
P[-1] = -P[-1]
S[-1] = -S[-1]
print 'Finish backtracking'
print 'P', P, 'S', S, 'V', V
return []
#End of backtrack function
def branchbound_v(c):
# ca = cplex.Cplex()
# ca.read(sys.argv[1])
#copy ca to c for self processing
# c = cplex.Cplex(ca)
c.parameters.output.writelevel.set(0)
# record index of binary variables
int_var_idx = []
con_var_idx = []
for i in range(c.variables.get_num()):
if c.variables.get_types(i) != 'C':
int_var_idx.append(i)
else:
con_var_idx.append(i)
# change the type from MILP into LP (0:LP, 1:MILP)
c.set_problem_type(type=0)
ub = c.variables.get_upper_bounds()
lb = c.variables.get_lower_bounds()
sense = c.objective.get_sense()
# three vectors to track the progress of tree search process
# use three list to store the information
P = [] # P: path vector
S = [] # S: sign vector (the sign indicate the bound value)
V = [] # V: value vector
s = 0
v = 0.0
v_up = 0.0
v_lo = 0.0
v_fr = 0.0
branch_var = 0
branch_dir = 0
# consider min and max problem
# declare global z and node z
if sense == -1: #maximization
z_global = -10000000
else: #minimization
z_global = 10000000
z_node = 0
iter = 0
c.parameters.simplex.display.set(0)
while True:
# be ready to solve the node LP
iter = iter + 1
c.solve()
print
print 'Iteratation', iter
print 'status', c.solution.get_status_string(), c.solution.get_status()
# check the solution status
if c.solution.get_status() == 3:
# fathom by infeasibility
# update P and S and add modify c
print 'fathom by infeasiblity'
backtrack(c, P, S, V, lb, ub)
else:
# get solution at node LP
x = np.array( c.solution.get_values() )
if not (x - np.floor(x))[int_var_idx].any():
# integer feasible then update the node optimal value
print 'fathom by optimality'
z_node = c.solution.get_objective_value()
if sense == -1: #maximization
z_global = max(z_node, z_global)
else: #minimization
z_global = min(z_node, z_global)
# fathom by integrality and then backtrack
backtrack(c, P, S, V, lb, ub)
else:
# integer infeasible then check the bounds
z_node = c.solution.get_objective_value()
if z_node <= z_global and sense == -1: #maximization
# fathom by bounds and backtrack
print 'fathom by bounds'
backtrack(c, P, S, V, lb, ub)
elif z_node >= z_global and sense == 1: #minimization
print 'fathom by bounds'
backtrack(c, P, S, V, lb, ub)
else:
# select branch variable
x_int_frac_min = np.minimum( x - np.floor(x) , np.ceil(x) - x)
x_int_frac_min[con_var_idx] = 0
s = np.argmax( x_int_frac_min )
# v = c.solution.get_values(s)
v = x[s]
v_up = np.ceil(v)
v_lo = np.floor(v)
v_fr = v - v_lo
### update P and S and modify c and go the next node always go left
P.append(-s - 1)
# print 's', s
branch_var = s
if v_fr <= 0.5:
# go left
S.append(-1)
V.append(v_lo)
c.variables.set_upper_bounds(s, v_lo)
branch_dir = -1
else:
#go right
S.append(1)
V.append(v_up)
c.variables.set_lower_bounds(s, v_up)
branch_dir = +1
# print c.variables.get_lower_bounds()
print 'branching variable:', branch_var, 'branching direction', branch_dir
print '----------------'
print 'z_node' , z_node
print 'z_global', z_global
if len(P) == 0:
break
#End of while loop
print
print 'Final solution:'
print 'z_node', z_node
print 'z_global', z_global
#branchbound()
| Python |
from numpy import *
import randgraph
#
n = 200
rho = 0.6
adj_mat = randgraph.randgraph(n, rho)
adj_mat_new = zeros([n,n])
for i in range(n-1):
adj_mat_new[i+1, 0:i+1] = adj_mat[0:i+1, i]
adj_mat_new[0:i+1, i+1] = adj_mat[0:i+1, i]
print adj_mat
print adj_mat_new
nodes = [[i] for i in range(n)]
S = []
S_bar = nodes[:]
S.extend([0])
S_bar.remove([0])
iter = 0
incumbent = 0.0
def find_weights(S_weights, target):
weights = 0
for elem in target:
weights += S_weights[elem]
return weights
def find_min_weights(S, S_bar, adj):
# The following block of codes generates the new nodes given S and S_bar
# The following codes needs to be refactored to deal with element of S_bar as a list of nodes
S_weights = zeros(n)
for node in S:
S_weights += adj[node]
conn_weights = zeros(len(S_bar))
for i in range(len(S_bar)):
conn_weights[i] = find_weights(S_weights, S_bar[i])
max_weights = max( conn_weights )
max_weights_ind = argmax( conn_weights )
new_node = S_bar[max_weights_ind]
"""
# Old codes
max_weights = max( sum_weights_vec[S_bar] )
# find the node to add to S
for node in S_bar:
if sum_weights_vec[node] == max_weights:
new_node = node
break
"""
return new_node, max_weights
#Outter while loop
while len(nodes) > 2:
S = []
S_bar = list(nodes)
S.extend([0])
S_bar.remove([0])
iter = 0
#Inner while loop
while len(S_bar) > 1:
iter += 1
new_node, maxweights = find_min_weights(S, S_bar, adj_mat_new)
S.extend( new_node )
S_bar.remove( new_node )
"""
print "Step ", iter
print S
print S_bar
"""
p = new_node
q = S_bar[0]
new_node, max_weights = find_min_weights(S, S_bar, adj_mat_new)
incumbent = max(max_weights, incumbent)
# Then merge the last two nodes
nodes.remove(p)
nodes.remove(q)
nodes.append( p+q )
# Only two nodes left
new_node, max_weights = find_min_weights(S, S_bar, adj_mat_new)
incumbent = max(max_weights, incumbent)
print incumbent
#update S and S_bar
"""
S = []
S_bar = list(nodes)
S.append(0)
S_bar.remove(0)
"""
| Python |
from numpy import *
from random import choice
import itertools
import sys
n = 50
rho = 0.4
def randgraph(n, rho):
int_lb = 1
int_ub = 10
adj_mat = zeros( (n-1, n-1) )
# Start from i to j+1
up_tri_ind = [(i,j) for j in range(n-1) for i in range(j+1)]
# Init the list of degrees at each node
node_deg = [0] * n
nodes = range(n)
# Generate the node-node adjacent (n-1) * (n-1) matrix
for ind in up_tri_ind:
if random.uniform() < rho:
adj_mat[ind] = random.randint( int_lb, int_ub )
node_deg[ ind[0] ] += 1
node_deg[ ind[1] + 1 ] += 1
#print adj_mat
#print node_deg
# Check for node degrees and modify the adj_mtx
for i in range( len(node_deg) ):
if node_deg[i] == 0: #the node is isolated
# Generate two new edges
print "The graph is isolated try another one"
sys.exit()
elif node_deg[i] == 1: #the node is a leaf
print "Dectect leaf node"
nodes_rest = range(n)
nodes_rest.remove(i)
j = choice(nodes_rest)
# Generate one new edges
if i > j:
adj_mat[ (j, i-1) ] = random.randint( int_lb, int_ub )
else:
adj_mat[ (i, j-1) ] = random.randint( int_lb, int_ub )
# Update degrees at the nodes
node_deg[ i ] += 1
node_deg[ j ] += 1
#print adj_mat
#print node_deg
m = sum(node_deg) / 2.0
#print "rho: ", rho
#print "m/(n(n-1)/2): ", m / (n*(n-1)/2)
return adj_mat
| Python |
#This module is for applying subgradient algorithm
#input: tolerance
#output: the list of primal solution, dual solution
#it internally calls the solvelr function with different lambda values
#to get primal and dual solutions
import sys
from lagrange import *
#print getidx(1,2,5)
iter = 0
N = 10
b = 40
t = 1
#report = False
report = True
seed = int(sys.argv[1])
dual_rows = ["u" + str(i+1) for i in range(N)] + ["v" + str(i+1) for i in range(N)]
#dual_rows = ["v" + str(i+1) for i in range(N)]
#dual_rows = ["u" + str(i+1) for i in range(N)] + ["k"]
#l = np.ones( len(dual_rows) )
l = np.zeros( len(dual_rows) )
rho = 0.9
eps = 1
print "solve the problem by cplex"
prob_org = initip(seed, N, b)
prob_org.parameters.mip.display.set(0)
prob_org.solve()
z_opt_true = prob_org.solution.get_objective_value()
if report == True:
print prob_org.solution.get_values()
print prob_org.solution.get_objective_value()
prob_org = initip(seed, N, b)
prob_org.set_problem_type(type=0)
prob_org.solve()
z_opt_lp = prob_org.solution.get_objective_value()
#prob_org.write("org.lp")
print "solve the problem by LR"
prob = initip( seed, N, b)
A, b, sen, c = initlr(prob, dual_rows)
#print "c is ", c
prob.parameters.mip.display.set(0)
z = 0
z_opt = 1000000
iter_opt_cnt = 0
iter_opt = 0
#a while loop for solving the lr(lambda)
l_pos_ind = []
l_eql_ind = []
l_neg_ind = []
print sen
for i in range( len(sen) ):
if sen[i] == "E":
l_eql_ind.append(i)
elif sen[i] == "L":
l_pos_ind.append(i)
else:
l_neg_ind.append(i)
print l_pos_ind
print l_eql_ind
print l_neg_ind
while True:
#print "c is ", c
if iter_opt_cnt > 10:
print "Reach iteration limit"
break
solvelr(prob, l, A, b, c)
# Get the current optimal solutions
x = np.array( prob.solution.get_values() )
z = prob.solution.get_objective_value()
g = gap(x, A, b)
# Report values at current iteration
if report == True:
print "iteration ", iter,"----------------"
print "t is", t
print "l is", l
print "z is", z
# print "x is", x
print "g is", g
print
#prob.write("lr"+str(iter)+".lp")
if opt_test(x, l, A, b, sen):
print "Optimal solution found"
z_opt = z
iter_opt = iter
break
# Can be wrapped up as a function
# Update lambda parameters
# l = np.maximum( np.zeros(len(l)), l - t * g)
temp_l = l - t*g
if len(l_pos_ind) != 0:
l[l_pos_ind] = np.maximum( np.zeros(len(l_pos_ind) ), temp_l[l_pos_ind])
if len(l_eql_ind) != 0:
l[l_eql_ind] = temp_l[l_eql_ind]
if len(l_neg_ind) != 0:
l[l_neg_ind] = np.minimum( np.zeros(len(l_neg_ind) ), temp_l[l_neg_ind])
# Update step length by geometric series
t = t * rho
# Update step length by another rule by variable fixing
# t = eps * z -
# Update z*
if z < z_opt:
z_opt = z
iter_opt = iter
iter_opt_cnt = 1
elif z == z_opt:
iter_opt = iter
iter_opt_cnt = iter_opt_cnt + 1
else:
iter_opt_cnt = iter_opt_cnt + 1
iter = iter+1
r_opt_gap = abs(z_opt_true - z_opt)/ z_opt_true
print "-------------------------"
print "---- Summary: ------"
print "-------------------------"
print "true ip optimal solution", z_opt_true, "\n"
print "true lp optimal solution", z_opt_lp, "\n"
print " lr optimal solution", z_opt, "at iteration", iter_opt, "\n"
print "total iterations", iter, "\n"
print "relative optimality gap", r_opt_gap
#format the output
| Python |
from lagrange import *
bat_dual_rows = []
#for i in bat_dual_row_names:
#do subgradient for each case
iter = 0
N = 20
b = 100
#t = 1
#report = True
#rho = 0.8
eps = 1
def subgrad(prob, dual_rows):
A, b, sen, c = initlr(prob, dual_rows)
# set initial value of l
l = 0 * np.ones( len(dual_rows) )
z = 0
z_opt = 1000000
iter = 0
iter_opt_cnt = 0
iter_opt = 0
rho = 0.9
t = 1
status = ""
l_pos_ind = []
l_eql_ind = []
l_neg_ind = []
for i in range( len(sen) ):
if sen[i] == "E":
l_eql_ind.append(i)
elif sen[i] == "L":
l_pos_ind.append(i)
else:
l_neg_ind.append(i)
while True:
if iter > 1000:
status = "U"
# print "Reach iteration limit"
break
if iter_opt_cnt > 40:
status = "L"
# print "Reach optimal iteration limit"
break
solvelr(prob, l, A, b, c)
x = np.array( prob.solution.get_values() )
z = prob.solution.get_objective_value()
g = gap(x, A, b)
if opt_test(x, l, A, b, sen):
z_opt = np.dot(x, c)
# print "Reach optimal solution"
# z_opt = z
iter_opt = iter
status = "O"
break
temp_l = l - t*g
if len(l_pos_ind) != 0:
l[l_pos_ind] = np.maximum( np.zeros(len(l_pos_ind) ), temp_l[l_pos_ind])
if len(l_eql_ind) != 0:
# l[l_eql_ind] = np.maximum( np.zeros(len(l_eql_ind) ), temp_l[l_eql_ind])
l[l_eql_ind] = temp_l[l_eql_ind]
if len(l_neg_ind) != 0:
l[l_neg_ind] = np.minimum( np.zeros(len(l_neg_ind) ), temp_l[l_neg_ind])
t = t * rho
#t = 1 / (iter + 1.0)
if z < z_opt:
z_opt = z
iter_opt = iter
iter_opt_cnt = 1
elif z == z_opt:
iter_opt = iter
iter_opt_cnt = iter_opt_cnt + 1
else:
iter_opt_cnt = iter_opt_cnt + 1
iter = iter+1
return z_opt, iter_opt, iter, status
# the outer loop should iterate through all dual rows
# for dual_rows in dual_rows_list
def ipsolve(prob):
prob.solve()
ip_opt_val = prob.solution.get_objective_value()
prob.set_problem_type(type=0)
prob.solve()
#prob.parameters.output.writelevel.set(0)
lp_opt_val = prob.solution.get_objective_value()
return ip_opt_val, lp_opt_val
#dual_rows = ["u" + str(i+1) for i in range(N)]
dual_rows = ["u" + str(i+1) for i in range(N)] + ["v" + str(i+1) for i in range(N)]
#dual_rows = ["v" + str(i+1) for i in range(N)]
#dual_rows = ["u" + str(i+1) for i in range(N)] + ["k"]
prob = cplex.Cplex()
print "%10s" % "case_num",
print "%10s" % "iter_total",
print "%10s" % "iter_opt",
print "%6s" % "status",
print "%12s" % "ld_opt",
print "%12s" % "ip_opt",
print "%12s" % "lp_opt",
print "%12s" % "opt_gap"
for case in range(10):
seed = (case+1) * 1000
prob = initip(seed, N, b)
prob_org = initip(seed, N, b)
ld_opt_val, ld_opt_iter, tt_iter, status = subgrad(prob, dual_rows)
ip_opt_val, lp_opt_val = ipsolve(prob_org)
opt_gap = abs(ld_opt_val - ip_opt_val)/ ip_opt_val
print "%10d" % (case+1),
print "%10d" % tt_iter,
print "%10d" % ld_opt_iter,
print "%6s" % status,
print "%12.6f" % ld_opt_val,
print "%12.6f" % ip_opt_val,
print "%12.6f" % lp_opt_val,
print "%12.6f" % opt_gap
# Then print out
| Python |
import cplex
import random
import numpy as np
from cplex.exceptions import CplexError
#The ideal case is that
# createld(prob, rownames)
# solveld (prob, lambda, A, b)
def getidx(i,j,N):
return j*N + i + 1
def initip(seed=10, N=20, b=100):
random.seed(seed)
prob = cplex.Cplex()
prob.objective.set_sense(prob.objective.sense.maximize)
# Add variables
varnames = ["x" + str(getidx(i,j,N)) for j in range(N) for i in range(N)]
#orgobj = [random.uniform(1,10) for i in range(N) for j in range(N)]
orgobj = [random.randint(1,10) for i in range(N) for j in range(N)]
vartypes = ["B" for i in range(N) for j in range(N)]
prob.variables.add(obj = orgobj,
types = vartypes,
names = varnames)
# Add constant in the objective
prob.variables.add(obj = [0],
types = ["C"],
lb = [1],
ub = [1],
names = ["x0"])
# Populate U constraints
unames = ["u" +str(i+1) for i in range(N) ]
urowcoefs = [1] * N
usenses = ["E"] * N
urhs = [1] * N
uexpr = []
for i in range(N):
urowvars = ["x" + str(getidx(i,j,N)) for j in range(N)]
uexpr.append([urowvars, urowcoefs])
prob.linear_constraints.add(lin_expr = uexpr,
senses = usenses,
rhs = urhs,
names = unames)
# Populate V constraints
vnames = ["v" + str(j+1) for j in range(N) ]
vrowcoefs = [1] * N
vsenses = ["E"] * N
vrhs = [1] * N
vexpr = []
for j in range(N):
vrowvals = ["x" + str(getidx(i,j,N)) for i in range(N)]
vexpr.append([vrowvals, vrowcoefs])
prob.linear_constraints.add(lin_expr = vexpr,
senses = vsenses,
rhs = vrhs,
names = vnames)
# Populate knapsack constraints
knames = ["k"]
krownames = varnames
#This is t_ij
t_lo = int(0.5 * b/ (1*N) )
t_up = int(3.0 * b/ (1*N) )
#krowcoefs = [random.uniform(t_lo, t_up) for i in range(N*N) ]
krowcoefs = [random.randint(t_lo, t_up) for i in range(N*N)]
kcoefs = [krownames, krowcoefs]
prob.linear_constraints.add(lin_expr = [kcoefs],
senses = ["L"],
rhs = [b],
names = ["k"])
#prob.parameters.mip.display.set(0)
prob.set_results_stream(None)
return prob
#prob.write("lagrange.lp")
#def solvelr(prob, lamba, A, b):
# prob.objective.set_linear(varnames, value)
def initlr(prob, dual_rows):
#print dual_rows
A = prob.linear_constraints.get_rows(dual_rows)
b = prob.linear_constraints.get_rhs(dual_rows)
sen = prob.linear_constraints.get_senses(dual_rows)
prob.linear_constraints.delete(dual_rows)
c = prob.objective.get_linear()
return A, b, sen, c
def solvelr(prob, l, A, b, c):
prob.parameters.mip.tolerances.mipgap.set(0)
#update constants in
#set old coefficients
varnames = prob.variables.get_names()
prob.objective.set_linear( zip(varnames, c) )
const = np.dot(l, b)
prob.objective.set_linear("x0", const)
#This is a confusing part, we modify the coefficients with l
for i in range( len(l) ):
temp_ind = A[i].ind
temp_val = A[i].val
old_coef = prob.objective.get_linear(temp_ind)
new_coef = np.add(old_coef, -np.multiply(l[i], temp_val) )
prob.objective.set_linear( zip(A[i].ind, new_coef) )
prob.solve()
# for j in range( A[i].ind ):
# old_coef = prob.objective.get_linear(j)
# new_coef = old_coef * lambda[i] *
# prob.objective.set_linear( j, new_coef )
return 0
def gap(x, A, b):
#compute b - Ax
gap = np.zeros( len(b) )
for i in range( len(b) ):
temp_ind = A[i].ind
temp_val = A[i].val
gap[i] = b[i] - np.dot( x[temp_ind], temp_val )
# print x[temp_ind], temp_val
# print b[i]
return gap
def opt_test(x, l, A, b, sen):
g = gap(x, A, b)
#print "g", g, "l", l
#print abs(np.dot(l, g))
if abs(np.dot(l, g)) != 0.0:
#print "False at complementary"
return False
for i in range(len(l)):
if sen[i] == 'E' and g[i] != 0: #d - Dx != 0
# print "False at equality"
return False
elif sen[i] == 'L' and g[i] < 0: #d - Dx < 0
# print "False at inequality L"
return False
elif sen[i] == 'G' and g[i] > 0:
# print "False at inequality G"
return False
else:
continue
return True
| Python |
#read uflp problem as MIP
import sys
def get_words(line):
"""Return a list of the tokens in line."""
line = line.replace("\t", " ")
line = line.replace("\v", " ")
line = line.replace("\r", " ")
line = line.replace("\n", " ")
while line.count(" "):
line = line.replace(" ", " ")
line = line.strip()
return [word + " " for word in line.split(" ")]
def read_dat_file(filename):
f = open(filename)
allwords = []
for line in f:
allwords += get_words(line)
return allwords
#read_dat_file("a05100")
def read_uflp(filename):
f = open(filename)
filename = f.readline()
header = get_words( f.readline() )
num_fac = int(header[0]) # number of facilities
num_cty = int(header[1]) # number of cities(client)
fx_cost = [0.0] * num_fac
cn_cost = []
cty_cn_cost = [0.0] * num_fac
for i in range(num_cty):
words = get_words( f.readline() )
fx_cost[i] = float( words[1] )
for j in range(num_fac):
cty_cn_cost[j] = float( words[j+2] )
cn_cost.append( list(cty_cn_cost) )
return num_fac, num_cty, fx_cost, cn_cost
"""
num_fac, num_cty, fx_cost, cn_cost = read_uflp(sys.argv[1])
print num_fac
print num_cty
print fx_cost
"""
#print cn_cost
| Python |
import cplex
import readuflp
import sys
import os
def get_ind(i,j,N):
return j*N + i + 1
#stub
def gen_uflp(filename):
prob = cplex.Cplex()
num_fac, num_cty, fx_cost, cn_cost = readuflp.read_uflp(filename)
# add x_ij variables
for j in range(num_cty):
varnames = ["x" + str( get_ind(i,j, num_fac) ) for i in range(num_fac)]
varcosts = cn_cost[j]
vartypes = ["B"] * num_fac
prob.variables.add(obj = varcosts,
types = vartypes,
names = varnames)
# add facility variable y_i
var_names = ["y" + str(i) for i in range(num_fac)]
var_costs = fx_cost
var_types = ["B"] * num_fac
prob.variables.add(obj = var_costs,
types = var_types,
names = var_names)
# add assignment constraints
for j in range(num_cty):
var_names = ["x" + str( get_ind(i,j, num_fac) ) for i in range(num_fac)]
cty_expr = [varnames, [1] * num_fac]
prob.linear_constraints.add(lin_expr = [cty_expr],
senses = ["E"],
rhs = [1])
# add associativity constraints
for i in range(num_fac):
var_names = ["y" + str(i)] + \
["x" + str( get_ind(i,j, num_fac) ) for j in range(num_cty)]
var_coefs = [ -1*num_cty ] + \
[1] * num_cty
asso_expr = [var_names, var_coefs]
prob.linear_constraints.add(lin_expr = [asso_expr],
senses = ["L"],
rhs = [0])
return prob
def batch_gen_uflp(dirname):
for filename in os.listdir(dirname):
prob = gen_uflp(dirname + filename)
prob.write("uflp" + filename + ".lp")
batch_gen_uflp("./uniform/")
#prob = gen_uflp( sys.argv[1] )
#prob.write( sys.argv[1] + ".lp")
| Python |
#This is a file that generate a gap instances solved by cplex
import cplex
import random
import readgap
import os
def getidx(i,j,N):
return j*N + i + 1
def gengap(filename):
prob = cplex.Cplex()
nr, nj, c, a, b = readgap.readgap(filename)
print nr, nj, b
prob.objective.set_sense(prob.objective.sense.maximize)
for j in range(nr):
#Add Variables
varnames = ["x" + str(getidx(i,j, nj)) for i in range(nj)]
varcosts = c[j]
vartypes = ["B"] * nj
prob.variables.add(obj = varcosts,
types = vartypes,
names = varnames)
print j
kexpr = [varnames, a[j]]
prob.linear_constraints.add(lin_expr = [kexpr],
senses = ["L"],
rhs = [ b[j] ] )
#Populate capacity constraints
for i in range(nj):
varnames = ["x" + str(getidx(i,j, nj)) for j in range(nr)]
kexpr = [varnames, [1]*nr ]
prob.linear_constraints.add(lin_expr = [kexpr],
senses = ["L"],
rhs = [1])
return prob
def gengap_batch(dirname):
for filename in os.listdir(dirname):
prob = gengap(dirname + filename)
prob.write("gap" + filename + ".lp")
gengap_batch("./c/")
| Python |
def get_words(line):
"""Return a list of the tokens in line."""
line = line.replace("\t", " ")
line = line.replace("\v", " ")
line = line.replace("\r", " ")
line = line.replace("\n", " ")
while line.count(" "):
line = line.replace(" ", " ")
line = line.strip()
return [word + " " for word in line.split(" ")]
def read_dat_file(filename):
f = open(filename)
allwords = []
for line in f:
allwords += get_words(line)
return allwords
#read_dat_file("a05100")
def gap_allwords(allwords):
nr = eval(allwords[0]) # number of resources
nj = eval(allwords[1]) # number of jobs
n = len(allwords)
c_begin_ind = 2
a_begin_ind = 2 + nj*nr
b_begin_ind = 2 + 2*nj*nr
for i in range(2,n):
allwords[i] = float(allwords[i])
c = []
a = []
b = []
for i in range(nr):
row_c = allwords[c_begin_ind + i*nj :
c_begin_ind +(i+1)*nj]
row_a = allwords[a_begin_ind + i*nj :
a_begin_ind + (i+1)*nj]
c.append(row_c)
a.append(row_a)
b = allwords[b_begin_ind:]
# print c
# print a
return nr, nj, c, a, b
def readgap(filename):
allwords = read_dat_file(filename)
nr, nj, c, a, b = gap_allwords(allwords)
return nr, nj, c, a, b
| Python |
#This is a file that generate a random instance of knapsack problem
import cplex
import random
# Thinking of design the covers and cover classes
# covers(A, b)
# covers.set_inequalities(prob)
# covers.update_inequalities(prob)
# construct the min_covers from A and b
# cover.ind
# cover.val
# cover.max_val
# cover.isminimal()
# cover.islifted()
#from itertools import *
#def genkpineql(n, a, b):
def powerset(lst):
ind = range(len(lst))
P = reduce(lambda result, x: result + [subset + [x] for subset in result], lst, [[]])
I = reduce(lambda result, x: result + [subset + [x] for subset in result], ind, [[]])
return zip(I, P)
def cumsum(seq):
cum_sum = []
y = 0
for i in seq: # <--- i will contain elements (not indices) from n
y += i # <--- so you need to add i, not n[i]
cum_sum.append(y)
return cum_sum
def test_cover(coefs, b):
return sum(coefs) > b
# this function extend the cover
def extend_cover(cover, A):
n = len(A)
# how to keep track of the max_cover_val?
coefs = [A[i] for i in cover]
max_cover_val = max(coefs)
extra_items = []
for i in range(n):
if i not in cover and A[i] >= max_cover_val:
extra_items.append(i)
ext_cover = cover + extra_items
return ext_cover
def test_cover_minimal(coefs, b):
# test cover condition
if sum(coefs) <= b:
return False
# test minimality
for a in coefs:
if sum(coefs) - a > b:
return False
break
return True
def genkp(n, a, b):
#seed = 100
#random.seed(seed)
prob = cplex.Cplex()
prob.objective.set_sense(prob.objective.sense.maximize)
#Add Variables
varnames = ["x" + str(i) for i in range(n)]
varcosts = [random.randint(3, 5) for i in range(n)]
vartypes = ["B"]*n
prob.variables.add(obj = varcosts,
types = vartypes,
names = varnames)
#Populate knapsack constraints
kpnames = ["k"]
kcoefs = [random.randint(1, 35) for i in range(n)]
kcoefs.reverse()
#kcoefs.sort()
kexpr = [varnames, kcoefs]
#print kexpr
prob.linear_constraints.add(lin_expr = [kexpr],
senses = ["L"],
rhs = [b],
names = kpnames)
return prob
def gen_min_covers(prob):
row = prob.linear_constraints.get_rows(0)
rhs = prob.linear_constraints.get_rhs()
A = row.val
b = rhs[0]
min_covers = []
IP = powerset(A)
for c in IP:
if test_cover_minimal(c[1], b):
min_covers.append(c[0])
for cover in min_covers:
ext_cover = extend_cover(cover, A)
#print cover
#print ext_cover
ext_coefs = [1] * len( ext_cover ) #extend the cover here
prob.linear_constraints.add( lin_expr = [[ext_cover, ext_coefs]] ,
senses = ["L"],
rhs = [ len(ext_cover) - 1 ] )
"""
# generate regular minimal cover here
coefs = [1] * len( cover )
prob.linear_constraints.add( lin_expr = [[cover, coefs]] ,
senses = ["L"],
rhs = [ len(cover) - 1 ] )
"""
return min_covers
#def gen_ext_covers(prob):
def gen_lift_covers(prob):
row = prob.linear_constraints.get_rows(0)
rhs = prob.linear_constraints.get_rhs()
A = row.val
b = rhs[0]
min_covers = []
IP = powerset(A)
for c in IP:
if test_cover_minimal(c[1], b):
min_covers.append(c[0])
#print min_covers
for cover in min_covers:
A_coefs_cov = [A[i] for i in cover]
remainder = list(set(range(len(A))) - set(cover))
remainder.sort()
A_coefs_rem = [A[i] for i in remainder]
rem_coefs = [0] * len( remainder )
cov_coefs = [1] * len( cover )
mu = cumsum(A_coefs_cov)
mu = [0] + mu
lamda = mu[-1] - b
#print mu
for i in range( len(remainder) ):
a = A[ rem_coefs[i] ]
for h in range(len(cover)):
if mu[h] <= a and a <= mu[h+1] - lamda:
rem_coefs[i] = h
elif mu[h+1] - lamda + 1 <= a and a <= mu[h+1] - 1:
rem_coefs[i] = h+1
temp_ind = cover + remainder
temp_val = cov_coefs + rem_coefs
# print temp_ind
print temp_val
prob.linear_constraints.add( lin_expr = [[temp_ind, temp_val]] ,
senses = ["L"],
rhs = [ len(cover) - 1 ])
return 0
"""
min_covers = []
A = [random.randint(1, 20) for i in range(10)]
A.sort()
IP = powerset(A) #the powerset and its indices
b = 20
for c in IP:
if test_cover_minimal(c[1], b):
min_covers.append(c)
"""
prob = genkp(6, 5, 30)
prob.write("kp_org.lp")
gen_lift_covers(prob)
#prob.write("kp_with_extended_covers.lp")
prob.write("kp_with_lifted_covers.lp")
#prob = genkp(30, 5, 6)
#prob.write("kp.lp")
| Python |
'''
Created on 11/07/2014
@author: Juanpa y Yami
'''
from cx_Freeze import setup, Executable
#includes = ["atexit", "PyQt4.QtGui", "numpy", "PIL", "pyfftw.builders"]
packages = ["GUI", "core"]
setup(
options={"build_exe":{"packages":packages, "excludes":["Tkinter"]}},
name="Transformada de Fourier",
version="0.5",
description="Programa que calcula la FTT de imagenes",
executables = [Executable(script="mainffT.py", base="Win32GUI")]
) | Python |
'''
Created on 1/05/2014
@author: Juan Pablo Moreno - 20111020059
'''
import sys
from PyQt4.QtGui import QApplication
from GUI import VentanaMenu
def main():
app = QApplication(sys.argv)
ventana = VentanaMenu()
sys.exit(app.exec_())
if __name__ == '__main__':
main() | Python |
'''
Created on 3/06/2014
@author: Juan Pablo Moreno - 20111020059
@author:
@author:
@author:
'''
from __future__ import print_function
import os
from PIL import Image
import numpy as np
import pyfftw as pFT
_FORMATOS = ['PNG', 'JPEG', 'GIF', 'BMP']
def _abrirImagen(_ruta):
imagenes = []
if isinstance(_ruta, list) or isinstance(_ruta, tuple):
if len(_ruta) == 1:
imagenes = Image.open(_ruta.pop())
elif len(_ruta)>1:
for img in _ruta:
imagenes.append(Image.open(img))
else:
imagenes = None
elif isinstance(_ruta, str):
imagenes = Image.open(_ruta)
return imagenes
def transformar(ruta):
"""
Calcula la Transformada Discreta de Fourier de una imagen en escala de grises
y retorna en forma de imagenes la magnitud y angulo fase
"""
imagen = _abrirImagen(ruta)
if imagen.format in _FORMATOS:
if imagen.mode != 'L':
imagen = imagen.convert('L')
datos = np.array(list(imagen.getdata()))/255.0# - 1.0
datos.shape = imagen.size
transf = pFT.builders.fft2(datos, datos.shape)
resultado = transf()
#magnitud
magnitud = Image.new('L', imagen.size)
datosMag = np.around((np.absolute(resultado)))
datosMag = _reordenar(datosMag)
datosMag.shape = (datosMag.size)
magnitud.putdata(list(datosMag))
#angulo fase
fase = Image.new('L', imagen.size)
datosFase = np.rad2deg(np.arctan2(resultado.imag, resultado.real))
datosFase-=np.min(datosFase)
datosFase*=(255.0/np.max(datosFase))
datosFase = _reordenar(np.around(datosFase))
datosFase.shape = (datosFase.size)
fase.putdata(list(datosFase))
return magnitud, fase
else:
return None, None
def filtrar(rutaimg, filtro):
"""
Obtiene la magnitud del espectro de frecuencia y lo opera con el :filtro: seleccionado
"""
imagen = _abrirImagen(rutaimg)
filtro = _abrirImagen(os.path.join(os.path.dirname(os.path.dirname(__file__)),"filtros\\" + filtro + ".png"))
filtro = filtro.resize(imagen.size)
if imagen.format in _FORMATOS:
if imagen.mode != 'L' or filtro.mode!='L':
imagen = imagen.convert('L')
filtro = filtro.convert('L')
datos = np.array(list(imagen.getdata()))
datos.shape = imagen.size
transf = pFT.builders.fft2(datos, datos.shape)
resultado = transf()
datosFiltro = np.array(list(filtro.getdata()))/255.0
datosFiltro.shape = filtro.size
magnitud = np.around(np.absolute(resultado))
magnitud -= np.min(magnitud)
magnitud = _reordenar(magnitud)
magnitud *= datosFiltro
fase = np.rad2deg(np.arctan2(resultado.imag, resultado.real))
fase-=np.min(fase)
fase*=(255.0/np.max(fase))
fase = _reordenar(np.around(fase))
resultado = magnitud*(np.cos(np.deg2rad(fase)) + np.sin(np.deg2rad(fase))*1j)
inv = pFT.builders.ifft2(resultado, resultado.shape)
inversa = inv()#/inv.N
inversa.shape = inversa.size
imagen2 = Image.new("L", imagen.size)
imagen2.putdata(list(np.absolute(inversa)))
return imagen2
else:
return None
def invertir(rutas):
"""
calcula la transformada inversa a partir de las imagenes de magnitud y angulo fase
y genera una imagen
"""
imagenes = _abrirImagen(rutas)
datos = []
for imagen in imagenes:
lista = np.array(list(imagen.getdata()))
lista.shape = imagen.size
datos.append(lista)
magnitud, fase = datos
if magnitud.size != fase.size:
raise NoCorrespondenError()
datos = magnitud*(np.cos(np.deg2rad(fase)) + np.sin(np.deg2rad(fase))*1j)
inv = pFT.builders.ifft2(datos, datos.shape)
inversa = inv()
inversa.shape = inversa.size
imagen2 = Image.new("L", imagen.size)
imagen2.putdata(list(np.absolute(inversa)*255))
return imagen2
class NoCorrespondenError(Exception):
pass
def _print(lista):
for fila in lista:
for columna in fila:
print(columna, end='\t')
print("")
def _reordenar(a):
b = np.concatenate((a[(len(a))/2:,:],a[:(len(a))/2,:]),0)
c = np.concatenate((b[:,(len(a))/2:], b[:,:(len(a))/2]),1)
return c | Python |
from implementacion import transformar, filtrar, invertir, NoCorrespondenError | Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.