예제 #1
0
파일: Console.java 프로젝트: xanax/scratch
  void killPlayThread() {
    tellThreadToStop();

    try {
      if (playThread != null) {
        while (playThread.isAlive()) {
          try {
            playThread.interrupt();
          }
          // Ignore security exceptions resulting from
          // attempting to interrupt a thread.
          // TODO Explain this better.
          catch (SecurityException ex) {
          }
          playThread.join(50);
        }

        playThread = null;
      }
    } catch (InterruptedException ex) {
      System.out.println("Interrupted while killing the play thread.  Shouldn't happen.");
    }
  }
예제 #2
0
  /**
   * This one checks that the stats message was received. If not, the message is sent again up to
   * five times. Run time an best individual of run are logged.
   */
  public void finalStatistics(final EvolutionState state, final int result) {
    super.finalStatistics(state, result);

    EvolutionAgent agent = (EvolutionAgent) state;

    StatisticsData data =
        new StatisticsData(
            new Address(agent.getName()),
            state.generation,
            System.currentTimeMillis() - creationtime,
            getBestIndividual(state),
            getBestIndividual(state));

    if (agent.iamroot) // Local logging
    printStatistics(state, data); // Every statistic will go there
    else { // DRM logging
      for (int i = 0; i < 5; i++) { // Try to send final data 5 times
        IRequest request = agent.fireMessage(agent.getRootAddress(), EvolutionAgent.M_STATS, data);
        while (request.getStatus() == IRequest.WAITING) {
          Thread.yield();
          // try{Thread.sleep(1000);}
          // catch(Exception e){state.output.error("Exception: " + e);}
        }
        if (request.getStatus() == IRequest.DONE) {
          break;
        } else {
          state.output.error("There was an error sending final statistics.");
          try {
            Thread.sleep(1000 * i ^ 2);
          } catch (Exception e) {
            state.output.error("Exception: " + e);
          }
        }
      }
    }
  }
예제 #3
0
파일: Console.java 프로젝트: xanax/scratch
 void resumePlayThread() {
   synchronized (playThread) {
     setPaused(false);
     playThread.notify();
   }
 }
