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

📄 compositegene.java

📁 JGAP是一种遗传算法和遗传规划的组成部分提供了一个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 licensing 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.util.*;
import java.lang.reflect.*;
import org.jgap.*;

/**
 * Ordered container for multiple genes
 * Has the same interface as a single gene and could be used accordingly.
 * Use the addGene(Gene) method to add single genes (possibly CompositeGenes)
 * after construction, an empty CompositeGene without genes makes no sense.
 * Beware that there are two equalities defined for a CompositeGene in respect
 * to its contained genes:
 * a) Two genes are (only) equal if they are identical
 * b) Two genes are (seen as) equal if their equals method returns true
 *
 * This influences several methods such as addGene. Notice that it is safer
 * to use addGene(a_gene, false) than addGene(a_gene, true) because the second
 * variant only allows to add genes not seen as equal to already added genes in
 * respect to their equals function. But: the equals function returns true for
 * two different DoubleGenes (e.g.) just after their creation. If no specific
 * (and hopefully different) allele is set for these DoubleGenes they are seen
 * as equal!
 *
 * @author Klaus Meffert
 * @author Audrius Meskauskas
 * @since 1.1
 */
public class CompositeGene
    extends BaseGene
    implements ICompositeGene, IPersistentRepresentation  {
  /** String containing the CVS revision. Read out via reflection!*/
  private final static String CVS_REVISION = "$Revision: 1.60 $";

  /**
   * This field separates gene class name from the gene persistent representation
   * string. '*' does not work properly with URLEncoder!
   */
  public final static String GENE_DELIMITER = "#";

  /**
   * Represents the heading delimiter that is used to separate genes in the
   * persistent representation of CompositeGene instances.
   */
  public final static String GENE_DELIMITER_HEADING = "<";

  /**
   * Represents the closing delimiter that is used to separate genes in the
   * persistent representation of CompositeGene instances.
   */
  public final static String GENE_DELIMITER_CLOSING = ">";

  private Gene m_geneTypeAllowed;

  /**
   * The genes contained in this CompositeGene
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  private List<Gene> m_genes;

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

  /**
   * @param a_config the configuration to use
   * @throws InvalidConfigurationException
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public CompositeGene(Configuration a_config)
      throws InvalidConfigurationException {
    this(a_config, null);
  }

  /**
   * Allows to specify which Gene implementation is allowed to be added to the
   * CompositeGene.
   *
   * @param a_config the configuration to use
   * @param a_geneTypeAllowed the class of Genes to be allowed to be added to
   * the CompositeGene
   *
   * @throws InvalidConfigurationException
   *
   * @author Klaus Meffert
   * @since 2.0
   */
  public CompositeGene(final Configuration a_config,
                       final Gene a_geneTypeAllowed)
      throws InvalidConfigurationException {
    super(a_config);
    m_genes = new Vector();
    if (a_geneTypeAllowed != null) {
      m_geneTypeAllowed = a_geneTypeAllowed;
    }
  }

  /**
   * Adds a gene to the CompositeGene.
   *
   * @param a_gene the gene to add
   */
  public void addGene(final Gene a_gene) {
    addGene(a_gene, false);
  }

  /**
   * @return the gene type allowed, or null if any type allowed
   *
   * @author Klaus Meffert
   * @since 2.4
   */
  public Gene getGeneTypeAllowed() {
    return m_geneTypeAllowed;
  }

  /**
   * Adds a gene to the CompositeGene's container. See comments in class
   * header for additional details about equality (concerning "strict" param.)
   *
   * @param a_gene the gene to be added
   * @param a_strict false: add the given gene except the gene itself already is
   * contained within the CompositeGene's container. true: add the gene if
   * there is no other gene being equal to the given gene in request to the
   * Gene's equals method
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public void addGene(final Gene a_gene, final boolean a_strict) {
    if (a_gene == null) {
      throw new IllegalArgumentException("Gene instance must not be null!");
    }
    if (m_geneTypeAllowed != null) {
      if (!a_gene.getClass().getName().equals(m_geneTypeAllowed.getClass().
                                              getName())) {
        throw new IllegalArgumentException("Adding a "
                                           + a_gene.getClass().getName()
                                           + " has been forbidden!");
      }
    }
    // Check if gene already exists.
    // -----------------------------
    boolean containsGene;
    if (!a_strict) {
      containsGene = containsGeneByIdentity(a_gene);
    }
    else {
      containsGene = m_genes.contains(a_gene);
    }
    if (containsGene) {
      throw new IllegalArgumentException("The gene is already contained"
                                         + " in the CompositeGene!");
    }
    m_genes.add(a_gene);
  }

  /**
   * Removes the given gene from the collection of genes. The gene is only
   * removed if an object of the same identity is contained. The equals
   * method is not used here intentionally.
   *
   * @param a_gene the gene to be removed
   * @return true: given gene found and removed
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public boolean removeGeneByIdentity(final Gene a_gene) {
    int size = size();
    if (size < 1) {
      return false;
    }
    else {
      for (int i = 0; i < size; i++) {
        if (geneAt(i) == a_gene) {
          m_genes.remove(i);
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Removes the given gene from the collection of genes. The gene is
   * removed if another gene exists that is equal to the given gene in respect
   * to the equals method of the gene.
   *
   * @param a_gene the gene to be removed
   * @return true: given gene found and removed
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public boolean removeGene(final Gene a_gene) {
    return m_genes.remove(a_gene);
  }

  /**
   * Executed by the genetic engine when this Gene instance is no
   * longer needed and should perform any necessary resource cleanup.
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public void cleanup() {
    Gene gene;
    int size = m_genes.size();
    for (int i = 0; i < size; i++) {
      gene = (Gene) m_genes.get(i);
      gene.cleanup();
    }
  }

  /**
   * See interface Gene for description.
   *
   * @param a_numberGenerator the random number generator that should be used
   * to create any random values. It's important to use this generator to
   * maintain the user's flexibility to configure the genetic engine to use the
   * random number generator of their choice
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public void setToRandomValue(final RandomGenerator a_numberGenerator) {
    if (a_numberGenerator == null) {
      throw new IllegalArgumentException("Random generatoe must not be null!");
    }
    Gene gene;
    int size = m_genes.size();
    for (int i = 0; i < size; i++) {
      gene = (Gene) m_genes.get(i);
      gene.setToRandomValue(a_numberGenerator);
    }
  }

  /**
   * See interface Gene for description.
   *
   * @param a_representation the string representation retrieved from a prior
   * call to the getPersistentRepresentation() method
   *
   * @throws UnsupportedRepresentationException
   *
   * @author Klaus Meffert
   * @author Audrius Meskauskas
   * @since 1.1
   */
  public void setValueFromPersistentRepresentation(String a_representation)
      throws UnsupportedRepresentationException {
    if (a_representation != null) {
      try {
        // Remove the old content.
        // -----------------------
        m_genes.clear();
        List r = split(a_representation);
        Iterator iter = r.iterator();
        StringTokenizer st;
        String clas;
        String representation;
        String g;
        Gene gene;
        while (iter.hasNext()) {
          g = decode( (String) iter.next());
          st = new StringTokenizer(g, GENE_DELIMITER);
          if (st.countTokens() != 2)
            throw new UnsupportedRepresentationException("In " + g + ", " +
                "expecting two tokens, separated by " + GENE_DELIMITER);
          clas = st.nextToken();
          representation = st.nextToken();
          gene = createGene(clas, representation);
          addGene(gene);
        }
      }
      catch (Exception ex) {
        throw new UnsupportedRepresentationException(ex.toString());
      }
    }
  }

  /**
   * Creates a new instance of gene.
   *
   * @param a_geneClassName name of the gene class
   * @param a_persistentRepresentation persistent representation of the gene to
   * create (could be obtained via getPersistentRepresentation)
   *
   * @return newly created gene
   * @throws Exception
   *
   * @author Klaus Meffert
   */
  protected Gene createGene(String a_geneClassName,
                            String a_persistentRepresentation)
      throws Exception {
    Class geneClass = Class.forName(a_geneClassName);
    Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class});
    Gene gene = (Gene) constr.newInstance(new Object[] {getConfiguration()});
    gene.setValueFromPersistentRepresentation(a_persistentRepresentation);
    return gene;
  }

  /**
   * See interface Gene for description.
   *
   * @return string representation of this Gene's current state
   * @throws UnsupportedOperationException
   *
   * @author Klaus Meffert
   * @author Audrius Meskauskas
   * @since 1.1
   */
  public String getPersistentRepresentation()
      throws UnsupportedOperationException {
    StringBuffer b = new StringBuffer();
    Iterator iter = m_genes.iterator();
    Gene gene;
    while (iter.hasNext()) {
      gene = (Gene) iter.next();
      b.append(GENE_DELIMITER_HEADING);
        b.append(encode(
            gene.getClass().getName() +
            GENE_DELIMITER +
            gene.getPersistentRepresentation()));
      b.append(GENE_DELIMITER_CLOSING);
    }
    return b.toString();
  }

  /**
   * Retrieves the value represented by this Gene. All values returned
   * by this class will be Vector instances. Each element of the Vector
   * represents the allele of the corresponding gene in the CompositeGene's

⌨️ 快捷键说明

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