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

📄 jgapclientgp.java

📁 JGAP是一种遗传算法和遗传规划的组成部分提供了一个Java框架。它提供了基本的遗传机制
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
   * 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
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void onError(Exception a_ex)
      throws Exception {
    // Do not handle any eror specifically.
    // ------------------------------------
    throw a_ex;
  }

  /**
   * Called in case of any unhandled error when trying to delete a request or
   * result.
   * Override in sub classes if needed.
   *
   * @param a_ex exception object expressing the error
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.4
   */
  protected void onDeleteError(Exception a_ex)
      throws Exception {
    // Do not handle any eror specifically.
    // ------------------------------------
    throw a_ex;
  }

  /**
   * Called in run() on error when receiving work results.
   * Override in sub classes if needed.
   *
   * @param a_workRequests for which to receive results
   * @param a_ex Exception occured
   * @throws Exception rethrow an unhandled exception!
   *
   * @author Klaus Meffert
   * @since 3.3.4
   */
  protected void onErrorReceiveWorkResults(JGAPRequestGP[] a_workRequests,
      Exception a_ex)
      throws Exception {
    // Do not handle any eror specifically.
    // ------------------------------------
    throw a_ex;
  }

  /**
   * Threaded: Splits work, sends it to workers and receives computed solutions.
   *
   * @author Klaus Meffert
   * @since 3.01
   */
  public void run() {
    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 {
        boolean showResultsError = false;
        do {
          boolean doBreak = false;
          try {
            onBeginOfRunning();
            if (!showResultsError) {
              // Show stats about best results for current application.
              // ------------------------------------------------------
              try {
                showCurrentResults();
              } catch (Exception ex) {
                log.error("Error during showing current results", ex);
                showResultsError = true;
              }
            }
            // Do deferred deletion of results.
            // --------------------------------
            Iterator<String> it = m_objects.getResults().keySet().iterator();
            boolean modified = false;
            try {
              while (it.hasNext()) {
                String key = it.next();
                String value = (String) m_objects.getResults().get(key);
                if (startsWith(value, "delete:")) {
                  log.info("Delete result (deferred), key: " + key);
                  try {
                    m_gcmed.removeMessage(key);
                  } catch (MalformedURLException mex) {
                    log.warn("Invalid key", mex);
                  } catch (Exception ex) {
                    onDeleteError(ex);
                    continue;
                  }
                  it.remove();
//                  m_objects.getResults().remove(key);
                  modified = true;
                }
                else {
                  if (startsWith(value, "delete")) {
                    it.remove();
                    modified = true;
                  }
                }
              }
            } finally {
              if (modified) {
                m_persister.save();
                modified = false;
              }
            }
            try {
              try {
                if (m_list) {
                  // List existing requests and results with extended information.
                  // -------------------------------------------------------------
                  listRequests();
                  listResults();
                }
                if (!m_receiveOnly && !m_no_evolution) {
                  // Initialize evolution.
                  // ---------------------
                  IClientEvolveStrategyGP clientEvolver = m_gridConfig.
                      getClientEvolveStrategy();
                  if (clientEvolver != null) {
                    clientEvolver.initialize(m_gcmed, getConfiguration(),
                        m_gridConfig.getClientFeedback());
                  }
                }
                if (!m_no_evolution) {
                  // Do the evolution.
                  // -----------------
                  beforeEvolve(m_gcmed);
                  evolve(m_gcmed, m_receiveOnly);
                  afterEvolve(m_gcmed);
                }
                doBreak = true;
              } catch (Exception ex) {
                log.error("Error: ", ex);
                throw ex;
              }
            } finally {
              Throwable t = null;
              try {
                try {
                  m_gcmed.stop();
                } catch (Throwable t1) {
                  t = t1;
                }
              } finally {
                log.info("Calling afterStopped");
                afterStopped(t);
                if (doBreak) {
                  break;
                }
              }
            }
          } catch (Exception ex1) {
            try {
              log.info("before onError");
              onError(ex1);
            } catch (Exception ex) {
              log.fatal("Unpredicted error", ex);
              m_gridConfig.getClientFeedback().error(
                  "Error while doing the work",
                  ex);
              try {
//              m_gcmed.disconnect();
              } catch (Exception ex2) {
                log.warn("Precautios disconnect failed.", ex2);
              }
              sleep(10000);
            }
          }
        } while (true);
        if (!m_endless) {
          break;
        }
        else {
          log.info("Starting again after a short break...");
          sleep(15000);
        }
      } while (true);
    } catch (InterruptedException iex) {
      // Thread interrupted.
      // -------------------
      log.fatal("Thread was interrupted", iex);
      try {
        m_gcmed.disconnect();
      } catch (Exception ex) {
        log.warn("Disconnect after interruption failed", ex);
      }
    } catch (Throwable t) {
      t.printStackTrace();
    }
    log.info("Stopping client");
  }

  protected JGAPRequestGP[] sendWorkRequests(int a_evolutionIndex,
      IClientEvolveStrategyGP evolver, IRequestSplitStrategyGP splitter,
      IClientFeedbackGP feedback)
      throws Exception {
    JGAPRequestGP[] workRequests = null;
    if (beforeGenerateWorkRequests()) {
      log.info("Beginning evolution cycle " + a_evolutionIndex);
      try {
//      m_clientEvolveStrategy.beforeGenerateWorkResults();
        workRequests = evolver.generateWorkRequests(m_workReq, splitter, null);
        feedback.setProgressMaximum(0);
        feedback.setProgressMaximum(workRequests.length - 1);
        for (int i = 0; i < workRequests.length; i++) {
          log.info("Setting up work request " + i);
          presetPopulation(workRequests[i]);
        }
        if (beforeSendWorkRequests(workRequests)) {
          /**@todo merge previous results in req.getPopulation()*/
          if (!m_no_comm) {
            try {
              sendWorkRequests(workRequests);
              return workRequests;
            } catch (Exception ex) {
              throw new WorkRequestsSendException(ex, workRequests);
            }
          }
          else {
            return workRequests;
          }
        }
        else {
          return null;
        }
      } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
      }
    }
    else {
      return null;
    }
  }

  protected void sendWorkRequests(JGAPRequestGP[] a_workList)
      throws Exception {
    // Send work requests.
    // -------------------
    for (int i = 0; i < a_workList.length; i++) {
      JGAPRequestGP req = a_workList[i];
      req.setRequestDate(DateKit.now());
      GPPopulation pop = req.getPopulation();
      if (pop == null || pop.isFirstEmpty()) {
        log.debug("Population to send to worker is empty!");
      }
      else {
        GPGenotype.checkErroneousPop(pop, " before sending to worker", true);
        /**@todo hier ist fehler aufgetreten!*/
      }
      m_gridConfig.getClientFeedback().sendingFragmentRequest(req);
      MessageContext context = new MessageContext(MODULE_CS,
          CONTEXT_WORK_REQUEST, CONTEXT_ID_EMPTY);
      context.setVersion(APP_VERSION);
      m_gcmed.send(new GridMessageWorkRequest(req), context, null);
      if (isInterrupted()) {
        break;
      }
    }
  }

  protected void receiveWorkResults(JGAPRequestGP[] workList)
      throws Exception {
    log.info("Receiving work results...");
    IClientFeedbackGP feedback = m_gridConfig.getClientFeedback();
    // Receive work results.
    // ---------------------
    int size;
    if (workList == null) {
      size = -1;
    }
    else {
      size = workList.length;
    }
    if (m_WANMode) {
      // First, get a list of all work results.
      // --------------------------------------
      MessageContext context = new MessageContext(MODULE_WS,
          /**@todo later: SC*/
          CONTEXT_WORK_RESULT, CONTEXT_ID_EMPTY);
      List results = m_gcmed.listResults(context, null, null);
      // Then, iterate over them and receive one after another.
      // ------------------------------------------------------
      if (results == null || results.size() < 1) {
        log.info("No earlier results found.");
      }
      else {
        int i = 0;
        int len = results.size();
        log.info(len + " results found.");
        if (len > getMaxFetchResults()) {
          len = getMaxFetchResults();
          log.info("Fetching only " + len + " results.");
        }
        /**@todo sort results according to post date, the oldest first*/
        for (Object resultStub : results) {
          if (i >= m_max_fetch_results) {
            break;
          }
          feedback.setProgressValue(i);
          JGAPResultGP result = receiveWorkResult(resultStub, feedback, false);
          if (result != null) {
            log.info(" Generic data: " + result.getGenericData());
            /**@todo config.params wie popsite, evol.anz dazu*/
            log.info(" Title: " + result.getTitle());
            IGPProgram best = result.getPopulation().determineFittestProgram();
            String key = result.getID();
            // Check if result already received, and if, skip it
            if (m_objects.getResults().get(key) != null) {
              log.info("Already received result detected, key: "+key);
              continue;
            }
            if (best == null) {
              log.info("Empty result received!");
            }
            m_objects.getResults().put(key, "received");
            // Work with the result.
            // ---------------------
            m_gridConfig.getClientEvolveStrategy().resultReceived(result);
            try {
              // Remove result from online store.
              // ---------------------------------
              try {
                log.info("Removing result from online store");
                if (false && result.getGenericData() != null &&
                    WANData.class.isAssignableFrom(result.getGenericData().
                    getClass())) {
                  WANData wanData = (WANData) result.getGenericData();
                  m_gcmed.removeMessage(wanData.getUri());
                }
                else {
                  m_gcmed.removeMessage(resultStub);
                }
              } catch (Exception ex) {
                log.warn("Deletion of result failed, deferring...", ex);
                key = getKeyFromObject(resultStub);
                if (key != null) {
                  log.info(" Key for later deletion: " + key);
                  m_objects.getResults().put(key, "delete:");
                }
                else {
                  log.info("Deferred deletion not possible: key unknown");
                }
              }
            } finally {
              m_persister.save();
            }
            i++;
            resultReceived(best);
            MasterInfo worker = result.getWorkerInfo();
            if (worker != null) {
              log.info(" Worker IP " + worker.m_IPAddress + ", host " +
                       worker.m_name);

⌨️ 快捷键说明

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