⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gpgenotype.java

📁 JGAP是一种遗传算法和遗传规划的组成部分提供了一个Java框架。它提供了基本的遗传机制
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
   * @author Klaus Meffert
   * @since 3.0
   */
  public int compareTo(Object a_other) {
    try {
      // First, if the other Genotype is null, then they're not equal.
      // -------------------------------------------------------------
      if (a_other == null) {
        return 1;
      }
      GPGenotype otherGenotype = (GPGenotype) a_other;
      // First, make sure the other Genotype has the same number of
      // chromosomes as this one.
      // ----------------------------------------------------------
      int size1 = getGPPopulation().size();
      int size2 = otherGenotype.getGPPopulation().size();
      if (size1 != size2) {
        if (size1 > size2) {
          return 1;
        }
        else {
          return -1;
        }
      }
      // Next, prepare to compare the programs of the other Genotype
      // against the programs of this Genotype. To make this a lot
      // simpler, we first sort the programs in both this Genotype
      // and the one we're comparing against. This won't affect the
      // genetic algorithm (it doesn't care about the order), but makes
      // it much easier to perform the comparison here.
      // --------------------------------------------------------------
      Arrays.sort(getGPPopulation().getGPPrograms());
      Arrays.sort(otherGenotype.getGPPopulation().getGPPrograms());
      for (int i = 0; i < getGPPopulation().size(); i++) {
        int result = (getGPPopulation().getGPProgram(i).compareTo(
            otherGenotype.getGPPopulation().getGPProgram(i)));
        if (result != 0) {
          return result;
        }
      }
      return 0;
    } catch (ClassCastException e) {
      return -1;
    }
  }

  /***
   * Hashcode function for the genotype, tries to create a unique hashcode for
   * the chromosomes within the population. The logic for the hashcode is
   *
   * Step  Result
   * ----  ------
   *    1  31*0      + hashcode_0 = y(1)
   *    2  31*y(1)   + hashcode_1 = y(2)
   *    3  31*y(2)   + hashcode_2 = y(3)
   *    n  31*y(n-1) + hashcode_n-1 = y(n)
   *
   * Each hashcode is a number and the binary equivalent is computed and
   * returned.
   * @return the computed hashcode
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public int hashCode() {
    int i, size = getGPPopulation().size();
    IGPProgram prog;
    int twopower = 1;
    // For empty genotype we want a special value different from other hashcode
    // implementations.
    // ------------------------------------------------------------------------
    int localHashCode = -573;
    for (i = 0; i < size; i++, twopower = 2 * twopower) {
      prog = getGPPopulation().getGPProgram(i);
      localHashCode = 31 * localHashCode + prog.hashCode();
    }
    return localHashCode;
  }

  /**
   * @param a_verbose true: output status information to console
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public void setVerboseOutput(boolean a_verbose) {
    m_verbose = a_verbose;
  }

  private IGPProgram cloneProgram(IGPProgram a_original) {
    IGPProgram validProgram = a_original;
    ICloneHandler cloner = getGPConfiguration().getJGAPFactory().
        getCloneHandlerFor(validProgram, null);
    if (cloner != null) {
      try {
        IGPProgram program = (IGPProgram) cloner.perform(
            validProgram, null, null);
        return program;
      } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return null;
      }
    }
    return null;
  }

  /**
   * Stores a Variable.
   *
   * @param a_var the Variable to store
   *
   * @author Klaus Meffert
   * @since 3.2
   */
  public void putVariable(Variable a_var) {
    m_variables.put(a_var.getName(), a_var);
  }

  /**
   * @param a_varName name of variable to retriebe
   * @return Variable instance or null, if not found
   *
   * @author Klaus Meffert
   * @since 3.2
   */
  public Variable getVariable(String a_varName) {
    return (Variable) m_variables.get(a_varName);
  }

  /**
   * Adds a GP program to this Genotype. Does nothing when given null.
   * The injection is actually executed in method create(..) of GPPopulation.
   *
   * @param a_toAdd the program to add
   *
   * @author Klaus Meffert
   * @since 3.2
   */
  public void addFittestProgram(final IGPProgram a_toAdd) {
    if (a_toAdd != null) {
      m_fittestToAdd = a_toAdd;
    }
  }

  /**
   * Fills up the population with random programs if necessary.
   *
   * @param a_num the number of programs to add
   * @throws InvalidConfigurationException
   *
   * @author Klaus Meffert
   * @since 3.2
   */
  public void fillPopulation(final int a_num)
      throws InvalidConfigurationException {
    IGPProgram sampleProg = getGPConfiguration().getPrototypeProgram();
    if (sampleProg == null) {
      /**@todo care about*/
    }
    Class sampleClass = sampleProg.getClass();
    IInitializer chromIniter = getGPConfiguration().getJGAPFactory().
        getInitializerFor(sampleProg, sampleClass);
    if (chromIniter == null) {
      throw new InvalidConfigurationException("No initializer found for class "
          + sampleClass);
    }
    try {
      for (int i = 0; i < a_num; i++) {
        /**@todo implement filling up population*/
//        getGPPopulation().addChromosome( (IChromosome) chromIniter.perform(sampleProg,
//            sampleClass, null));
      }
    } catch (Exception ex) {
      throw new IllegalStateException(ex);
    }
  }

