jueves, 12 de julio de 2012

Análisis de complejidad asintótica de heurísticos

Complejidad es la medida del uso de algún recurso por parte de un algoritmo, estos recursos pueden ser requerimientos de almacenamiento, memoria o tiempo. 
Por lo general, la cantidad de tiempo que un algoritmo toma es el recurso más encontrado.
El análisis asintótico es la determinación de cantidad de recursos usados por un algoritmo.

En esta entrada graficamos
Búsqueda Tabú 
Búsqueda Local
Recocido Simulado
Algoritmo Genético
HiperHeuristicos
Serán dos graficas por cada Heurística con una densidad de 0.6
Significados de las abreviaciones
  • BL= Local
  • BT=Búsqueda Tabú
  • RS=Recocido Simulado
  • AG=Algoritmo Genético
  • HH=Hiperheuristico 
Tomamos en Cuenta los Criterios mencionados a continuación:
Tiempo será medido en segundos
Memoria será medida en bytes
Numero de Vértices

Búsqueda Local 



Búsqueda Tabú



Recocido Simulado





Algoritmo Genético



HiperHeurísticos


Bibliografia:



karenalduncin  wtf Dx

Visualización de evaluación de heurísticos

La evaluación heurística es un análisis de experto en el cual se hace una inspección minuciosa a interfaces o sistemas con el fin de determinar si cada uno de sus elementos se adhieren o no a los principios de usabilidad, diseño o arquitectura de informaición comúnmente aceptados en sus respectivas disciplinas. Esta entrada trata de evaluar el tiempo, la memoria y objetivo de nuestro programa 

gnuplot> set xrange [0:80]
gnuplot> set size 1.2, 1
gnuplot> set xrange [0:100]>
gnuplot> set ytics 10,2
gnuplot> set Title "Tiempo"


gnuplot> set title "Tiempo"
gnuplot> set origin 0,1
gnuplot> set yrange [0:5]
gnuplot> set ytics 3,10
gnuplot> set title "Memoria"
gnuplot> set origin 1.2, 1
gnuplot> set yrange [0:5]
gnuplot> set ytics 1,1
gnuplot> set title "Objetivo"
gnuplot> set origin 2.4,1
gnuplot> set yrange [0:5]



10 15 1 22 36
10 15 1 23 56
11 23 2 28 57
12 24 2 44 76










39 13 12 2 22
39 14 13 3 45
42 14 28 3 45
87 19 34 3 59




43 3 59 2 32
31 3 45 2 24
28 3 45 1 10
21 2 22 1 13










       





miércoles, 11 de julio de 2012

Análisis estadístico de desempeño

En éste análisis obtendremos el tiempo de ejecución, la cantidad total de memoria utilizada y calidad de la solución generada para cada una de las heurísticas ya conocidas y lo meteremos a un archivo para su posterior uso.


