when I run my program it gives me this error:
new = colony.Colony(self.__tasks,self.__times) UnboundLocalError: local variable 'colony' referenced before assignment
my class is as follows:
import tareas
import hormiga
import colonia
class inicio:
def __init__(self):
self.__nHormigas = 20 #mAnts
self.__veces = 4 #mIter
self.__generaciones = 500 #mHillsCount
self.__alfa = 1
self.__beta = 1
self.__p = 0.1 #mEvap
self.__nTareas = 100
self.__mColonia = [] #mHills
self.__tareas = []
self.__mMejorRuta = []
def getMejorCoste(self):
return self.__mejorCoste #mBestCost
def getRuta(self):
return self.__mMejorRuta #mBestPath
def Iniciar(self):
self.__mejorCoste = float('inf')
for e in range(self.__nTareas):
tarea = tareas.Tarea()
self.__tareas.append(tarea)
for i in range(self.__generaciones):
nueva = colonia.Colonia(self.__tareas,self.__veces) #aquí es el error
self.__mColonia.append(nueva)
#en paralelo??
for colonia in self.__mColonia:
colonia.empezar()
self.__mColonia.sort(key=lambda x: x.getMejorCoste())
if (self.__mColonia[0].getMejorCoste() < self.__mejorCoste):
self.__mejorCoste = self.__mColonia[0].getMejorCoste()
self.__mMejorRuta = []
for tarea in self.__mColonia[0].getMejorRuta():
self.__mMejorRuta.append(tarea)
print(self.__mejorCoste)
My file directory contains one called colony.py whose constructor is as follows:
class Colonia:
def __init__ (self, tareas, n_iteraciones, evaporacion=0.1, n_hormigas=20):
self.__constanteEvaporacion = evaporacion
self.__nHormigas = n_hormigas
self.__iteraciones = n_iteraciones
self.__evaporacion = 1.0 - evaporacion
self.__tareas = tareas
self.__mejorCoste = float('inf')
self.__mejorRuta = list()
self.__hormigas = []
#inicializamos matriz de feromonas
self.__mFeromonas = [[getValorInicialFeromona()]*len(self.__tareas) for x in range(len(self.__tareas))]
self.__feromonas = [[0.0]*len(self.__tareas) for x in range(len(self.__tareas))]
Any ideas?
Thanks.
I have to see the structure of your directories and files, if you do not solve it with what I am going to tell you, add it and I will edit my answer.
Make sure that the directory where the module is located
colonia.py
also contains the file .__init__.py
This is used to indicate that the package (directory where the__init__.py
) contains python files, otherwise you will not be able to import the modules.Another cause of the error can be an improper import:
if the module
colonia.py
is in another package the correct import would befrom paquetex.colonia import Colonia
and if it is in the same package ``from colony import colony`The initialization of the object would be like this:
`new = Colony(self.__tasks,self.__times)