//  /**
//   * Disabling a chromosome is equivalent to not declaring it. However, if you
//   * skip a declaration, indices will shift. With this method it is easier
//   * skipping a chromosome.
//   *
//   * @param a_index index of the chromosome to disable.
//   *
//   * @author Klaus Meffert
//   * @since 3.2.2
//   */
//  public void disableChromosome(int a_index) {
//    if (a_index < 0 || a_index >= disabledChromosomes.length) {
//      throw new IllegalArgumentException("Invalid index!");
//    }
//    disabledChromosomes[a_index] = true;
//  }
//
//  /**
//   *
//   * @param a_index index of the chromosome to check.
//   * @return true if chromosome disabled
//   *
//   * @author Klaus Meffert
//   * @since 3.2.2
//   */
//  public boolean isDisabledChromosome(int a_index) {
//    if (a_index < 0 || a_index >= disabledChromosomes.length) {
//      throw new IllegalArgumentException("Invalid index!");
//    }
//    return disabledChromosomes[a_index];
//  }

  public static void checkErroneousPop(GPPopulation pop, String s) {
    checkErroneousPop(pop, s, false);
  }

  public static void checkErroneousPop(GPPopulation a_pop, String a_s,
                                       boolean a_clearFitness) {
    if (a_pop == null) {
      return;
    }
    checkErroneousPop(a_pop, a_s, a_clearFitness,
                      a_pop.getGPConfiguration().isVerifyPrograms());
  }

  public static void checkErroneousPop(GPPopulation a_pop, String a_s,
                                       boolean a_clearFitness,
                                       boolean a_active) {
    if (a_pop == null) {
      return;
    }
    if (!a_active) {
      // Verification not activated!
      // ---------------------------
      return;
    }
    int popSize1 = a_pop.size();
    for (int i = 0; i < popSize1; i++) {
      IGPProgram a_prog = a_pop.getGPProgram(i);
      checkErroneousProg(a_prog, a_s, a_clearFitness, a_active);
    }
  }

  public static void checkErroneousProg(IGPProgram prog, String s) {
    checkErroneousProg(prog, s, false);
  }

  public static void checkErroneousProg(IGPProgram a_prog, String a_s,
                                        boolean a_clearFitness) {
    if (a_prog == null) {
      return;
    }
    checkErroneousProg(a_prog, a_s, a_clearFitness,
                       a_prog.getGPConfiguration().isVerifyPrograms());
  }

  public static void checkErroneousProg(IGPProgram a_prog, String s,
                                        boolean a_clearFitness,
                                        boolean a_active) {
    if (a_prog == null) {
      return;
    }
    if (!a_active) {
      // Verification not activated!
      // ---------------------------
      return;
    }
    // Has program already been verified?
    // ----------------------------------
    /**@todo impl. cache*/

    if (a_clearFitness) {
      // Reset fitness value.
      // --------------------
      a_prog.setFitnessValue(GPFitnessFunction.NO_FITNESS_VALUE);
    }
    try {
      a_prog.getFitnessValue();
    } catch (Throwable ex) {
      String msg = "Invalid program detected" + s + "!";
      LOGGER.fatal(msg);
      throw new RuntimeException(msg, ex);
    }
  }

  private void writeToFile(IGPProgram i1, IGPProgram i2, IGPProgram inew,
                           String header) {
    StringBuffer sb = new StringBuffer();
    try {
      sb.append(header);
      sb.append("First Program to cross over\n");
      sb.append(getProgramString(i1));
      sb.append("\nSecond Program to cross over\n");
      sb.append(getProgramString(i2));
      sb.append("\nResulting Program after cross over\n");
      sb.append(getProgramString(inew));
      String filename = DateKit.getNowAsString();
      File f = new File(filename);
      FileWriter fw = new FileWriter(f);
      fw.write(sb.toString());
      fw.close();
    } catch (IOException iex) {
      System.out.println(sb.toString());
      iex.printStackTrace();
    }
  }

  private StringBuffer getProgramString(IGPProgram i1) {
    int size = i1.size();
    int size2;
    ProgramChromosome chrom;
    CommandGene gene;
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < size; i++) {
      chrom = i1.getChromosome(i);
      result.append("Chromosome " + i + ", class " + chrom.getClass() + "\n");
      size2 = chrom.size();
      for (int j = 0; j < size2; j++) {
        gene = chrom.getGene(j);
        result.append("Gene " + j + ", class " + gene.getClass() +
                      ", toString: " + gene.toString() + " \n");
      }
    }
    return result;
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -