diff --git a/.gitignore b/.gitignore index c30bcbb..25968b5 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ nbproject/private/private.xml nbproject/private/private.properties /log/ *0.txt +nbproject/genfiles.properties + +nbproject/build-impl.xml diff --git a/bash.exe.stackdump b/bash.exe.stackdump new file mode 100644 index 0000000..abb9208 --- /dev/null +++ b/bash.exe.stackdump @@ -0,0 +1,11 @@ +Stack trace: +Frame Function Args +00800000010 0018006392E (00180279F10, 0018026AFD1, 00800000010, 000FFFFBA20) +00800000010 0018004973A (00100002000, 000FFFFCBC0, 00180350128, 00000000002) +00800000010 00180049772 (00000000002, 00180350438, 00800000010, 00000000008) +00800000010 0018005CBDD (0018004ABEC, 000FFFFCC55, 00000000000, 000FFFFCC50) +000FFFFCBCC 0018005CD4F (205C795C745C745C, 655C205C265C265C, 205C6F5C685C635C, 695C6C5C245C225C) +000FFFFCCE0 00180049EE8 (00000000000, 00000000000, 00000000000, 00000000000) +000FFFFFFF0 00180048846 (00000000000, 00000000000, 00000000000, 00000000000) +000FFFFFFF0 001800488F4 (00000000000, 00000000000, 00000000000, 00000000000) +End of stack trace diff --git a/config.txt b/config.txt index 23d4a08..055af1a 100644 --- a/config.txt +++ b/config.txt @@ -1,5 +1,8 @@ Archivos=GKD-c_1_n500_m50.txt GKD-c_2_n500_m50.txt GKD-c_3_n500_m50.txt SOM-b_11_n300_m90.txt SOM-b_12_n300_m120.txt SOM-b_13_n400_m40.txt MDG-a_21_n2000_m200.txt MDG-a_22_n2000_m200.txt MDG-a_23_n2000_m200.txt Semillas=26522589 65225892 52258926 22589265 25892652 -Algoritmos=Greedy Búsqueda_Local Búsqueda_Tabú +Poblacion=50 Evaluaciones=50000 -Tenencia_Tabu=5 +Prob_Cruce=0.7 +Prob_Mutacion=0.05 +Elite=2 3 +Cruce=2P MPX diff --git a/nbproject/private/config.properties b/nbproject/private/config.properties new file mode 100644 index 0000000..e69de29 diff --git a/nbproject/project.properties b/nbproject/project.properties index 896e841..3fe2fb2 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -1,9 +1,10 @@ annotation.processing.enabled=true annotation.processing.enabled.in.editor=false -annotation.processing.processor.options= annotation.processing.processors.list= annotation.processing.run.all.processors=true annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=Metaheristicas_Pr_2 +application.vendor=Miguerubsk build.classes.dir=${build.dir}/classes build.classes.excludes=**/*.java,**/*.form # This directory is removed when the project is cleaned: @@ -32,9 +33,10 @@ dist.jar=${dist.dir}/Metaheristicas_Pr_2.jar dist.javadoc.dir=${dist.dir}/javadoc dist.jlink.dir=${dist.dir}/jlink dist.jlink.output=${dist.jlink.dir}/Metaheristicas_Pr_2 +endorsed.classpath= excludes= includes=** -jar.compress=false +jar.compress=true javac.classpath= # Space-separated list of extra javac options javac.compilerargs= diff --git a/src/AGGeneracional/Genetico.java b/src/AGGeneracional/Genetico.java new file mode 100644 index 0000000..b797073 --- /dev/null +++ b/src/AGGeneracional/Genetico.java @@ -0,0 +1,481 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package AGGeneracional; + +import java.util.Random; +import java.util.Vector; +import java.util.concurrent.ExecutionException; +import tools.CargaDatos; +import tools.Configurador; + +/** + * + * @author miguerubsk + */ +public class Genetico { + + private final CargaDatos datos; //Datos para realizar la ejecucion + private final Configurador config; //Archivo de configuracion + private final Integer tamSolucion; //Tamaño de la solucion + private final Long semilla; //Semilla para inicializacion del aleatorio + private final Integer numElite; //Numero de elementos que formaran la elite + + private final Random aleatorio; //Genera aleatorios + private int t = 0, conte = 0, peorCo1, peorCo2, mejorCo1, mejorCo2, posPeor1, posPeor2; + float mejorCosteGlobal = -1; + private Poblacion poblacion, nuevaPoblacion; //Poblacion actual, y nueva poblacion con la que iremos trabajando + private Vector posi, mejor1, mejor2, mejorActual; + private final String operadorCruce; //Operador de cruce que se usara en la ejecucion + private Individuo mejorIndividuo; + + public Genetico(CargaDatos datos, Configurador config, Long semilla, String operadorCruce, Integer numElite) { + this.poblacion = new Poblacion(semilla, datos, true, config); + this.aleatorio = new Random(semilla); + this.operadorCruce = operadorCruce; + this.datos = datos; + this.nuevaPoblacion = null; + this.config = config; + this.tamSolucion = datos.getTamSolucion(); + this.semilla = semilla; + this.numElite = numElite; + } + + /** + * @brief Realiza la ejecucion del algoritmo + */ + public void ejecutar() throws Exception { + int iteracion = 0; + switch (operadorCruce) { + case "2P": + int contador; + /*Ejecutamos el algoritmo hasta que se complete el numero de iteraciones*/ + while (iteracion < 300) { + nuevaPoblacion = new Poblacion(semilla, datos, false, config); //Creamos una nueva poblacion para trabajar sobre ella + contador = 0; + + Vector elite = generarElite(); //Generamos la elite de la actual generacion + + Vector seleccion = seleccionTorneo(); //Realizamos la seleccion por torneo + + /*Realizamos el cruce y su reparacion para cada uno de los elementos de la seleccion.+ + Se realizará el cruce y reparacion con probabilidad 0.7. + Si no se realiza cruce, el individuo es añadido sin realizar su cruce.*/ + for (int i = 0; i < seleccion.size(); i += 2) { + if (aleatorio.nextDouble() < config.getProb_Cruce()) { + cruce2P(seleccion.get(i), seleccion.get(i + 1)); + reparar2Puntos(nuevaPoblacion.getIndividuo(contador).getCromosoma(), datos.getMatriz(), datos.getTamSolucion()); + reparar2Puntos(nuevaPoblacion.getIndividuo(contador + 1).getCromosoma(), datos.getMatriz(), datos.getTamSolucion()); + contador += 2; + } else { + nuevaPoblacion.addIndividuo(seleccion.get(i)); + nuevaPoblacion.addIndividuo(seleccion.get(i + 1)); + } + } + + /*Realizamos la mutacion para cada elemento de los cromosomas de cada individuo. + Esta mutacion tiene una probabilidad de 0.05.*/ + for (int i = 0; i < nuevaPoblacion.getTamPoblacion(); i++) { + for (int j = 0; j < nuevaPoblacion.getIndividuo(i).getTamCromosoma(); j++) { + if (aleatorio.nextDouble() < config.getProb_Mutacion()) { + Mutacion(nuevaPoblacion.getIndividuo(i).getCromosoma(), j, datos.getTamMatriz()); + nuevaPoblacion.getIndividuo(i).setCalculado(false); + } + } + } + + + /*Añadimos los individuos elite*/ + for (Individuo individuo : elite) { + nuevaPoblacion.addIndividuo(individuo); + } + + /*Sustituimos la poblacion anterior con la nueva poblacion*/ + poblacion = nuevaPoblacion; + + /*Calculamos los costes de cada individuo si este no los tiene actualizados*/ + for (int i = 0; i < poblacion.getTamPoblacion(); i++) { + if (!poblacion.getIndividuo(i).isCalculado()) { + poblacion.getIndividuo(i).actualizarCoste(); + + iteracion++; //Sumamos una iteracion por cada calculo del coste + } + } + + eliminarIndividuosSobrantes(poblacion); + } + + break; + + case "MPX": + while (iteracion < 300) { + Vector elite = generarElite(); //Generamos la elite de la actual generacion + + for (int i = 0; i < poblacion.getTamPoblacion(); i += 2) { + Vector crom1 = obtenerHijoMPX(poblacion.getIndividuo(i).getCromosoma(), poblacion.getIndividuo(i + 1).getCromosoma(), (int) config.getProb_Cruce() * 100); + Vector crom2 = obtenerHijoMPX(poblacion.getIndividuo(i).getCromosoma(), poblacion.getIndividuo(i + 1).getCromosoma(), (int) config.getProb_Cruce() * 100); + + poblacion.getIndividuo(i).setCromosoma(crom1); + poblacion.getIndividuo(i + 1).setCromosoma(crom2); + + repararMPX(poblacion.getIndividuo(i).getCromosoma(), datos.getMatriz(), datos.getTamSolucion()); + repararMPX(poblacion.getIndividuo(i + 1).getCromosoma(), datos.getMatriz(), datos.getTamSolucion()); + } + + for (int i = 0; i < poblacion.getTamPoblacion(); i++) { + for (int j = 0; j < poblacion.getIndividuo(i).getTamCromosoma(); j++) { + if (aleatorio.nextDouble() < config.getProb_Mutacion()) { + Mutacion(poblacion.getIndividuo(i).getCromosoma(), j, datos.getTamMatriz()); + poblacion.getIndividuo(i).setCalculado(false); + } + } + } + + /*Añadimos los individuos elite*/ + for (Individuo individuo : elite) { + poblacion.addIndividuo(individuo); + } + + for (int i = 0; i < poblacion.getTamPoblacion(); i++) { + if (!poblacion.getIndividuo(i).isCalculado()) { + poblacion.getIndividuo(i).actualizarCoste(); + + iteracion++; //Sumamos una iteracion por cada calculo del coste + } + } + + eliminarIndividuosSobrantes(poblacion); + iteracion -= numElite; + } + + break; + } + + /*Guardamos el individuo con mejor coste como el mejor individuo de toda la poblacion*/ + double mayor = 0; + Integer mejor = null; + + for (int i = 0; i < poblacion.getTamPoblacion(); i++) { + if (poblacion.getIndividuo(i).getCoste() > mayor) { + mayor = poblacion.getIndividuo(i).getCoste(); + mejor = i; + + } + } + + mejorIndividuo = poblacion.getIndividuo(mejor); + +// System.out.println("Tamaño poblacion: " + poblacion.getTamPoblacion() + "\n"); +// for (int i = 0; i < poblacion.getTamPoblacion(); i++) { +// System.out.println("Coste: " + nuevaPoblacion.getIndividuo(i).getCoste() + "\nCromosoma: " + nuevaPoblacion.getIndividuo(i).getCromosoma().toString()); +// } + } + + //Funciones auxiliares + /** + * @brief Realiza una seleccion por torneo con k = 2 + * @return vector con la seleccion de los individuos + */ + private Vector seleccionTorneo() { + + Vector seleccion = new Vector<>(); + int p1, p2; + + do { + do { + p1 = aleatorio.nextInt(poblacion.getTamPoblacion()); + p2 = aleatorio.nextInt(poblacion.getTamPoblacion()); + } while (p2 == p1 && seleccion.contains(poblacion.getIndividuo(p1)) && seleccion.contains(poblacion.getIndividuo(p2))); + + if (poblacion.getIndividuo(p1).getCoste() > poblacion.getIndividuo(p2).getCoste()) { + seleccion.add(poblacion.getIndividuo(p1)); + } else { + seleccion.add(poblacion.getIndividuo(p2)); + } + } while (seleccion.size() < config.getTamPoblacion()); + + return seleccion; + } + + /** + * @brief Cruza dos cromosomas usando el cruce en 2 puntos + * @param individuoA Primer cromosoma a cruzar + * @param individuoB Segundo cromosoma a cruzar + */ + private void cruce2P(Individuo individuoA, Individuo individuoB) { + try { + Vector r1 = new Vector<>(), r2 = new Vector<>(); + int tam = individuoA.getTamCromosoma(); + int p1, p2, aux; + p1 = aleatorio.nextInt(tam); + + do { + p2 = aleatorio.nextInt(tam); + } while (p2 == p1); + + if (p1 > p2) { + aux = p1; + p1 = p2; + p2 = aux; + } + + for (int i = 0; i < p1; i++) { + r1.add(individuoB.getCromosoma().get(i)); + r2.add(individuoA.getCromosoma().get(i)); + } + for (int i = p1; i < p2; i++) { + r1.add(individuoA.getCromosoma().get(i)); + r2.add(individuoB.getCromosoma().get(i)); + } + for (int i = p2; i < individuoA.getTamCromosoma(); i++) { + r1.add(individuoB.getCromosoma().get(i)); + r2.add(individuoA.getCromosoma().get(i)); + } + + individuoA.setCromosoma(r1); + individuoB.setCromosoma(r2); + nuevaPoblacion.addIndividuo(new Individuo(semilla, datos)); + nuevaPoblacion.addIndividuo(new Individuo(semilla, datos)); + } catch (Exception e) { + System.err.println("AGGeneracional.Genetico.cruce2P(): " + e.toString()); + } + } + + /** + * @brief funcion que cruza dos cromosomas usando MPX + * @param a primer cromosoma a cruzar + * @param b segundo cromosoma a cruzar + * @param por probabilidad de que se realize el cruce + */ + private void cruceMPX(Vector a, Vector b, int por) { + //@TODO + } + + /** + * @brief Funcion que muta un gen de un cromosoma + * @param v Cromosoma que se quiere mutar + * @param p posicion del gen que se quiere mutar + * @param n rango de valores de la mutacion + */ + private void Mutacion(Vector v, int p, int n) { + int x = 0; + do { + x = aleatorio.nextInt(n); + } while (v.contains(x)); + + intercambia(p, x, v); + } + + /** + * @brief Funcion que repara una solucion no factible + * @param a Solucion a reparar + * @param dist matriz de distancias + * @param n tamaño solucion + */ + private void reparar2Puntos(Vector a, double dist[][], int n) { + try { + Vector r = new Vector(); + + for (int i = 0; i < a.size(); i++) { + boolean enc = false; + for (int j = 0; j < r.size(); j++) { + if (a.get(i) == r.get(j)) { + enc = true; + break; + } + + } + if (!enc) { + r.add(a.get(i)); + } + } + int x = a.size() - r.size(); + for (int i = 0; i < x; i++) { + int ele = MasAporta(dist, a, n); + a.add(a.get(ele)); + } + } catch (Exception e) { + System.err.println("AGGeneracional.Genetico.reparar2Puntos(): " + e.toString()); + } + } + + //@TODO + private void repararMPX(Vector a, double dist[][], int m) { + int dif = a.size() - m; + for (int i = 0; i < dif; i++) { + int p = menorAporte(a.size(), dist, a); + a.remove(p); + } + + Vector r = new Vector(); + + for (int i = 0; i < a.size(); i++) { + boolean enc = false; + for (int j = 0; j < r.size(); j++) { + if (a.get(i) == r.get(j)) { + enc = true; + break; + } + + } + if (!enc) { + r.add(a.get(i)); + } + } + + a = r; + } + + /** + * @brief función que devuelve un hijo al cruzar dos cromosomas usando MPX + * @param a primer cromosoma a cruzar + * @param b segundo cromosoma a cruzar + * @param prob probabilidad de que se realize el cruce + * @return un cromosoma resultado de cruzar dos cromosomas + */ + private Vector obtenerHijoMPX(Vector a, Vector b, int prob) { + int p; + Vector aa = a, bb = b, r = new Vector<>(); + int tam = aa.size(); + int elegibles = tam * prob / 100; + int tamaP = tam; + + for (int i = 0; i < elegibles; i++) { + p = aleatorio.nextInt(tamaP); + tamaP--; + r.add(aa.get(p)); + aa.remove(p); + } + + for (int i = 0; i < tam; i++) { + if (!r.contains(bb.get(i))) { + r.add(b.get(i)); + } + } + return r; + } + + /** + * @brief Funcion que obtiene la posicion de menor aporte de la solucion + * @param m tamaño de la solucion + * @param dist matriz de distancias + * @param vector una solucion + * @return posicion de menor aporte + */ + private Integer menorAporte(int m, double[][] dist, Vector vector) { + double peso = 0.0; + Integer posMenor = 0; + double menor = 999999999; + for (int i = 0; i < m; i++) { + for (int j = 0; j < m; j++) { + if (vector.get(i) != vector.get(j)) { + peso += dist[vector.get(i)][vector.get(j)]; + } + } + + if (peso < menor) { + menor = peso; + posMenor = i; + } + peso = 0.0; + } + + return posMenor; + } + + /** + * @brief Funcion que obtiene la posicion de mayor aporte de la solucion + * @param dist matriz de distancias + * @param vector una solucion + * @param m tamaño de la solucion + * @return posicion de mayor aporte + */ + private int MasAporta(double dist[][], Vector vector, int m) { + double peso = 0.0; + double mayor = 0.0; + int posMayor = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < m; j++) { + if (vector.get(i) != vector.get(j)) { + peso += dist[vector.get(i)][vector.get(j)]; + } + } + + if (peso < mayor) { + mayor = peso; + posMayor = i; + } + peso = 0.0; + } + + return posMayor; + } + + /** + * @brief Operador de intercambio que cambia un elemento por otro en la + * solucion + * @param i indice del elemento que se quiere modificar + * @param j elemento que se quiere añadir en la posicion i + */ + private void intercambia(int i, int j, Vector solucion) { + solucion.setElementAt(j, i); + } + + private Vector generarElite() { + Integer generados = 0; + Vector elite = new Vector<>(); + Vector posiciones = new Vector<>(); + do { + double mayor = 0; + Integer mejor = null; + + for (int i = 0; i < poblacion.getTamPoblacion(); i++) { + if (poblacion.getIndividuo(i).getCoste() > mayor && !poblacion.getIndividuo(i).isElite()) { + mayor = poblacion.getIndividuo(i).getCoste(); + mejor = i; + } + } + + elite.add(poblacion.getIndividuo(mejor)); + poblacion.getIndividuo(mejor).setElite(true); + posiciones.add(mejor); + generados++; + } while (generados < numElite); + + for (Integer posicion : posiciones) { + poblacion.getIndividuo(posicion).setElite(false); + } + + for (Individuo individuo : elite) { + individuo.setElite(false); + } + + return elite; + } + + public Individuo getMejorIndividuo() { + return mejorIndividuo; + } + + public int getTamPoblacion() { + return poblacion.getTamPoblacion(); + } + + private void eliminarIndividuosSobrantes(Poblacion poblacion) { + int dif = poblacion.getTamPoblacion() - config.getTamPoblacion(); + for (int i = 0; i < dif; i++) { + double menorCoste = 999999999; + int pos = 0; + for (int j = 0; j < poblacion.getTamPoblacion(); j++) { + + if (poblacion.getIndividuo(j).getCoste() < menorCoste) { + menorCoste = poblacion.getIndividuo(j).getCoste(); + pos = j; + } + } + poblacion.removeIndividuo(pos); + } + } +} diff --git a/src/AGGeneracional/Individuo.java b/src/AGGeneracional/Individuo.java new file mode 100644 index 0000000..f9c760e --- /dev/null +++ b/src/AGGeneracional/Individuo.java @@ -0,0 +1,116 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package AGGeneracional; + +//import java.util.Random; +import java.util.Vector; +import tools.CargaDatos; +import tools.Random; + +/** + * + * @author miguerubsk + */ +public class Individuo { + + private Vector cromosoma; + private int tamCromosoma; + private double coste; + private Random aleatorio; + private boolean calculado; + private boolean elite; + private CargaDatos datos; + + public Individuo(long semilla, CargaDatos datos) { + this.datos = datos; + this.aleatorio = new Random(semilla); + this.tamCromosoma = this.datos.getTamSolucion(); + this.cromosoma = generarCromosomaAleatorio(this.datos.getTamMatriz()); + this.coste = coste(this.datos); + this.calculado = true; + this.elite = false; + } + + public void setCromosoma(Vector cromosoma) { + this.cromosoma = cromosoma; + this.calculado = false; + } + + public Vector getCromosoma() { + return cromosoma; + } + + public int getTamCromosoma() { + return tamCromosoma; + } + + public double getCoste() { + return coste; + } + + public boolean isCalculado() { + return calculado; + } + + public void actualizarCoste() { + if (!calculado) { + coste = coste(datos); + calculado = true; + } + } + + /** + * @brief Genera una solucion aleatoria + * @param tamañoSolucion tamaño de la solucion + * @param tamañoMatriz tamaño de la matriz + */ + private Vector generarCromosomaAleatorio(int tamañoMatriz) { + Integer generados = 0; + Vector crom = new Vector(); + + while (generados < tamCromosoma) { +// Integer elemento = aleatorio.nextInt(tamañoMatriz); + Integer elemento = aleatorio.Randint(0, tamañoMatriz - 1); + if (!crom.contains(elemento)) { + crom.add(elemento); + generados++; + } + } + return crom; + } + + /** + * @brief Función que calcula el coste de la solucion + * @param matriz matriz de distancias + * @param tamañoSolucion tamaño de la solucion + * @return Coste de la solucion + */ + private double coste(CargaDatos datos) { + double coste = 0.0; + + for (int i = 0; i < tamCromosoma; i++) { + for (int j = i + 1; j < tamCromosoma; j++) { + coste += datos.getMatriz()[cromosoma.get(j)][cromosoma.get(i)]; + } + } + + return coste; + } + + public boolean isElite() { + return elite; + } + + public void setElite(boolean elite) { + this.elite = elite; + } + + public void setCalculado(boolean calculado) { + this.calculado = calculado; + } + + +} diff --git a/src/AGGeneracional/Poblacion.java b/src/AGGeneracional/Poblacion.java new file mode 100644 index 0000000..cdd4167 --- /dev/null +++ b/src/AGGeneracional/Poblacion.java @@ -0,0 +1,73 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package AGGeneracional; + +import java.util.Vector; +import java.util.concurrent.*; +import tools.CargaDatos; +import tools.Configurador; +import tools.Random; + +/** + * + * @author miguerubsk + */ +public class Poblacion { + + private Vector poblacion; + private int tamPoblacion; + private long semilla; + private CargaDatos datos; + private final Configurador config; + private Random aleatorio; + + public Poblacion(long semilla, CargaDatos datos, boolean generar, Configurador config) { + this.poblacion = new Vector(); + this.tamPoblacion = 0; + this.semilla = semilla; + this.datos = datos; + this.config = config; + this.aleatorio = new Random(1231123112); + if (generar) { + generarPoblacion(); + } + } + + @Override + public String toString() { + return "Poblacion{" + "poblacion=" + poblacion + ", tamPoblacion=" + tamPoblacion + ", semilla=" + semilla + ", datos=" + datos + '}'; + } + + public void addIndividuo(Individuo individuo) throws Exception { +// if (tamPoblacion >= tamPoblacion + 2) { +// Exception excepcion = new Exception("El tamaño de la poblacion no puede ser mayor que " + String.valueOf(tamPoblacion + 2)); +// throw excepcion; +// } + poblacion.add(individuo); + tamPoblacion++; + } + + public Individuo getIndividuo(int i) { + return poblacion.get(i); + } + + public int getTamPoblacion() { + return tamPoblacion; + } + + public void removeIndividuo(int i) { + poblacion.remove(i); + tamPoblacion--; + } + + private void generarPoblacion() { + for (int i = 0; i < config.getTamPoblacion(); i++) { + Individuo nuevoIndividuo = new Individuo(semilla + aleatorio.Randint(0, datos.getTamMatriz()), datos); + poblacion.add(nuevoIndividuo); + tamPoblacion++; + } + } +} diff --git a/src/metaheristicas_pr_2/Metaheristicas_Pr_2.java b/src/metaheristicas_pr_2/Metaheristicas_Pr_2.java index d83bbb5..0938c4b 100644 --- a/src/metaheristicas_pr_2/Metaheristicas_Pr_2.java +++ b/src/metaheristicas_pr_2/Metaheristicas_Pr_2.java @@ -5,6 +5,17 @@ */ package metaheristicas_pr_2; +import AGGeneracional.Genetico; +import java.util.ArrayList; +import java.util.Vector; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.logging.Level; +import java.util.logging.Logger; +import tools.CargaDatos; +import tools.Configurador; + /** * * @author Miguerubsk @@ -15,7 +26,39 @@ public class Metaheristicas_Pr_2 { * @param args the command line arguments */ public static void main(String[] args) { - // TODO code application logic here + //Cargamos el archivo de configuracion + Configurador config = new Configurador("config.txt"); + + //Cargamos los ficheros de datos + ArrayList Datos = new ArrayList<>(); + for (int i = 0; i < config.getFicheros().size(); i++) { + Datos.add(new CargaDatos(config.getFicheros().get(i))); + } + + for (int i = 0; i < config.getTipoCruce().size(); i++) { + for (int j = 0; j < config.getElite().size(); j++) { + for (int k = 0; k < Datos.size(); k++) { + for (int l = 0; l < config.getSemillas().size(); l++) { + Genetico genetico = new Genetico(Datos.get(k), config, config.getSemillas().get(l), config.getTipoCruce().get(i), config.getElite().get(j)); + try { + // System.out.println("i: " + i + " j: " + j + " k: " + k); + genetico.ejecutar(); + } catch (Exception ex) { + Logger.getLogger(Metaheristicas_Pr_2.class.getName()).log(Level.SEVERE, null, ex); + } + System.out.println("EJECUCION TERMINADA" + + "\nFichero: " + Datos.get(k).getNombreFichero() + + "\nSemilla: " + config.getSemillas().get(l) + + "\nTipo de cruce: " + config.getTipoCruce().get(i) + + "\nNum de elite: " + config.getElite().get(j) + + "\nMejor individuo: " + genetico.getMejorIndividuo().getCromosoma().toString() + + "\nTamaño cromosoma: " + genetico.getMejorIndividuo().getCromosoma().size() + + "\nCoste mejor individuo: " + genetico.getMejorIndividuo().getCoste() + + "\nTamaño poblacion final: " + genetico.getTamPoblacion() + + "\n---------------------------------------------"); + } + } + } + } } - } diff --git a/src/tools/CargaDatos.java b/src/tools/CargaDatos.java new file mode 100644 index 0000000..05217c1 --- /dev/null +++ b/src/tools/CargaDatos.java @@ -0,0 +1,70 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package tools; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +/** + * + * @author Miguerubsk + */ +public class CargaDatos { + private int TamMatriz, TamSolucion; + private double Matriz[][]; + private String NombreFichero; + + public CargaDatos(String fichero){ + NombreFichero = fichero; + FileReader f = null; + String linea; + try { + f = new FileReader(fichero); + BufferedReader b = new BufferedReader(f); + + if((linea = b.readLine()) != null){ + String[] split = linea.split(" "); + TamMatriz = Integer.parseInt(split[0]); + TamSolucion = Integer.parseInt(split[1]); + Matriz = new double[TamMatriz][TamMatriz]; + } + + for (int i = 0; i < TamMatriz; i++) { + for (int j = 0; j < TamMatriz; j++) { + Matriz[i][j] = 0; + } + } + + while((linea = b.readLine()) != null){ + String[] split = linea.split(" "); + Matriz[Integer.parseInt(split[0])][Integer.parseInt(split[1])] = Double.parseDouble(split[2]); + Matriz[Integer.parseInt(split[1])][Integer.parseInt(split[0])] = Double.parseDouble(split[2]); + } + + } catch (IOException e) { + System.out.println(e); + } + + } + + public int getTamMatriz() { + return TamMatriz; + } + + public int getTamSolucion() { + return TamSolucion; + } + + public double[][] getMatriz() { + return Matriz; + } + + public String getNombreFichero() { + return NombreFichero; + } + +} diff --git a/src/tools/Configurador.java b/src/tools/Configurador.java new file mode 100644 index 0000000..74b11be --- /dev/null +++ b/src/tools/Configurador.java @@ -0,0 +1,116 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package tools; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +/** + * + * @author Miguerubsk + */ +public class Configurador { + + private ArrayList Ficheros, tipoCruce; + private ArrayList Semillas; + private ArrayList Elite; + private Integer Evaluaciones, TamPoblacion; + private float Prob_Cruce, Prob_Mutacion; + + public Configurador(String ruta) { + Ficheros = new ArrayList<>(); + tipoCruce = new ArrayList<>(); + Semillas = new ArrayList<>(); + Elite = new ArrayList<>(); + + String linea; + FileReader f = null; + try { + f = new FileReader(ruta); + BufferedReader b = new BufferedReader(f); + + while ((linea = b.readLine()) != null) { + String[] split = linea.split("="); + switch (split[0]) { + case "Archivos": + String[] vF = split[1].split(" "); + for (int i = 0; i < vF.length; i++) { + Ficheros.add(vF[i]); + } + break; + case "Semillas": + String[] vS = split[1].split(" "); + for (int i = 0; i < vS.length; i++) { + Semillas.add(Long.parseLong(vS[i])); + } + break; + case "Cruce": + String[] vA = split[1].split(" "); + for (int i = 0; i < vA.length; i++) { + tipoCruce.add(vA[i]); + } + break; + case "Elite": + String[] vE = split[1].split(" "); + for (int i = 0; i < vE.length; i++) { + Elite.add(Integer.parseInt(vE[i])); + } + break; + case "Evaluaciones": + Evaluaciones = Integer.parseInt(split[1]); + break; + case "Poblacion": + TamPoblacion = Integer.parseInt(split[1]); + break; + case "Prob_Cruce": + Prob_Cruce = Float.parseFloat(split[1]); + break; + case "Prob_Mutacion": + Prob_Mutacion = Float.parseFloat(split[1]); + break; + } + } + + } catch (IOException e) { + System.out.println(e); + } + } + + public ArrayList getFicheros() { + return Ficheros; + } + + public ArrayList getTipoCruce() { + return tipoCruce; + } + + public ArrayList getSemillas() { + return Semillas; + } + + public Integer getEvaluaciones() { + return Evaluaciones; + } + + public int getTamPoblacion() { + return TamPoblacion; + } + + public ArrayList getElite() { + return Elite; + } + + public float getProb_Cruce() { + return Prob_Cruce; + } + + public float getProb_Mutacion() { + return Prob_Mutacion; + } + +} diff --git a/src/tools/GuardarLog.java b/src/tools/GuardarLog.java new file mode 100644 index 0000000..e8113cb --- /dev/null +++ b/src/tools/GuardarLog.java @@ -0,0 +1,72 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package tools; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * + * @author Miguerubsk + */ +public class GuardarLog { + + private FileWriter fichero = null; + private PrintWriter pw = null; + private String separador = "\n-------------------------------------"; + + public GuardarLog(String nombreArchivo, String texto, String algoritmo) { + try { + String carpeta = "log/" + algoritmo + "/"; + File directorio = new File(carpeta); + if (!directorio.exists()) { + directorio.mkdirs(); + } + + File file = new File(carpeta + nombreArchivo + ".txt"); + if (!file.exists()) { + file.createNewFile(); + } else { + file.delete(); + file.createNewFile(); + } + fichero = new FileWriter(carpeta + nombreArchivo + ".txt"); + pw = new PrintWriter(fichero); + + pw.write(texto + separador); + + } catch (IOException e) { + System.err.println(e.toString()); + } + } + + public void escribir(String texto) { + try { + fichero.write("\n[INFORMACION]\n" + texto + "\n"); + } catch (Exception e) { + System.out.println("tools.GuardarLog.escribir()" + e.toString()); + } + } + + public void escribirNoInfo(String texto) { + try { + fichero.write("\n" + texto + "\n"); + } catch (Exception e) { + System.out.println("tools.GuardarLog.escribir()" + e.toString()); + } + } + + public void escribirFinal(String texto) { + try { + fichero.write(separador + "\n" + texto + "\n"); + fichero.close(); + } catch (Exception e) { + System.out.println("tools.GuardarLog.escribir()" + e.toString()); + } + } +} diff --git a/src/tools/Random.java b/src/tools/Random.java new file mode 100644 index 0000000..860385c --- /dev/null +++ b/src/tools/Random.java @@ -0,0 +1,54 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package tools; + +/** + * + * @author mamechapa + */ +public class Random { + + long Seed = 0L; + static final int MASK = 2147483647; + static final int PRIME = 65539; + static final double SCALE = 0.4656612875e-9; + + public Random(long x) { + Seed = (long) x; + } + + /*@brief Inicializa la semilla al valor x. Solo debe llamarse a esta funcion una vez en todo el programa */ + public void Set_random(long x) { + Seed = (long) x; + } + + /*@brief Devuelve el valor actual de la semilla */ + public long Get_random() { + return Seed; + } + + /*@brief Genera un numero aleatorio real en el intervalo [0,1](incluyendo el 0 pero sin incluir el 1) */ + public float Rand() { + return (float) ((Seed = ((Seed * PRIME) & MASK)) * SCALE); + } + + /*@brief Genera un numero aleatorio entero en {low,...,high} + * @param low + * @param high + */ + public int Randint(int low, int high) { + return (int) (low + (high - (low) + 1) * Rand()); + } + + /*@brief Genera un numero aleatorio real en el intervalo [low,...,high](incluyendo 'low' pero sin incluir 'high') + * @param low + * @param high + */ + public float Randfloat(float low, float high) { + return (low + (high - (low)) * Rand()); + } + +} \ No newline at end of file