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

📄 compositegene.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.io.*;
import java.net.*;
import java.util.*;
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 (not CompositeGenes!) after
 * construction, an empty CompositeGene without genes makes no sense.
 * Beware that there are two equalities defined for a CompsoiteGene 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 "better"
 * 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 Gene {
  /** String containing the CVS revision. Read out via reflection!*/
  private final static String CVS_REVISION = "$Revision: 1.25 $";

  /**
   * This field separates gene class name from
   * the gene persistent representation string.
   * '*' does not work properly with URLEncoder, so I have changed it to '#'
   */
  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 genes;

  /**
   * Optional helper class for checking if a given allele value to be set
   * is valid. If not the allele value may not be set for the gene!
   *
   * @author Klaus Meffert
   * @since 2.0
   */
  private IGeneConstraintChecker m_geneAlleleChecker;

  /**
   * @author Klaus Meffert
   * @since 1.1
   */
  public CompositeGene() {
    this(null);
  }

  /**
   * Allows to specify which Gene implementation is allowed to be added to the
   * CompositeGene.
   *
   * @param a_geneTypeAllowed the class of Genes to be allowed to be added to
   * the CompositeGene.
   *
   * @author Klaus Meffert
   * @since 2.0
   */
  public CompositeGene(Gene a_geneTypeAllowed) {
    genes = new Vector();
    if (a_geneTypeAllowed != null) {
      m_geneTypeAllowed = a_geneTypeAllowed;
    }
  }

  public void addGene(Gene a_gene) {
    addGene(a_gene, false);
  }

  /**
   * 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 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(Gene a_gene, boolean strict) {
    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 (!strict) {
      containsGene = containsGeneByIdentity(a_gene);
    }
    else {
      containsGene = genes.contains(a_gene);
    }
    if (containsGene) {
      throw new IllegalArgumentException("The gene is already contained"
                                         + " in the CompositeGene!");
    }
    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 will not be used here intentionally
   * @param gene the gene to be removed
   * @return true: given gene found and removed
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public boolean removeGeneByIdentity(Gene gene) {
    int size = size();
    if (size < 1) {
      return false;
    }
    else {
      for (int i = 0; i < size; i++) {
        if (geneAt(i) == gene) {
          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 gene the gene to be removed
   * @return true: given gene found and removed
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public boolean removeGene(Gene gene) {
    return genes.remove(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;
    for (int i = 0; i < genes.size(); i++) {
      gene = (Gene) 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(RandomGenerator a_numberGenerator) {
    if (a_numberGenerator == null) {
      throw new IllegalArgumentException("Random generatoe must not be null!");
    }
    Gene gene;
    for (int i = 0; i < genes.size(); i++) {
      gene = (Gene) 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 */
        genes.clear();
        ArrayList 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 String
   * @param a_persistentRepresentation String
   * @throws Exception
   * @return Gene
   */
  protected Gene createGene(String a_geneClassName,
                            String a_persistentRepresentation)
      throws Exception {
    Class geneClass = Class.forName(a_geneClassName);
    Gene gene = (Gene) geneClass.newInstance();
    gene.setValueFromPersistentRepresentation(a_persistentRepresentation);
    return gene;
  }

  /**
   * See interface Gene for description
   * @return A 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 = 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
   * container
   *
   * @return the Boolean value of this Gene.
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public Object getAllele() {
    List alleles = new Vector();
    Gene gene;
    for (int i = 0; i < genes.size(); i++) {
      gene = (Gene) genes.get(i);
      alleles.add(gene.getAllele());
    }
    return alleles;
  }

  /**
   * Sets the value of the contained Genes to the new given value. This class
   * expects the value to be of a Vector type. Each element of the Vector
   * must conform with the type of the gene in the CompositeGene's container
   * at the corresponding position.
   *
   * @param a_newValue the new value of this Gene instance.
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public void setAllele(Object a_newValue) {
    if (! (a_newValue instanceof List)) {

⌨️ 快捷键说明

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