Código:
 ArrayList <Integer> usos = new ArrayList<Integer>();
 Hashtable <String, Double> heuristica = new Hashtable <String, Double>();
 Hashtable <String, Integer> contador = new Hashtable <String, Integer>();
 String opciones[] = {"local", "tabu", "recocido", "genetico"};
 Runtime rt = Runtime.getRuntime(); 
 BufferedWriter out = new BufferedWriter(new FileWriter("instancias.txt"));
 
 for(int i = 0; i < opciones.length ; i++){ 
  heuristica.put(opciones[i], 1.0);
 }


 ArrayList<Integer> actual = Arista.inicial(grafo);


 while(reinicio <= re){
 
    int indice = ruletaheur(heuristica, opciones);
  
  if(contador.containsKey(opciones[indice])){
   int valor = contador.get(opciones[indice]);
   valor += 1;
   contador.put(opciones[indice], valor);
  }else{
   contador.put(opciones[indice], 1);  
  }
  
 System.out.print("Usando "+opciones[indice] +" en reinicio " +re +"\n"); 
 long tiempoInicio = System.currentTimeMillis();
 long memoriaInicio = rt.freeMemory(); 
 
 switch(indice) {
  case 0:
      break;
  case 1: 
      sol = tabu(actual, tabu);
      if(sol <= actual){
       actual = sol;
       double puntos = heuristica.get(opciones[indice]);
       puntos *= premio;
       heuristica.put(opciones[indice], puntos);
      }
      break;
  case 3: 
      sol = recocido(actual);
      if(sol <= actual){
       actual = sol;
       double puntos = heuristica.get(opciones[indice]);
       puntos *= premio;
       heuristica.put(opciones[indice], puntos);
      }
      break;
  case 4: 
      sol = nacimiento(pob, n, grafo);
      if(sol <= actual){
       actual = sol;
       double puntos = heuristica.get(opciones[indice]);
       puntos *= premio;
       heuristica.put(opciones[indice], puntos);
      }
      break;
  }  

 long tiempoFinal = System.currentTimeMillis();
    long memoriaFinal = rt.freeMemory();

   out.write(reinicio);
   out.write("  ");
   out.write(String.valueOf(tiempoFinal-tiempoInicio));
   out.write("  ");
   out.write(String.valueOf(memoriaInicio-memoriaFinal));
   out.write("  ");
   out.write(String.valueOf(sol));
   out.newLine(); 
 reinicio++;   
 }   

martes, 10 de julio de 2012

Hiperheurísticos

La hiperheurística consiste básicamente en hacer uso de un conjunto de varias heurísticas que ya conocemos para ir generando diversas soluciones que se irán evaluando y así poder determinar cuál heurística es la que nos conviene para resolver el problema propuesto. La idea es que al principio las heurísticas a usar se elijan aleatoriamente y después con un sistema de premios y castigos, ir dando prioridad a las heurísticas que mejores resultados obtengan en el menor tiempo.




Código:

    public static int ruletaheur (Hashtable <String, Double> heuristica, String opciones[]){
     
     double total = 0.0;
     
     for(int i = 0; i < heuristica.size(); i++){
      double opcion = heuristica.get(opciones[i]);
      total += opcion;
     }
     
     double corte = Arista.r.nextInt((int)total);
     total = 0.0;
     for(int i = 0; i < heuristica.size(); i++){
      double opcion = heuristica.get(opciones[i]);
      total += opcion;
      if(total >= corte){
       return i;
      }
     }
    return 0; 
    } 






 ArrayList <Integer> usos = new ArrayList<Integer>();
 Hashtable <String, Double> heuristica = new Hashtable <String, Double>();
 Hashtable <String, Integer> contador = new Hashtable <String, Integer>();
 String opciones[] = {"local", "tabu", "recocido", "genetico"};

 
 for(int i = 0; i < opciones.length ; i++){ 
  heuristica.put(opciones[i], 1.0);
 }


 ArrayList<Integer> actual = Arista.inicial(grafo);


 while(reinicio <= re){
 
    int indice = ruletaheur(heuristica, opciones);
  
  if(contador.containsKey(opciones[indice])){
   int valor = contador.get(opciones[indice]);
   valor += 1;
   contador.put(opciones[indice], valor);
  }else{
   contador.put(opciones[indice], 1);  
  }
  
 System.out.print("Usando "+opciones[indice] +" en reinicio " +re +"\n"); 
  
 
 switch(indice) {
  case 0:
      break;
  case 1: 
      sol = tabu(actual, tabu);
      if(sol <= actual){
       actual = sol;
       double puntos = heuristica.get(opciones[indice]);
       puntos *= premio;
       heuristica.put(opciones[indice], puntos);
      }
      break;
  case 3: 
      sol = recocido(actual);
      if(sol <= actual){
       actual = sol;
       double puntos = heuristica.get(opciones[indice]);
       puntos *= premio;
       heuristica.put(opciones[indice], puntos);
      }
      break;
  case 4: 
      sol = nacimiento(pob, n, grafo);
      if(sol <= actual){
       actual = sol;
       double puntos = heuristica.get(opciones[indice]);
       puntos *= premio;
       heuristica.put(opciones[indice], puntos);
      }
      break;
  }  
  
  
 reinicio++;   
 }   
  
 for(int i = 0; i < opciones.length ; i++){ 
  System.out.print("Heuristica "+opciones[i] +" fue usada " +contador.get(opciones[i]) +" veces; puntuacion final: " +heuristica.get(opciones[i]) +"\n");
 }  