예제 #4
0
파일: Console.java 프로젝트: xanax/scratch
  void spawnPlayThread(final boolean rfc) {
    threadIsToStop = false;

    Runnable run =
        new Runnable() {
          Vector listeners = new Vector();
          boolean restoreFromCheckpoint = rfc;

          void addListener(EvolutionStateListener l) {
            listeners.add(l);
          }

          void firePostEvolutionStep() {
            EvolutionStateEvent evt = new EvolutionStateEvent(this);
            Iterator it = listeners.iterator();
            while (it.hasNext()) {
              EvolutionStateListener l = (EvolutionStateListener) it.next();
              l.postEvolution(evt);
            }
          }

          void restoreFromCheckpoint() {
            state.startFromCheckpoint();
            statisticsPane.removeAll();
            setupChartPanes();
            setupInspectionPanes();
          }

          /**
           * @throws BadParameterException
           * @throws ParamClassLoadException
           */
          void initializeEvolutionState() throws BadParameterException, ParamClassLoadException {
            listeners.removeAllElements();
            Output output = initializeOutput();

            // 2. set up thread values
            /*
              int breedthreads = parameters.getInt(
              new Parameter(Evolve.P_BREEDTHREADS),null,1);
              if (breedthreads < 1)
              Output.initialError("Number of breeding threads should be an integer >0.",
              new Parameter(Evolve.P_BREEDTHREADS));

              int evalthreads = parameters.getInt(
              new Parameter(Evolve.P_EVALTHREADS),null,1);
              if (evalthreads < 1)
              Output.initialError("Number of eval threads should be an integer >0.",
              new Parameter(Evolve.P_EVALTHREADS));
            */

            int breedthreads =
                Evolve.determineThreads(output, parameters, new Parameter(Evolve.P_BREEDTHREADS));
            int evalthreads =
                Evolve.determineThreads(output, parameters, new Parameter(Evolve.P_EVALTHREADS));
            boolean auto =
                (Evolve.V_THREADS_AUTO.equalsIgnoreCase(
                        parameters.getString(new Parameter(Evolve.P_BREEDTHREADS), null))
                    || Evolve.V_THREADS_AUTO.equalsIgnoreCase(
                        parameters.getString(
                            new Parameter(Evolve.P_EVALTHREADS),
                            null))); // at least one thread is automatic.  Seeds may need to be
                                     // dynamic.

            // 3. create the Mersenne Twister random number generators,
            // one per thread
            MersenneTwisterFast[] random =
                new MersenneTwisterFast[breedthreads > evalthreads ? breedthreads : evalthreads];
            int[] seeds = new int[breedthreads > evalthreads ? breedthreads : evalthreads];

            String seed_message = "Seed: ";
            for (int x = 0; x < random.length; x++) {

              seeds[x] = conPanel.getSeed(currentJob, x);
              seed_message = seed_message + seeds[x] + " ";
            }

            for (int x = 0; x < random.length; x++) {

              for (int y = x + 1; y < random.length; y++)
                if (seeds[x] == seeds[y]) {

                  Output.initialError(
                      Evolve.P_SEED
                          + "."
                          + x
                          + " ("
                          + seeds[x]
                          + ") and "
                          + Evolve.P_SEED
                          + "."
                          + y
                          + " ("
                          + seeds[y]
                          + ") ought not be the same seed.");
                }
              random[x] = new MersenneTwisterFast(seeds[x]);
            }

            state =
                (EvolutionState)
                    parameters.getInstanceForParameter(
                        new Parameter(Evolve.P_STATE), null, EvolutionState.class);

            state.parameters = parameters;
            state.random = random;
            state.output = output;
            String jobFilePrefix = Console.this.conPanel.getJobFilePrefix();
            if (Console.this.conPanel.getNumJobs() > 1) {
              if (jobFilePrefix == null || jobFilePrefix.length() < 1) {
                jobFilePrefix = "job";
              }
              jobFilePrefix = jobFilePrefix + "." + Console.this.currentJob + ".";
              state.output.setFilePrefix(jobFilePrefix);
            }

            state.evalthreads = evalthreads;
            state.breedthreads = breedthreads;

            output.systemMessage("Threads:  breed/" + breedthreads + " eval/" + evalthreads);
            output.systemMessage(seed_message);

            state.startFresh();

            if (Console.this.conPanel.getNumJobs() > 0) {
              state.checkpointPrefix = jobFilePrefix + state.checkpointPrefix;
            }

            if (currentJob == 0) {
              statisticsPane.removeAll();
            }

            setupChartPanes();
            setupInspectionPanes();
          }

          /**
           * @throws NumberFormatException
           * @throws BadParameterException
           */
          void setupInspectionPanes() throws NumberFormatException, BadParameterException {
            inspectionPane.removeAll();
            // Setup the Evolution State inspection pane
            JScrollPane stateInspectionPane = new JScrollPane();
            JTree stateInspectionTree = new JTree(new ReflectedObject(Console.this.state));
            stateInspectionPane.setViewportView(stateInspectionTree);
            inspectionPane.add("Evolution State", stateInspectionPane);

            // Setup the subpopulation inspection panes
            Parameter p_subPops = new Parameter("pop.subpops");
            int numSubPops = parameters.getInt(p_subPops, null);
            for (int subPop = 0; subPop < numSubPops; ++subPop) {
              SubpopulationPanel subPopPane = new SubpopulationPanel(Console.this, subPop);
              subPopPane.setup(Console.this.state, p_subPops.push("" + subPop));
              inspectionPane.add("SubPop " + subPop, subPopPane);
              addListener(subPopPane);
            }
          }

          /** @throws BadParameterException */
          void setupChartPanes() throws BadParameterException {
            // Set up statistics charts (if any)
            StatisticsChartPane statPane = new StatisticsChartPane();
            statPane.setup(state, new Parameter("stat"));
            if (statPane.numCharts > 0) statisticsPane.addTab("Job " + currentJob, statPane);
          }

          public void run() {

            try {
              while (currentJob < conPanel.getNumJobs()) {
                if (!restoreFromCheckpoint) initializeEvolutionState();
                else restoreFromCheckpoint();
                state.output.message("\nJob " + currentJob);

                result = EvolutionState.R_NOTDONE;
                while (result == EvolutionState.R_NOTDONE
                    && !Thread.currentThread().isInterrupted()
                    && !isThreadToStop()) {

                  try {
                    synchronized (playThread) {
                      while (isPaused() && !getStep()) {
                        playThread.wait();
                      }
                    }
                  } catch (InterruptedException e) {
                    // This can happen if the play thread is stopped
                    // while paused
                  }

                  if (!Thread.currentThread().isInterrupted() && !isThreadToStop()) {
                    result = state.evolve();
                    try {
                      firePostEvolutionStep();
                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                    Console.this
                        .getStatusField()
                        .setText("Job: " + currentJob + " Generation: " + state.generation);
                    setStep(false);
                  }
                }

                /*
                 * If the play thread has been interrupted before the experiment
                 * has completed, consider the experiment a failure.
                 */
                if (result == EvolutionState.R_NOTDONE) result = EvolutionState.R_FAILURE;

                if (state != null && result != EvolutionState.R_NOTDONE) {
                  state.finish(result);
                }

                currentJob++;
              }
            } catch (Exception e) {
              e.printStackTrace();
              // System.err.println("Exception when running job:\n\t"+e);
            }

            conPanel.enableControls();
            finishAndCleanup();
          }
        };

    playThread = new Thread(run);
    playThread.start();
  }