Example #1
0
 /**
  * 9b) Descargar las sentencias de un almacén en un archivo de texto de nuestro directorio.
  *
  * @param nombreDeArchivo - fichero en el que se van a escribir las sentencias del almacén
  */
 public void descargar(String nombreDeArchivo) {
   try {
     Arista arista;
     Fichero.abrir(nombreDeArchivo, true, false);
     for (int i = 0; i < nodosSalientes.size(); ++i) {
       for (int j = 0; j < nodosSalientes.get(i).size(); ++j) {
         arista = nodosSalientes.get(i).get(j);
         for (int k = 0; k < arista.repeticiones; ++k)
           Fichero.escribirSentencia(
               listaSujetosObjetos.get(i)
                   + " "
                   + listaPropiedades.get(arista.propiedad)
                   + " "
                   + listaSujetosObjetos.get(arista.verticeObjetivo)
                   + " .");
       }
     }
     Fichero.cerrar();
   } catch (IOException e) {
     System.err.println("Error: Imposible acceder al fichero especificado.");
     return;
   }
 }
Example #2
0
  /** Reads the data of the configuration file */
  public void leer_conf() {
    int i, j;
    String cadenaEntrada, valor;
    double cruce, mutacion, a, b, tau;
    int long_poblacion, tipo_fitness;

    // we read the file in a String
    cadenaEntrada = Fichero.leeFichero(fichero_conf);
    StringTokenizer sT = new StringTokenizer(cadenaEntrada, "\n\r=", false);

    // we read the algorithm's name
    sT.nextToken();
    sT.nextToken();

    // we read the name of the training and test files
    sT.nextToken();
    valor = sT.nextToken();

    StringTokenizer ficheros = new StringTokenizer(valor, "\t ", false);
    ficheros.nextToken();
    fich_datos_chequeo = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fich_datos_tst = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fichero_br = ((ficheros.nextToken()).replace('\"', ' ')).trim();

    // we read the name of the output files
    sT.nextToken();
    valor = sT.nextToken();

    ficheros = new StringTokenizer(valor, "\t ", false);
    fich_tra_obli = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fich_tst_obli = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fichero_reglas = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    ruta_salida = fich_tst_obli.substring(0, fich_tst_obli.lastIndexOf('/') + 1);

    // we read the seed of the random generator
    sT.nextToken();
    valor = sT.nextToken();
    semilla = Double.parseDouble(Quita_blancos(valor));
    Randomize.setSeed((long) semilla);
    ;

    // we read the Number of Iterations
    sT.nextToken();
    valor = sT.nextToken();
    n_generaciones = Long.parseLong(Quita_blancos(valor));

    // we read the Population Size
    sT.nextToken();
    valor = sT.nextToken();
    long_poblacion = Integer.parseInt(Quita_blancos(valor));

    // we read the Tau parameter for the minimun maching degree required to the KB
    sT.nextToken();
    valor = sT.nextToken();
    tau = Double.parseDouble(Quita_blancos(valor));

    // we read the Parameter a
    sT.nextToken();
    valor = sT.nextToken();
    a = Double.parseDouble(Quita_blancos(valor));

    // we read the Parameter b
    sT.nextToken();
    valor = sT.nextToken();
    b = Double.parseDouble(Quita_blancos(valor));

    // we read the Type of Fitness Function
    sT.nextToken();
    valor = sT.nextToken();
    tipo_fitness = Integer.parseInt(Quita_blancos(valor));

    // we read the Cross Probability
    sT.nextToken();
    valor = sT.nextToken();
    cruce = Double.parseDouble(Quita_blancos(valor));

    // we read the Mutation Probability
    sT.nextToken();
    valor = sT.nextToken();
    mutacion = Double.parseDouble(Quita_blancos(valor));

    // we create all the objects
    tipoc = 1;
    tabla = new MiDataset(fich_datos_chequeo, true);
    if (tabla.salir == false) {
      base_reglas = new BaseR(fichero_br, tabla);
      fun_adap = new Adap(tabla, base_reglas, tau, tipo_fitness);
      alg_gen = new AG(long_poblacion, base_reglas.n_reglas, cruce, mutacion, a, b, fun_adap);
    }
  }
Example #3
0
  public void run() {
    int i, j;
    double ec, el, ec_tst, el_tst;

    /* We read the configutate file and we initialize the structures and variables */
    leer_conf();
    if (tabla.salir == false) {
      Gen = 0;

      /* Generation of the initial population */
      alg_gen.Initialize();

      /* Evaluation of the initial population */
      alg_gen.Evaluate();

      Gen++;

      /* Main of the genetic algorithm */
      do {
        /* Interchange of the new and old population */
        alg_gen.Intercambio();

        /* Selection by means of Baker */
        alg_gen.Select();

        /* Crossover */
        if (tipoc > 0) alg_gen.Max_Min_Crossover();
        else alg_gen.Cruce_Multipunto();

        /* Mutation */
        alg_gen.Mutacion();

        /* Elitist selection */
        alg_gen.Elitist();

        /* Evaluation of the current population */
        alg_gen.Evaluate();

        /* we increment the counter */
        Gen++;
      } while (Gen <= n_generaciones);

      /* we calcule the MSEs */
      fun_adap.Decodifica(alg_gen.solucion());
      fun_adap.Error_tra();
      ec = fun_adap.EC;
      el = fun_adap.EL;

      tabla_tst = new MiDataset(fich_datos_tst, false);
      fun_adap.Error_tst(tabla_tst);
      ec_tst = fun_adap.EC;
      el_tst = fun_adap.EL;

      fun_adap.Cubrimientos_Base();

      /* we write the RB */
      cadenaReglas = base_reglas.BRtoString();
      cadenaReglas +=
          "\nMSEtra: "
              + ec
              + "  MSEtst: "
              + ec_tst
              + "\nAverage covering degree: "
              + fun_adap.medcb
              + " Minimum covering degree: "
              + fun_adap.mincb;

      Fichero.escribeFichero(fichero_reglas, cadenaReglas);

      /* we write the obligatory output files*/
      String salida_tra = tabla.getCabecera();
      salida_tra += fun_adap.getSalidaObli(tabla);
      Fichero.escribeFichero(fich_tra_obli, salida_tra);

      String salida_tst = tabla_tst.getCabecera();
      salida_tst += fun_adap.getSalidaObli(tabla_tst);
      Fichero.escribeFichero(fich_tst_obli, salida_tst);

      /* we write the MSEs in specific files */
      Fichero.AnadirtoFichero(ruta_salida + "PcomunR.txt", "" + base_reglas.n_reglas + "\n");
      Fichero.AnadirtoFichero(ruta_salida + "PcomunTRA.txt", "" + ec + "\n");
      Fichero.AnadirtoFichero(ruta_salida + "PcomunTST.txt", "" + ec_tst + "\n");
    }
  }