viernes, 6 de julio de 2012

Metaheurística Genética Básica

La Metaheurística Genética Básica Genera una Población de soluciones iniciales después así 
poder elegir al azar una de estas soluciones y mutarlas o cruzarlas y generar mas nuevas  soluciones para despues eliminar y solo conservar las generaciones que contengan las mejores soluciones este es el avance de la clase.

//
genera una poblacion inicial

    public static ArrayList<ArrayList<Integer>> poblacion(ArrayList <Arista> grafo,int tam)//verif
    {
 ArrayList<ArrayList<Integer>> lista= new ArrayList<ArrayList<Integer>>();
 while(lista.size()<=tam)
     {
  lista.add(Arista.inicial(grafo));
     }
 //System.out.println("Poblacion @_@");
 // Arista.imprime(lista);
 return lista;
    }
    //cromosoma
    public static ArrayList<String> cromosoma(ArrayList<Integer> seleccion, int cantidad)
    //cantidad total de vertices 
    {
 ArrayList<String> ref = new ArrayList<String>();
 for(int i=0;i<cantidad;i++)
     {
  if(seleccion.contains(i))
     {
         ref.add("1");
     }
     else
         ref.add("0");
     }
 //Arista.imprime(ref);
        return ref;
    }

    public static ArrayList<Integer> cubierta (ArrayList<String> cromosoma)
    {
 ArrayList<Integer> selection= new ArrayList<Integer>();
 int pos =0;
  for (int i=0;i<cromosoma.size();i++)
     {
  if((cromosoma.get(i)).equals("1"))
      selection.add(pos);
  pos+=1;
     }
 //System.out.println("cubierta");
 //Arista.imprime(selection);
 return selection;
    }

    public static void mutacion(ArrayList<ArrayList<Integer>>poblacion,int verticestotales,ArrayList<Arista> g)
    {
 int individuo = Arista.r.nextInt(poblacion.size());
 ArrayList<Integer> id = poblacion.get(individuo);
 //System.out.println("id");
 //Arista.imprime(id);
 ArrayList<String> cr =cromosoma(id,verticestotales);
 int ubic= Arista.r.nextInt(verticestotales);
 if (cr.get(ubic)== "0")//si el individuo seleccionado es igual a 0
     {
  cr.set(ubic,"1"); 
     }
 else
     {
  cr.set(ubic,"0");
     }
 //System.out.println("cadenita");
 //Arista.imprime(cr);
 ArrayList <Integer> mutante = Arista.cubierta(cr);
 // System.out.println("mutante");
 //Arista.imprime(mutante);
 int objetivo = Arista.objetivo(mutante);
 boolean fact = Arista.factible(mutante,g);
 if(fact==true )
     poblacion.add(mutante);
 return;
    }
    
    public static void nacimiento(ArrayList<ArrayList<Integer>>poblacion,int n,ArrayList<Arista> g)
    {
 int i=0;
 ArrayList<String> papa = cromosoma(poblacion.get(Arista.r.nextInt(poblacion.size())),n);
 ArrayList<String> mama = cromosoma(poblacion.get(Arista.r.nextInt(poblacion.size())),n);
 int pos = Arista.r.nextInt(n);
 //mama
 ArrayList<String> hija=null;
 ArrayList<String> hijo=null;
 Iterator<String> pa = papa.iterator();//recorre 
 Iterator<String> ma = mama.iterator();
 while (pa.hasNext() && ma.hasNext()) {
     if(i<pos)
  {
      hija.add(pa.next());
      hijo.add(ma.next());
     i++;
  }
     else
  {
      hija.add(ma.next());
      hijo.add(pa.next());
      i++;
  }
 }
 System.out.println("mama");
 Arista.imprime(mama);
 System.out.println("papa");
 Arista.imprime(papa);
 System.out.println("hija");
 Arista.imprime(hija);
 System.out.println("hijo");
 Arista.imprime(hijo);
 poblacion.add(hija);
 poblacion.add(hijo);   
 return ;
 }

