jgapclientgp.java

来自「jGAp 遗传算法 提不错的一款软件 最新的更新」· Java 代码 · 共 1,135 行 · 第 1/3 页

JAVA
1,135
字号
/*
 * 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.distr.grid.gp;

import java.io.*;
import java.util.*;

import org.apache.commons.cli.*;
import org.homedns.dade.jcgrid.client.*;
import org.homedns.dade.jcgrid.cmd.*;
import org.homedns.dade.jcgrid.message.*;
import org.jgap.*;
import org.jgap.distr.*;
import org.jgap.distr.grid.*;
import org.jgap.distr.grid.common.*;
import org.jgap.distr.grid.util.*;
import org.jgap.gp.*;
import org.jgap.gp.impl.*;
import org.jgap.util.*;

import com.thoughtworks.xstream.*;

/**
 * A client defines work for the grid and sends it to the JGAPServer.
 * Use this class as base class for your grid client implementations.
 *
 * @author Klaus Meffert
 * @since 3.2
 */
public class JGAPClientGP
    extends Thread {
  /**@todo in dateiname requester/worker kodieren*/
  /**@todo small, medium, large work requests*/
  /**@todo re-evaluate each result on behalf of another worker*/
  /**@todo versionsnummer in filename rein, mit der file erzeugt*/
  /**@todo remove old requests from online store auotmatically*/
  /** String containing the CVS revision. Read out via reflection!*/
  private final static String CVS_REVISION = "$Revision: 1.11 $";

  public static final String MODULE_CS = "CS";

  public static final String CLIENT_DATABASE = "clientdb0.jgap";

  /**@todo das ist nicht module, sondern sender-receiver*/

  public static final String MODULE_SC = "SC";

  public static final String MODULE_SW = "SW";

  public static final String MODULE_WS = "WS";

  public static final String MODULE_ANY = "*";

  public static final String CONTEXT_WORK_REQUEST = "WREQ";

  public static final String CONTEXT_WORK_RESULT = "WRES";

  public static final String CONTEXT_ANY = "W*";

  public static final String CONTEXT_ID_EMPTY = "0";

  public static final String CONTEXT_ID_ANY = "*";

  public static final int TIMEOUT_SECONDS = 20;

  public static final int WAITTIME_SECONDS = 5;

//  private transient Logger log = Logger.getLogger(getClass());
  private static transient org.apache.log4j.Logger log
      = org.apache.log4j.Logger.getLogger(JGAPClientGP.class);

  protected GridNodeClientConfig m_gridconfig;

  protected JGAPRequestGP m_workReq;

  private IGridClientMediator m_gcmed;

  private IGridConfigurationGP m_gridConfig;

  /**
   * Is the client operating in a WAN or in a LAN?
   * TRUE:  WAN --> Do not use JCGrid architecture
   * FALSE: LAN --> Do use JCGrid architecture
   */
  private boolean m_WANMode;

  /**
   * Only received results or send requests beforehand?
   */
  private boolean m_receiveOnly;

  private boolean m_list;

  private String m_workDir;

  private String m_runID;

  private boolean m_endless;

  private ClientStatus m_objects;

  private PersistableObject m_persister;

  private int m_requestIdx;

  private boolean m_no_comm;

  private boolean m_no_evolution;

  public JGAPClientGP(GridNodeClientConfig a_gridconfig,
                      String a_clientClassName,
                      boolean a_WANMode,
                      boolean a_receiveOnly, boolean a_list, boolean a_no_comm,
                      boolean a_no_evolution, boolean a_endless)
      throws Exception {
    this(null, a_gridconfig, a_clientClassName, a_WANMode, a_receiveOnly,
         a_list, a_no_comm, a_no_evolution, a_endless);
    m_gcmed = new DummyGridClientMediator(m_gridconfig);
  }

  public JGAPClientGP(IGridClientMediator a_gcmed,
                      GridNodeClientConfig a_gridconfig,
                      String a_clientClassName, boolean a_WANMode,
                      boolean a_receiveOnly, boolean a_list, boolean a_no_comm,
                      boolean a_no_evolution, boolean a_endless)
      throws Exception {
    m_runID = getRunID();
    log.info("ID of this run: " + m_runID);
    if (a_clientClassName == null || a_clientClassName.length() < 1) {
      throw new IllegalArgumentException(
          "Please specify a class name of the configuration!");
    }
    m_WANMode = a_WANMode;
    m_receiveOnly = a_receiveOnly;
    if (m_receiveOnly) {
      log.info("Only receive results");
    }
    m_list = a_list;
    if (m_list) {
      log.info("List requests and results");
    }
    m_endless = a_endless;
    if (m_endless) {
      log.info("Endless run");
    }
    m_no_comm = a_no_comm;
    if (m_no_comm) {
      log.info("Don't send or receive anything");
    }
    m_no_evolution = a_no_evolution;
    if (m_no_evolution) {
      log.info("Don't execute genetic evolution");
    }
    m_gridconfig = a_gridconfig;
    Class client = Class.forName(a_clientClassName);
    m_gridConfig = (IGridConfigurationGP) client.getConstructor(new
        Class[] {}).newInstance(new Object[] {});
    m_gridConfig.initialize(m_gridconfig);
    if (m_gridConfig.getClientFeedback() == null) {
      m_gridConfig.setClientFeedback(new NullClientFeedbackGP());
    }
    // Setup work request.
    // -------------------
    JGAPRequestGP req = new JGAPRequestGP(m_gridconfig.getSessionName(),
        m_runID + "_" + m_requestIdx,
        0, m_gridConfig);
    m_requestIdx++;
    req.setWorkerReturnStrategy(m_gridConfig.getWorkerReturnStrategy());
    req.setGenotypeInitializer(m_gridConfig.getGenotypeInitializer());
    req.setEvolveStrategy(m_gridConfig.getWorkerEvolveStrategy());
    MasterInfo requester = new MasterInfo(true);
    req.setRequesterInfo(requester);
    req.setRequestDate(DateKit.now());
    // If evolution takes place on client only:
    // ----------------------------------------
//    req.setEvolveStrategy(null);
    //
    setWorkRequest(req);
    m_gcmed = a_gcmed;
    init();
  }

  private void init()
      throws Exception {
    String workDir = FileKit.getCurrentDir() + "/work/" + "storage";
    workDir = FileKit.getConformPath(workDir);
    // Try to load previous object information.
    // ----------------------------------------
    File f = new File(workDir, CLIENT_DATABASE);
    m_persister = new PersistableObject(f);
    m_objects = (ClientStatus) m_persister.load();
    if (m_objects == null) {
      m_objects = new ClientStatus();
      m_persister.setObject(m_objects);
    }
  }

  /**
   * @return the most possibly unique ID of a single program execution
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected String getRunID() {
    if (m_runID == null) {
      return "RJGrid" + DateKit.getNowAsString();
    }
    else {
      return m_runID;
    }
  }

  public void setWorkRequest(JGAPRequestGP a_request) {
    m_workReq = a_request;
  }

  /**
   * Called at start of run().
   * Override in sub classes if needed.
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void onBeginOfRunning()
      throws Exception {
  }

  /**
   * Called in run() before sending work requests.
   * Override in sub classes if needed.
   *
   * @param a_workRequests work requests pending to be sent
   *
   * @return true: do send work requests, false: don't send any work request
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected boolean beforeSendWorkRequests(JGAPRequestGP[] a_workRequests)
      throws Exception {
    return true;
  }

  /**
   * Called in run() before generating work requests for sending.
   * Override in sub classes if needed.
   *
   * @return true: do generate work requests, false: don't generate any work request
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected boolean beforeGenerateWorkRequests()
      throws Exception {
    return true;
  }

  /**
   * Called in run() after sending work requests successfully.
   * Override in sub classes if needed.
   *
   * @param a_workRequests the sent requests
   * @return true: process further, false: stop processing the rest
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected boolean afterSendWorkRequests(JGAPRequestGP[] a_workRequests)
      throws Exception {
    return true;
  }

  protected void errorOnSendWorkRequests(Throwable uex,
      JGAPRequestGP[] a_workRequests)
      throws Exception {
  }

  /**
   * Called in run() before one evolution step is executed.
   * Override in sub classes if needed.
   *
   * @param a_gcmed the GridClient mediator
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void beforeEvolve(IGridClientMediator a_gcmed)
      throws Exception {
  }

  /**
   * Called in run() after one evolution step is executed.
   * Override in sub classes if needed.
   *
   * @param a_gcmed the GridClient mediator
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void afterEvolve(IGridClientMediator a_gcmed)
      throws Exception {
  }

  /**
   * Called after stopping the client in run().
   * Override in sub classes if needed.
   *
   * @param a_t null if no error occured on stopping, otherwise exception object
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void afterStopped(Throwable a_t)
      throws Exception {
  }

  /**
   * Called in run() in case of any unhandled error.
   * Override in sub classes if needed.
   *
   * @param a_ex exception object expressing the error
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void onError(Exception a_ex) {
  }

  /**
   * Threaded: Splits work, sends it to workers and receives computed solutions.
   *
   * @author Klaus Meffert
   * @since 3.01
   */
  public void run() {
    int errorConnect = 0;
    try {
      try {
        // Check for updates.
        // ------------------
        String libDir = "D:\\jgap\robocode\\rjgrid\\lib\\";
//        checkForUpdates("http://www.klaus-meffert.de/", libDir, m_workDir);
      } catch (Exception ex) {
        log.error("Check for updates failed", ex);
      }
      do {
        do {
          try {
            onBeginOfRunning();
            // Show stats about best results for current application.
            // ------------------------------------------------------
            showCurrentResults();
            // Do deferred deletion of results.
            // --------------------------------
            Iterator<String> it = m_objects.getResults().keySet().iterator();
            while (it.hasNext()) {
              String key = it.next();
              String value = (String) m_objects.getResults().get(key);
              if ("delete".equals(value)) {

⌨️ 快捷键说明

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