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

📄 commandgene.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.gp;

import java.io.*;

import org.apache.commons.lang.builder.*;
import org.jgap.*;
import org.jgap.gp.impl.*;

/**
 * Abstract base class for all GP commands.
 *
 * A CommandGene represents a node within a GP program. A node either is a
 * terminal (like a constant), or a function (having input parameters).
 *
 * A CommandGene can hold additional CommandGene's, it acts sort of like a
 * * Composite (also see CompositeGene for a comparable concept, although for a
 * GA).
 *
 * @author Klaus Meffert
 * @since 3.0
 */
public abstract class CommandGene
    implements Comparable, Serializable {
  /** String containing the CVS revision. Read out via reflection!*/
  private final static String CVS_REVISION = "$Revision: 1.36 $";

  /**
   * Represents the delimiter that is used to separate fields in the
   * persistent representation.
   */
  final static String PERSISTENT_FIELD_DELIMITER = ":";

  final static String EXTENDED_INFO_DELIMITER = "~";

  /**
   * Delta, useful for comparing doubles and floats.
   */
  public static final double DELTA = 0.0000001;

  public final static Class BooleanClass = Boolean.class;

  public final static Class IntegerClass = Integer.class;

  public final static Class LongClass = Long.class;

  public final static Class FloatClass = Float.class;

  public final static Class DoubleClass = Double.class;

  public final static Class VoidClass = Void.class;

  public final static Class CharacterClass = Character.class;

  public enum COMMAND_TYPE {
    COMMAND_TYPE_UNDEFINED(0),
    COMMAND_TYPE_LOOP(8),
    COMMAND_TYPE_CONDITIONAL(16),
    COMMAND_TYPE_OPERATION(32),
    COMMAND_TYPE_MATH_OPERATION(33),
    COMMAND_TYPE_DECLARATION(64),
    COMMAND_TYPE_ASSIGNMENT(128),
    COMMAND_TYPE_ANALYSIS(256),
    COMMAND_TYPE_EXECUTION(512);

    private int m_value;

    public int intValue() {
      return m_value;
    }

    COMMAND_TYPE(int a_value) {
      m_value = a_value;
    }
  }
  private GPConfiguration m_configuration;

  /**
   * Should isValid() be called? True = no!
   */
  private boolean m_noValidation;

  /**
   * The return type of this node.
   */
  private Class m_returnType;

  /**
   * The arity of this node. Arity is the number of children of the node.
   * An arity if zero means: there are no children.
   * A terminal has an arity of zero.
   */
  private int m_arity;

  private int m_arityMin;

  private int m_arityMax;

  private boolean m_integerType;

  private boolean m_floatType;

  /** Energy of a gene, see RFE 1102206*/
  private double m_energy;

  /**
   * Application-specific data that is attached to the Gene. This data may
   * assist the application in labelling this Gene.
   * JGAP ignores the data, aside from allowing it to be set and
   * retrieved and considering it in clone and compareTo.
   *
   * @since 3.0
   */
  private Object m_applicationData;

  /**
   * Method compareTo and equals: Should we also consider the application data
   * when comparing? Default is "false" as "true" means a Gene's losing its
   * identity when application data is set differently!
   *
   * @since 3.0
   */
  private boolean m_compareAppData;

  private int m_subReturnType;

  private int[] m_subChildTypes;

  public int nodeIndex;

  /**
   * Initializations, called from each Constructor.
   */
  protected void init() {
  }

  /**
   * Default constructor, only for dynamic instantiation.
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.4
   */
  public CommandGene()
      throws Exception {
  }

  /**
   *
   * @param a_conf the configuration to use
   * @param a_arity the number of children of the node
   * @param a_returnType type of the return value of the node
   * @throws InvalidConfigurationException
   */
  public CommandGene(final GPConfiguration a_conf, final int a_arity,
                     final Class a_returnType)
      throws InvalidConfigurationException {
    if (a_conf == null) {
      throw new InvalidConfigurationException("Configuration must not be null!");
    }
    m_configuration = a_conf;
    init();
    m_arity = a_arity;
    m_returnType = a_returnType;
    if (a_returnType == Integer.class
        || a_returnType == Long.class) {
      m_integerType = true;
    }
    else if (a_returnType == Double.class
             || a_returnType == Float.class) {
      m_floatType = true;
    }
  }

  /**
   * Allows specifying a sub return type and sub child types.
   *
   * @param a_conf the configuration to use
   * @param a_arity the number of children of the node
   * @param a_returnType type of the return value of the node
   * @param a_subReturnType sub type of the return type, optional usage
   * @param a_childSubTypes sub types of the childs, optional usage
   * @throws InvalidConfigurationException
   *
   * @author Klaus Meffert
   * @since 3.2
   */
  public CommandGene(final GPConfiguration a_conf, final int a_arity,
                     final Class a_returnType, final int a_subReturnType,
                     final int[] a_childSubTypes)
      throws InvalidConfigurationException {
    this(a_conf, a_arity, a_returnType);
    if (a_childSubTypes != null) {
      boolean specialCase = false;
      // Special case from convenient construction.
      // ------------------------------------------
      if (a_childSubTypes.length == 1) {
        if (a_childSubTypes[0] == 0) {
          m_subChildTypes = null;
          specialCase = true;
        }
      }
      if (!specialCase) {
        if (a_childSubTypes.length != a_arity) {
          throw new IllegalArgumentException(
              "Length of child sub types must equal"
              + " the given arity (or set the former to null)");
        }
      }
      else {
        m_subChildTypes = a_childSubTypes;
      }
    }
    else {
      m_subChildTypes = a_childSubTypes;
    }
    m_subReturnType = a_subReturnType;
  }

  /**
   * Allows specifying a sub return type.
   *
   * @param a_conf the configuration to use
   * @param a_arity the number of children of the node
   * @param a_returnType type of the return value of the node
   * @param a_subReturnType sub type of the return type, optional usage
   * @throws InvalidConfigurationException
   *
   * @author Klaus Meffert
   * @since 3.2
   */
  public CommandGene(final GPConfiguration a_conf, final int a_arity,
                     final Class a_returnType, final int a_subReturnType)
      throws InvalidConfigurationException {
    this(a_conf, a_arity, a_returnType, a_subReturnType, null);
  }

  /**
   * Command with one child: Allows specifying a sub return type and a sub child
   * type. Convenience version of the called constructor.
   *
   * @param a_conf the configuration to use
   * @param a_arity the number of children of the node
   * @param a_returnType type of the return value of the node
   * @param a_subReturnType sub type of the return type, optional usage
   * @param a_childSubType sub type of a child, optional usage
   * @throws InvalidConfigurationException
   *
   * @author Klaus Meffert
   * @since 3.2
   */
  public CommandGene(final GPConfiguration a_conf, final int a_arity,
                     final Class a_returnType, final int a_subReturnType,
                     final int a_childSubType)
      throws InvalidConfigurationException {
    this(a_conf, a_arity, a_returnType, a_subReturnType,
         new int[] {a_childSubType});
  }

  public void setAllele(Object a_newValue) {
    throw new java.lang.UnsupportedOperationException(
        "Method setAllele() not used.");
  }

  public Object getAllele() {
    return null;
  }

  public void setToRandomValue(RandomGenerator a_numberGenerator) {
    // Do nothing here by default.
    // ---------------------------
  }

  public void cleanup() {
    // Do nothing here by default.
    // ---------------------------
  }

  public int size() {
    return m_arity;
  }

  /**
   * Arity of the command. Override if necessary.
   * The arity is the number of children a node has.
   *
   * @param a_indvividual the invididual the command's arity may depend on (in
   * most cases the arity will not depend on the individual)
   * @return arity of the command
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public int getArity(IGPProgram a_indvividual) {
    return m_arity;
  }

  /**
   * Should only be used by class CommandDynamicArity or a similar class.
   *
   * @param a_arity the arity to set, overrides the current arity.
   *
   * @author Klaus Meffert
   * @since 3.4
   */
  protected void setArity(int a_arity) {
    m_arity = a_arity;
  }

  /**
   * Adaptation of the arity so that it represents a value within the interval
   * [m_arityMin, m_arityMax].
   *
   * Override if necessary. See CommandDynamicArity for an implementation.
   *
   * @author Klaus Meffert
   * @since 3.4
   */
  public void dynamizeArity() {
    // Nothing done here by default.
    // -----------------------------
  }

  /**
   * Should only be used by class CommandDynamicArity or a similar class.
   * @param a_arityMin the minimal arity possible
   *
   * @author Klaus Meffert
   * @since 3.4
   */
  protected void setArityMin(int a_arityMin) {
    m_arityMin = a_arityMin;
  }

  /**
   * Should only be used by class CommandDynamicArity or a similar class.
   * @param a_arityMax the maximal arity possible
   *
   * @author Klaus Meffert
   * @since 3.4
   */
  protected void setArityMax(int a_arityMax) {
    m_arityMax = a_arityMax;
  }

  protected int getArityMin() {
    return m_arityMin;
  }

  protected int getArityMax() {
    return m_arityMax;
  }

  /**
   * The compareTo-method. Considers application data when the configuration
   * asks for this.
   *
   * @param a_other the other object to compare
   * @return -1, 0, 1
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public int compareTo(Object a_other) {
    if (a_other == null) {
      return 1;
    }
    CommandGene other = (CommandGene) a_other;
    if (getClass() != other.getClass()) {
      /**@todo do it more precisely*/
      return -1;
    }
    else {
      CompareToBuilder comparator = new CompareToBuilder();
      comparator.append(size(), other.size())
          .append(m_subChildTypes, other.m_subChildTypes)
          .append(m_subReturnType, other.m_subReturnType);
      if (m_compareAppData) {
        comparator.append(m_applicationData, other.m_applicationData);
      }
      return comparator.toComparison();
    }
  }

  /**
   * The equals-method. Considers application data when the configuration
   * asks for this.
   *
   * @param a_other the other object to compare
   * @return true if the objects are seen as equal
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public boolean equals(Object a_other) {
    if (a_other == null) {
      return false;
    }
    try {
      CommandGene other = (CommandGene) a_other;
      EqualsBuilder equals = new EqualsBuilder();
      equals.append(size(), other.size())
          .append(m_subChildTypes, other.m_subChildTypes)
          .append(m_subReturnType, other.m_subReturnType)
          .append(m_returnType, other.m_returnType);
      if (m_compareAppData) {
        equals.append(m_applicationData, other.m_applicationData);
      }
      return equals.isEquals();
    } catch (ClassCastException cex) {
      return false;
    }
  }
  /**
   * @return the string representation of the command. Especially usefull to
   * output a resulting formula in human-readable form.
   */
  public abstract String toString();

  /**
   * Executes this node without knowing its return type.
   *
   * @param c the current Chromosome which is executing
   * @param n the index of the Function in the Chromosome's Function array which
   * is executing
   * @param args the arguments to the current Chromosome which is executing
   * @return the object which wraps the return value of this node, or null
   * if the return type is null or unknown
   * @throws UnsupportedOperationException if the type of this node is not
   * boolean
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public Object execute(ProgramChromosome c, int n, Object[] args) {
    if (m_returnType == BooleanClass) {
      return new Boolean(execute_boolean(c, n, args));
    }
    if (m_returnType == IntegerClass) {
      return new Integer(execute_int(c, n, args));
    }
    if (m_returnType == LongClass) {
      return new Long(execute_long(c, n, args));
    }
    if (m_returnType == FloatClass) {
      return new Float(execute_float(c, n, args));
    }
    if (m_returnType == DoubleClass) {
      return new Double(execute_double(c, n, args));
    }
    if (m_returnType == VoidClass) {
      execute_void(c, n, args);
    }
    else {
      return execute_object(c, n, args);
    }
    return null;
  }

  /**
   * @return the return type of this node
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public Class getReturnType() {
    return m_returnType;
  }

  /**
   * Sets the return type of this node.
   *
   * @param a_type the type to set the return type to
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public void setReturnType(Class a_type) {
    m_returnType = a_type;
  }

  /**
   * Executes this node as a boolean. Override to implement.
   *
   * @param c ignored here
   * @param n ignored here
   * @param args ignored here
   * @return nothing but exception
   * @throws UnsupportedOperationException
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public boolean execute_boolean(ProgramChromosome c, int n, Object[] args) {
    throw new UnsupportedOperationException(getName() +
        " cannot return boolean");
  }

  /**
   * Executes this node, returning nothing. Override to implement.
   *
   * @param c ignored here
   * @param n ignored here
   * @param args ignored here
   * @throws UnsupportedOperationException
   *
   * @author Klaus Meffert
   * @since 3.0
   */
  public void execute_void(ProgramChromosome c, int n, Object[] args) {
    throw new UnsupportedOperationException(getName() +
        " cannot return void");
  }

⌨️ 快捷键说明

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