Example #4
0
  /**
   * Constructora Carga las sentencias en el almacén desde el fichero especificado.
   *
   * @param nombreDeArchivo de texto desde el que leer las entidades
   */
  private Almacen(String nombreDeArchivo) throws IOException {
    // Inicializa los atributos de la clase
    nodosEntrantes = new ListaArray<ListaArray<Arista>>();
    nodosSalientes = new ListaArray<ListaArray<Arista>>();
    sujetos = objetos = propiedades = sentencias = 0;
    arbolSujetosObjetos = new Trie();
    arbolPropiedades = new Trie();
    listaSujetosObjetos = new ListaArray<String>();
    listaPropiedades = new ListaArray<String>();
    // Variables auxiliares
    int tempArista;
    Arista a;

    // Lee las sentencias desde el fichero y las añade al trie y a la lista de nodos del grafo
    Fichero.abrir(nombreDeArchivo, false, false);
    String sentencia, sujeto, propiedad, objeto;
    int idSujeto, idPropiedad, idObjeto;
    StringTokenizer tokenizador;
    sentencia = Fichero.leerSentencia();
    while (sentencia != null) {
      tokenizador = new StringTokenizer(sentencia);
      sujeto = tokenizador.nextToken();
      propiedad = tokenizador.nextToken();
      objeto = tokenizador.nextToken();
      sentencias++;

      // Insertar sujeto en el trie
      idSujeto = arbolSujetosObjetos.insertar(sujeto, sujetos + objetos);
      if (idSujeto == sujetos + objetos) {
        // Agregar al array de int -> String
        listaSujetosObjetos.insertLast(sujeto);
        // Añadir su hueco en las listas de adyacencia
        nodosEntrantes.insertLast(new ListaArray<Arista>());
        nodosSalientes.insertLast(new ListaArray<Arista>());
        // Incrementar contador
        sujetos++;
      }
      // Insertar propiedad en el trie
      idPropiedad = arbolPropiedades.insertar(propiedad, propiedades);
      if (idPropiedad == propiedades) {
        // Agregar al array de int -> String
        listaPropiedades.insertLast(propiedad);
        // En caso de ser una propiedad especial, guardar su valor entero
        if (propiedad.equals(propiedadEs)) idPropiedadEs = idPropiedad;
        else if (propiedad.equals(propiedadSubClaseDe)) idPropiedadSubClaseDe = idPropiedad;
        else if (propiedad.equals(propiedadCursa)) idPropiedadCursa = idPropiedad;
        else if (propiedad.equals(propiedadEncargadoDe)) idPropiedadEncargadoDe = idPropiedad;
        else if (propiedad.equals(propiedadDepartamentoDe)) idPropiedadDepartamentoDe = idPropiedad;
        else if (propiedad.equals(propiedadTrabajaPara)) idPropiedadTrabajaPara = idPropiedad;
        // Incrementar contador
        propiedades++;
      }
      // Insertar objeto en el trie
      idObjeto = arbolSujetosObjetos.insertar(objeto, sujetos + objetos);
      if (idObjeto == sujetos + objetos) {
        // Agregar al array de int -> String
        listaSujetosObjetos.insertLast(objeto);
        // Añadir su hueco en las listas de adyacencia
        nodosEntrantes.insertLast(new ListaArray<Arista>());
        nodosSalientes.insertLast(new ListaArray<Arista>());
        // Incrementar contador
        objetos++;
      }

      // Inserta la arista en la primera lista de adyacencia, o añade una repetición
      tempArista = nodosSalientes.get(idSujeto).find(new Arista(idObjeto, idPropiedad));
      if (tempArista == -1)
        nodosSalientes.get(idSujeto).insertLast(new Arista(idObjeto, idPropiedad));
      else nodosSalientes.get(idSujeto).get(tempArista).repeticiones++;

      // Lee la siguiente sentencia
      sentencia = Fichero.leerSentencia();
    }

    Fichero.cerrar();

    // Crear la segunda lista de adyacencia a partir de la primera
    for (int i = 0; i < nodosSalientes.size(); i++) {
      for (int j = 0; j < nodosSalientes.get(i).size(); j++) {
        a = nodosSalientes.get(i).get(j);
        nodosEntrantes
            .get(a.verticeObjetivo)
            .insertLast(new Arista(i, a.propiedad, a.repeticiones));
      }
    }

    // Ordenar las aristas salientes de cada nodo
    nodosSalientesOrdenados = new ListaArray<ListaArray<Integer>>(nodosSalientes.size());
    for (int i = 0; i < nodosSalientes.size(); ++i)
      nodosSalientesOrdenados.set(i, nodosSalientes.get(i).sort());
  }