jueves, 5 de julio de 2012

Busqueda Recocido Simulado

El Enfriamiento o Recocido Simulado es un algoritmo de búsqueda por entornos con un criterio probabilístico de aceptación de soluciones basado en enfriamiento (Termodinámica).

„ Un modo de evitar que la búsqueda local finalice en óptimos locales, hecho que suele ocurrir con los algoritmos tradicionales de búsqueda local, es permitir que algunos movimientos sean hacia soluciones peores„ Pero si la búsqueda está avanzando realmente hacia una buena solución,
estos movimientos “de escape de óptimos locales” deben realizarse de un modo controlado,esto se realiza controlando la frecuencia de los movimientos de escape mediante una función de
probabilidad que hará disminuir la probabilidad de estos movimientos hacia soluciones peores conforme avanza la búsqueda (y por tanto estamos más cerca, previsiblemente, del óptimo local)
„ Así, se aplica la filosofía habitual de búsqueda de diversificar al principio e intensificar al final.
Hace uso de una variable llamada Temperatura, T, cuyo valor determina en qué medida pueden ser aceptadas soluciones vecinas peores que la actual?? La variable Temperatura se inicializa a un valor alto, denominado Temperatura inicial, T0, y se va reduciendo cada iteración mediante un mecanismo de enfriamiento de la temperatura, α(·), hasta alcanzar una Temperatura final, Tf

#Vertices = 12 Densidad = .4
Se generaron 29 aristas.
#instancia
(0, 1)
(0, 3)
(0, 9)
(0, 11)
(1, 8)
(1, 9)
(1, 10)
(1, 11)
(2, 3)
(2, 5)
(2, 6)
(2, 10)
(3, 4)
(3, 5)
(3, 6)
(3, 7)
(4, 5)
(4, 6)
(4, 7)
(4, 8)
(4, 11)
(5, 10)
(5, 11)
(6, 7)
(6, 8)
(6, 9)
(6, 10)
(6, 11)
(8, 9)
Cota inferior: 5.
Cota superior: 10.


0 0 8 factible
0 1 8 factible
0 2 8 factible
0 3 8 factible
0 4 8 factible
1 0 10 factible
RS 9 factible
1 1 9 factible
1 2 9 factible
1 3 9 factible
1 4 9 factible
2 0 9 factible
2 1 9 factible
RS 8 factible
2 2 8 factible
2 3 8 factible
2 4 8 factible
3 0 9 factible
3 1 9 factible
3 2 9 factible
3 3 9 factible
3 4 9 factible
4 0 11 factible
4 1 10 factible
4 2 10 factible
4 3 10 factible
RS 9 factible
4 4 9 factible
5 0 8 factible
5 1 8 factible
5 2 8 factible
5 3 8 factible
5 4 8 factible
6 0 10 factible
6 1 10 factible
RS 9 factible
6 2 9 factible
6 3 9 factible
6 4 9 factible


