jgapclientgp.java

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

JAVA
1,135
字号
      a_gcmed.disconnect();
    } catch (Exception ex) {
      log.error("Disconnecting from server failed!", ex);
    }
    m_gridConfig.getClientFeedback().endWork();
  }

  public void start() {
    try {
      m_gridConfig.validate();
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
    super.start();
  }

  public GPConfiguration getConfiguration() {
    return m_gridConfig.getConfiguration();
  }

  public IGridClientMediator getGridClientMediator() {
    return m_gcmed;
  }

  protected IGridConfigurationGP getGridConfigurationGP() {
    return m_gridConfig;
  }

  /**
   * Writes an object to a local file.
   *
   * @param a_obj the object to persist
   * @param a_dir directory to write the file to
   * @param a_filename name of the file to create
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  public void writeToFile(Object a_obj, String a_dir, String a_filename)
      throws Exception {
    XStream xstream = new XStream();
    File f = new File(a_dir, a_filename);
    FileOutputStream fos = new FileOutputStream(f);
    xstream.toXML(a_obj, fos);
    fos.close();
  }

  public void setWorkDirectory(String a_workDir)
      throws IOException {
    m_workDir = a_workDir;
    FileKit.createDirectory(m_workDir);
    log.info("Work dir: " + m_workDir);
  }

  public String getWorkdirectory() {
    return m_workDir;
  }

  protected void checkForUpdates(String a_URL, String a_libDir,
                                 String a_workDir)
      throws Exception {
    GridKit.updateModuleLibrary(a_URL, "rjgrid", a_libDir, a_workDir);
  }

  /**
   * Override in sub classes: list available requests
   */
  protected void listRequests() {
  }

  /**
   * Override in sub classes: list available results
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void listResults() {
  }

  /**
   * @return false: normal mode, true: do not communicate with the server
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  public boolean isNoCommunication() {
    return m_no_comm;
  }

  /**
   * Starts a client (first parameter: name of specific setup class).
   *
   * @param args String[]
   *
   * @author Klaus Meffert
   * @since 3.01
   */
  public static void main(String[] args) {
    try {
      // Setup logging.
      // --------------
      MainCmd.setUpLog4J("client", true);
      // Command line options.
      // ---------------------
      GridNodeClientConfig config = new GridNodeClientConfig();
      Options options = makeOptions();
      options.addOption("l", true, "LAN or WAN");
//      options.addOption("receive_only", false,
//                        "Only receive results, don't send requests");
//      options.addOption("list", false,
//                        "List requests and results");
//      options.addOption("no_comm", false,
//                        "Don't receive any results, don't send requests");
//      options.addOption("no_evolution", false,
//                        "Don't perform genetic evolution");
//      options.addOption("help", false,
//                        "Display all available options");
      CommandLine cmd = MainCmd.parseCommonOptions(options, config, args);
      printHelp(cmd, options);
      String networkMode = cmd.getOptionValue("l", "LAN");
      boolean inWAN;
      if (networkMode != null && networkMode.equals("LAN")) {
        inWAN = false;
      }
      else {
        inWAN = true;
      }
      if (!cmd.hasOption("config")) {
        System.out.println(
            "Please provide a name of the grid configuration class to use");
        System.out.println("An example class would be "
                           +
                           "examples.grid.fitnessDistributed.GridConfiguration");
        System.exit(1);
      }
//      if (args.length < 2) {
//        System.out.println(
//            "Please provide an application name of the grid (textual identifier");
//        System.exit(1);
//      }
      String clientClassName = cmd.getOptionValue("config");
      boolean receiveOnly = cmd.hasOption("receive_only");
      boolean list = cmd.hasOption("list");
      boolean noComm = cmd.hasOption("no_comm");
      boolean noEvolution = cmd.hasOption("no_evolution");
      boolean endless = cmd.hasOption("endless");
      // Setup and start client.
      // -----------------------
      JGAPClientGP client = new JGAPClientGP(config, clientClassName, inWAN,
          receiveOnly, list, noComm, noEvolution, endless);
      // Start the threaded process.
      // ---------------------------
      client.start();
      client.join();
    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(1);
    }
  }

  protected static void printHelp(CommandLine cmd, Options options) {
    if (cmd.hasOption("help")) {
      System.out.println("");
      System.out.println(" Command line options:");
      System.out.println(" ---------------------\n");
//      Option[] opts = options.
      for (Object opt0 : options.getOptions()) {
        Option opt = (Option) opt0;
        String s = opt.getOpt();
        s = StringKit.fill(s, 20, ' ');
        System.out.println(" " + s + " - " + opt.getDescription());
      }
      System.exit(0);
    }
  }

  protected static Options makeOptions() {
    Options options = new Options();
    options.addOption("no_comm", false,
                      "Don't receive any results, don't send requests");
    options.addOption("no_evolution", false,
                      "Don't perform genetic evolution");
    options.addOption("receive_only", false,
                      "Only receive results, don't send requests");
    options.addOption("endless", false, "Run endlessly");
    options.addOption("config", true, "Grid configuration's class name");
    options.addOption("list", false,
                      "List requests and results");
    options.addOption("help", false,
                      "Display all available options");
    return options;
  }

  protected void removeEntries(Map a_cachedKeys, Map a_foundKeys) {
    Iterator it = a_cachedKeys.keySet().iterator();
    while (it.hasNext()) {
      Object key = it.next();
      if (!a_foundKeys.containsKey(key)) {
        it.remove();
      }
    }
  }

  protected String getKeyFromObject(Object a_obj) {
    return null;
  }

  /**
   * New results has been received. Care that the best of them are stored
   * in case it is a top 3 result.
   *
   * @param a_pop the fittest results received for a work request
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void resultReceived(GPPopulation a_pop)
      throws Exception {
    for (IGPProgram prog : a_pop.getGPPrograms()) {
      if (prog != null) {
        resultReceived(prog);
      }
    }
  }

  /**
   * A new result has been received. Care that it is stored in case it is a top
   * 3 result.
   *
   * @param a_fittest the fittest result received for a work request
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void resultReceived(IGPProgram a_fittest)
      throws Exception {
    /**@todo jeden Worker einer von n (rein logischen) Gruppen zuteilen.
     * Pro logischer Gruppe top n Ergebnisse halten
     */
    try {
      Map<String, List> topAll = m_objects.getTopResults();
      String appid = m_gridConfig.getContext().getAppId();
      List<IGPProgram> topApp = topAll.get(appid);
      if (topApp == null) {
        topApp = new Vector();
        topAll.put(appid, topApp);
      }
      int fitter = 0;
      Iterator<IGPProgram> it = topApp.iterator();
      Object worstEntry = null;
      double worstFitness = -1;
      String norm = a_fittest.toStringNorm(0);
      while (it.hasNext()) {
        IGPProgram prog = (IGPProgram) it.next();
        // Don't allow identical results.
        // ------------------------------
        if (prog.toStringNorm(0).equals(norm)) {
          fitter = 100;
          break;
        }
        double fitness = prog.getFitnessValue();
        if (Math.abs(fitness - a_fittest.getFitnessValue()) < 0.001) {
          fitter = 100;
          break;
        }
        else if (fitness >= a_fittest.getFitnessValue()) {
          fitter++;
        }
        else {
          // Determine the worst entry for later replacement.
          // ------------------------------------------------
          if (worstEntry == null ||
              getConfiguration().getGPFitnessEvaluator().
              isFitter(worstFitness, fitness)) {
            worstEntry = prog;
            worstFitness = fitness;
          }
        }
      }
      if (fitter < 3) { /**@todo make configurable*/
        // Remove worst result yet and add new fit result.
        // -----------------------------------------------
        topApp.remove(worstEntry);
        topApp.add(a_fittest);
        log.info("Added fit program, fitness: " +
                 NumberKit.niceDecimalNumber(a_fittest.getFitnessValue(), 2));
      }
      else {
        log.info("Result not better than top results received");
      }
      m_persister.save();
    } catch (Exception ex) {
      ex.printStackTrace();
      throw ex;
    }
  }

  /**
   * Presets initial population to be included for input to workers.
   *
   * @param a_workRequest the work request that is about to be sent.
   *
   * @throws Exception
   *
   * @author Klaus Meffert
   * @since 3.3.3
   */
  protected void presetPopulation(JGAPRequestGP a_workRequest)
      throws Exception {
    /**@todo merge previously stored results with new requests!
     * sometimes preset them as input for worker, sometimes give worker an
     * empty population*/
    RandomGenerator randGen = getConfiguration().getRandomGenerator();
    double d = randGen.nextDouble();
    if (d > 0.2d) {
      Map<String, List> topAll = m_objects.getTopResults();
      String appid = m_gridConfig.getContext().getAppId();
      List<IGPProgram> topApp = topAll.get(appid);
      int added = 0;
      int index = 0;
      GPPopulation pop = a_workRequest.getPopulation();
      IGPProgram[] programs = pop.getGPPrograms();
      while (index < pop.getPopSize() && pop.getGPProgram(index) != null) {
        index++;
      }
      List toAdd = new Vector();
      for (IGPProgram prog : topApp) {
        toAdd.add(prog);
        added++;
        if (added >= 3 || randGen.nextDouble() > 0.7d) {
          break;
        }
      }
      // Now merge old and new programs to one pool.
      // -------------------------------------------
      int len = programs.length;
      if (len > 0) {
        len = 0;
        while (len < programs.length && programs[len] != null) {
          len++;
        }
      }
      IGPProgram[] programsNew = (IGPProgram[]) toAdd.toArray(new IGPProgram[] {});
      int size = len + toAdd.size();
      IGPProgram[] allPrograms = new IGPProgram[size];
      if (len > 0) {
        System.arraycopy(programs, 0, allPrograms, 0, len);
      }
      System.arraycopy(programsNew, 0, allPrograms, len, programsNew.length);
      pop.setGPPrograms(allPrograms);
      log.info("Population preset with " + added + " additional programs");
    }
  }

  protected void showCurrentResults()
      throws Exception {
    /**@todo impl*/
    String appid = m_gridConfig.getContext().getAppId();
    Map<String, List> topAll = m_objects.getTopResults();
    List<IGPProgram> topApp = topAll.get(appid);
    if (topApp != null && topApp.size() > 0) {
      log.info("Top evolved results yet:");
      log.info("------------------------");
      for (IGPProgram prog : topApp) {
        log.info("Fitness " +
                 NumberKit.niceDecimalNumber(prog.getFitnessValue(), 2));
      }
      log.info("");
    }
  }
}

⌨️ 快捷键说明

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