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

📄 mapgene.java

📁 一个开源的用java开发的遗传算法的封装好的工程
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * This file is part of JGAP.
 *
 * JGAP offers a dual license model containing the LGPL as well as the MPL.
 *
 * For licencing information please see the file license.txt included with JGAP
 * or have a look at the top of class org.jgap.Chromosome which representatively
 * includes the JGAP license policy applicable for any file delivered with JGAP.
 */
package org.jgap.impl;

import java.lang.reflect.*;
import java.util.*;
import org.jgap.*;

/**
 * ATTENTION: This class is preliminary and subject of future adaptations! Use
 * with care or wait for a more mature version we are working on.
 * <p>
 * Creates a gene instance in which individual alleles have both a label (key)
 * and a value with a distinct meaning. For example, IntegerGene only allows
 * for values having a continuous range, and does not have a function where it
 * is possible to specify setValue...
 * <p>This implementation does not support specifying a range of valid
 * integer values. Instead it is planned to provide a constraint checker plugin
 * later on. With this, the current implementation will stay unchanged and can
 * be as performant as possible without losing flexibility.</p>
 *
 * @author Johnathan Kool, Organisation: RSMAS, University of Miami
 * @author Klaus Meffert (adaptations)
 * @since 2.4
 */
public class MapGene
    extends BaseGene implements IPersistentRepresentation{
  /** String containing the CVS revision. Read out via reflection!*/
  private final static String CVS_REVISION = "$Revision: 1.21 $";

  /**
   * Container for valid alleles
   */
  private Map m_geneMap;

  /**
   * Represents the constant range of values supported by integers.
   */
  private Object m_value;

  /**
   * Represents the delimiter that is used to mark the allele map.
   */
  final static String ALLELEMAP_BEGIN_DELIMITER = "[";

  final static String ALLELEMAP_END_DELIMITER = "]";

  /**
   * Default constructor.<p>
   * Attention: The configuration used is the one set with the static method
   * Genotype.setConfiguration.
   * @throws InvalidConfigurationException
   *
   * @since 2.4
   */
  public MapGene()
      throws InvalidConfigurationException {
    this(Genotype.getStaticConfiguration());
  }

  /**
   * @param a_config the configuration to use
   * @throws InvalidConfigurationException
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public MapGene(final Configuration a_config)
      throws InvalidConfigurationException {
    super(a_config);
    m_geneMap = new HashMap();
  }

  /**
   * Constructor setting up valid alleles directly.
   * @param a_config the configuration to use
   * @param a_alleles the valid alleles of the gene
   * @throws InvalidConfigurationException
   *
   * @author Klaus Meffert
   * @since 2.4
   */
  public MapGene(final Configuration a_config, final Map a_alleles)
      throws InvalidConfigurationException {
    super(a_config);
    m_geneMap = new HashMap();
    addAlleles(a_alleles);
  }

  protected Gene newGeneInternal() {
    try {
      MapGene result = new MapGene(getConfiguration(), m_geneMap);
      // get m_value from original
      Object value = getAllele();
      result.setAllele(value);
      return result;
    }
    catch (InvalidConfigurationException iex) {
      throw new IllegalStateException(iex.getMessage());
    }
  }

  /**
   * Adds a potential allele value to the collection.
   *
   * @param a_key the key to be added
   * @param a_value the Integer value to be added
   * @since 2.4
   */
  public void addAllele(final Object a_key, final Object a_value) {
    m_geneMap.put(a_key, a_value);
  }

  /**
   * Adds a potential allele value to the collection.
   *
   * @param a_value the value to be added, also used as key
   *
   * @author Klaus Meffert
   * @since 2.4
   */
  public void addAllele(final Object a_value) {
    m_geneMap.put(a_value, a_value);
  }

  /**
   * Convenience method for addAllele (Object's that are Integer's)
   *
   * @param a_value the int value to be added, also used as key
   *
   * @author Klaus Meffert
   * @since 2.4
   */
  public void addAllele(final int a_value) {
    m_geneMap.put(new Integer(a_value), new Integer(a_value));
  }

  /**
   * Add a set of potential allele values to the collection
   *
   * @param a_alleles the set of alleles to be added
   *
   * @since 2.4
   */
  public void addAlleles(final Map a_alleles) {
    if (a_alleles == null) {
      throw new IllegalArgumentException("List of alleles may not be null!");
    }
    else {
      m_geneMap.putAll(a_alleles);
    }
  }

  /**
   * Removes a potential allele or set of alleles from the collection.
   *
   * @param a_key the unique value(s) of the object(s) to be removed
   *
   * @since 2.4
   */
  public void removeAlleles(final Object a_key) {
    m_geneMap.remove(a_key);
  }

  /**
   * @return the map of alleles
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public Map getAlleles() {
    return m_geneMap;
  }

  /**
   * Sets the allele value to be a random value using a defined random number
   * generator. If no valid alleles are defined, any allele is allowed. Then,
   * a new Integer with random value is set as random value. Override this
   * method if you want a different behaviour, such as a Double instead of the
   * Integer type.
   *
   * @param a_numberGenerator the random generator to use
   *
   * @author Klaus Meffert
   * @since 2.4
   */
  public void setToRandomValue(final RandomGenerator a_numberGenerator) {
    if (m_geneMap.isEmpty()) {
      m_value = new Integer(a_numberGenerator.nextInt());
    }
    else {
      m_value = m_geneMap.get(m_geneMap.keySet().toArray()[a_numberGenerator.
                              nextInt(m_geneMap.size())]);
    }
  }

  /**
   * See interface Gene for description of applyMutation.
   *
   * For this kind of gene, providing an index and a percentage of mutation
   * would have no significance because the individual allele forms are
   * independent of one another.  In mutating, they can only change from one
   * form to another. It may be possible to weight the likelihood of mutation
   * to different forms, but that is not implemented currently.
   *
   * @param a_index ignored here
   * @param a_percentage ignored here
   *
   * @author Klaus Meffert
   * @author Johnathan Kool
   * @since 2.4
   */
  public void applyMutation(final int a_index, final double a_percentage) {
    RandomGenerator rn;
    rn = getConfiguration().getRandomGenerator();
    setToRandomValue(rn);
  }

  /**
   * Sets the value and internal state of this Gene from the string
   * representation returned by a previous invocation of the
   * getPersistentRepresentation() method. This is an optional method but,
   * if not implemented, XML persistence and possibly other features will not
   * be available. An UnsupportedOperationException should be thrown if no
   * implementation is provided.
   *
   * @param a_representation the string representation retrieved from a prior
   * call to the getPersistentRepresentation() method.
   *
   * @throws UnsupportedOperationException to indicate that no implementation
   * is provided for this method
   * @throws UnsupportedRepresentationException if this Gene implementation
   * does not support the given string representation.
   *
   * @author Neil Rostan
   * @author Klaus Meffert
   * @since 2.4
   */
  public void setValueFromPersistentRepresentation(final String
      a_representation)
      throws UnsupportedRepresentationException {
    if (a_representation != null) {
      StringTokenizer tokenizer = new StringTokenizer(a_representation,
          PERSISTENT_FIELD_DELIMITER);
      // Make sure the representation contains the correct number of
      // fields. If not, throw an exception.
      // -----------------------------------------------------------
      if (tokenizer.countTokens() != 2) {
        throw new UnsupportedRepresentationException(
            "The format of the given persistent representation " +
            "is not recognized: it must contain two tokens.");
      }
      String valueRepresentation = tokenizer.nextToken();
      // First parse and set the representation of the value.
      // ----------------------------------------------------
      if (valueRepresentation.equals("null")) {
        m_value = null;
      }
      else {
        try {
          m_value = new Integer(Integer.parseInt(valueRepresentation));
        }
        catch (NumberFormatException e) {
          throw new UnsupportedRepresentationException(
              "The format of the given persistent representation " +
              "is not recognized: field 1 does not appear to be " +
              "an integer value.");
        }
      }
      // Parse gene map.
      // ---------------
      String s = tokenizer.nextToken();
      tokenizer = new StringTokenizer(s, ",");
      int lastWasOpening = 0;
      String key = null;
      String keyClass = null;
      String valueClass = null;
      while (tokenizer.hasMoreTokens()) {
        String element = tokenizer.nextToken(",");
        if (lastWasOpening == 1) {
          key = element.substring(0);
          lastWasOpening = 2;
        }
        else if (lastWasOpening == 2) {
          valueClass = element.substring(0);
          lastWasOpening = 3;
        }
        else if (lastWasOpening == 3) {
          if (element.endsWith(")")) {
            element = element.substring(0, element.length() - 1);
            try {
              Class keyType = Class.forName(keyClass);
              Constructor keyC = keyType.getConstructor(new Class[]{String.class});
              Object keyObject = keyC.newInstance(new Object[]{key});

⌨️ 快捷键说明

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