Se realizaron cambios a la función búsqueda...
public static ArrayList<Integer> busqueda(ArrayList<Arista> grafo, int n,int it,int re,int temperact, double enfriamiento) {
        //ArrayList<ArrayList<Integer>> lista = new ArrayList<ArrayList<Integer>>();
 ArrayList<Integer> mejorSol = null;
 // int intentos =0;
 //boolean TAB;
 //define la mejor solucion como nula para que cualquiera pueda mejorarla
 int mejorObj = n;//tamaño de la cubierta inicial seria el total de nodos en el grafo idem
 ArrayList<Integer> lista = new ArrayList<Integer>();
 
 for (int reinicio = 0; reinicio < re; reinicio++) {//pasos de reinicio
     ArrayList<Integer> solucion = Arista.inicial(grafo);//solucion inicial
     //Arista.imprime(solucion);
     int obj = Arista.objetivo(solucion);//objetivo de solucion
     //temperact=1000;
     for (int iter = 0; iter < it; iter++) {//iteraciones de comparar
  boolean fact = Arista.factible(solucion, grafo);//la solucion es factible
  ArrayList<Integer> otrasolucion = modificacion(solucion, n, fact); //modifica la solucion inicial a otra solucion
  boolean otraFact = Arista.factible(otrasolucion, grafo);//verifica que sea factible
  int otraObj = Arista.objetivo(otrasolucion);//el objetivo de esta
  int temp= mejorObj - obj;
  if (otraFact && otraObj <= obj) {//si la otra es factible y el objetivo es menor igual 
      solucion = otrasolucion;//ahora cambian de papel
      obj = otraObj;
      fact = otraFact;
      if(Arista.r.nextDouble() <= Math.exp(temp))//
   {
       temperact*= enfriamiento;
       lista.add(otraObj);
       System.out.println("RS "+ otraObj+ (fact ? "  factible" : "  no factible"));
   }
      
      if (obj < mejorObj) {//si es mejor que el mejor objetivo
   mejorObj = obj;
   mejorSol = new ArrayList<Integer>();//la agrega como mejor solucion
   Iterator<Integer> ve = solucion.iterator();
   while (ve.hasNext()) {
       mejorSol.add(ve.next());
   }
      }
  } 
  lista.add(mejorObj);
  System.out.println(reinicio + " " +iter + " " + obj + " " + (fact ? "factible" : "no factible")) ;
     }
 }
 //Arista.imprime(lista);
 return mejorSol;
    }


martes, 3 de julio de 2012

Búsqueda Tabú

El algoritmo consiste en utilizar Búsqueda Local pero con una solución inicial brindada con un factor de azar. La solución que brinda se guarda para futuras comparaciones y será actualizado en aquellos casos donde la nueva solución sea mejor que la anterior.

El motivo por el cual se parte de una solución inicial al azar es porque, al ser GRASP un algoritmo que solamente termina cuando llega a su límite de iteraciones máximas o durante unas iteraciones predeterminadas no hubo cambios. Si la solución fuese la cota inferior, siempre partiría de la misma, y siempre llegaría a lo mismo, terminando el algoritmo en los pasos dichos por la cantidad de iteraciones sin cambios.

-while
-Genera Solución inicial
-Aplica Busqueda Local
-if la solucion actual es mejor solucion
   mejorSol= solActual
}}
return  mejorSol;



En el peor caso, el algoritmo deberá  iterar hasta alcanzar la cantidad máxima de iteraciones (ya que se supone que es mucho mayor a la cantidad de iteraciones que deben pasar sin cambios para parar). Dado que en cada iteración se ejecutan SolucionInicial y la BusquedaLocal, la complejidad sería
                        O(im ∗ (n² + n⁵ m)) = O(im ∗ n⁵ m)
aunque, por supuesto, no se espera que llegue nunca a ejecutar casos de ese estilo.

En cada etapa construir una lista de candidatos con movimientos admisibles Ordenados con respecto a su beneficio.
Restringir la lista de forma que contenga buenos movimiento aunque no necesariamente óptimo „ Restringir por cardinalidad (los Objetivos mejores)

Idea:produce una diversidad de buenas soluciones, se espera que al menos una de ellas esté en un entorno de la solución óptima.
Se generaron 15 aristas.
Cota inferior: 4.
Cota superior: 7.
0 0 5 factible
0 1 5 factible
0 2 5 factible
0 3 5 factible
0 4 5 factible
1 0 7 factible
1 1 7 factible
1 2 7 factible
1 3 7 factible
1 4 7 factible
2 0 7 factible
2 1 7 factible
2 2 7 factible
2 3 6 factible
2 4 6 factible
3 0 7 factible
3 1 6 factible
3 2 6 factible
3 3 6 factible
3 4 6 factible
4 0 7 factible
4 1 7 factible
4 2 7 factible
4 3 7 factible
4 4 7 factible
5 0 6 factible
5 1 6 factible
5 2 6 factible
5 3 6 factible
5 4 6 factible
6 0 7 factible
6 1 7 factible
6 2 7 factible
6 3 7 factible
6 4 7 factible



public static boolean tabu (ArrayList<ArrayList<Integer>>cola, ArrayList<Integer> solucion, int iter)
    {
 cola = null;
 while(iter>0)
     { 
  if(cola.contains(solucion))
      {
   //cont++;modifica();
   return false;
      }
  else 
      {
   cola.add(solucion);
   if (cola.size()>=iter)
       {
    cola.remove(cola.get(0));
       }
      }
     }
 return true;
    }
    //busqueda**
    public static ArrayList<Integer> busqueda(ArrayList<Arista> grafo, int n,int it,int re) {
 ArrayList<ArrayList<Integer>> listatabu = new ArrayList<ArrayList<Integer>>();
 ArrayList<Integer> mejorSol = null;
 int intentos =0;
 boolean TAB;
 //define la mejor solucion como nula para que cualquiera pueda mejorarla
 int mejorObj = n;//tamaño de la cubierta inicial seria el total de nodos en el grafo idem
 ArrayList<Integer> lista = new ArrayList<Integer>();
 
 for (int reinicio = 0; reinicio < re; reinicio++) {//pasos de reinicio
     ArrayList<Integer> solucion = Arista.inicial(grafo);//solucion inicial
     //Arista.imprime(solucion);
     int obj = Arista.objetivo(solucion);//objetivo de solucion
     
     for (int iter = 0; iter < it; iter++) {//iteraciones de comparar
  boolean fact = Arista.factible(solucion, grafo);//la solucion es factible
  ArrayList<Integer> otrasolucion = modificacion(solucion, n, fact); //modifica la solucion inicial a otra solucion
  boolean otraFact = Arista.factible(otrasolucion, grafo);//verifica que sea factible
  int otraObj = Arista.objetivo(otrasolucion);//el objetivo de esta
  if (otraFact && otraObj <= obj) {//si la otra es factible y el objetivo es menor igual 
      solucion = otrasolucion;//ahora cambian de papel
      obj = otraObj;
      fact = otraFact;
      if (obj < mejorObj) {//si es mejor que el mejor objetivo
   mejorObj = obj;
   mejorSol = new ArrayList<Integer>();//la agrega como mejor solucion
   Iterator<Integer> ve = solucion.iterator();
   while (ve.hasNext()) {
       mejorSol.add(ve.next());
   }
      }
  } 
  System.out.println(reinicio + " " +iter + " " + obj + " " + (fact ? "factible" : "no factible")) ;
     }
 }
 // return mejorSol;//regresa la mejor solucion 
 //incluir busqueda tabú

 while(intentos>0)
     {
  TAB=false;
  int Obj=Arista.objetivo(mejorSol);
  boolean fact=Arista.factible(mejorSol,grafo);
  ArrayList<Integer> Actual = Arista.modificacion(mejorSol,n,fact);
  fact=Arista.factible(Actual,grafo);
  int objetivo=Arista.objetivo(Actual);
  
  if(tabu(listatabu,Actual,10)==true)//lista!
      {
   if(fact==true && Obj<=objetivo)
       {
    TAB=true;
    mejorSol = Actual;
    Obj = objetivo;
    if(objetivo<Obj)
       {
    System.out.println("MejorSolucion "+mejorSol+"Cobertura"+Obj+".");
    Arista.imprime(listatabu);//
       }
    if(TAB ==false)
        {
     intentos --;
        }  
    else
        System.out.println("reintenta ->"+"#intentos:"+intentos);      
       }
      }
     }
 return mejorSol;
    }