Package eas.users.lukas.evaluateMARB

Source Code of eas.users.lukas.evaluateMARB.TrajectoryMaster

/*
* File name:        EvaluationMaster.java (package eas.users.lukas.evaluateMARB)
* Author(s):        Lukas König
* Java version:     6.0
* Generation date:  21.12.2011 (09:17:20)
*
* (c) This file and the EAS (Easy Agent Simulation) framework containing it
* is protected by Creative Commons by-nc-sa license. Any altered or
* further developed versions of this file have to meet the agreements
* stated by the license conditions.
*
* In a nutshell
* -------------
* You are free:
* - to Share -- to copy, distribute and transmit the work
* - to Remix -- to adapt the work
*
* Under the following conditions:
* - Attribution -- You must attribute the work in the manner specified by the
*   author or licensor (but not in any way that suggests that they endorse
*   you or your use of the work).
* - Noncommercial -- You may not use this work for commercial purposes.
* - Share Alike -- If you alter, transform, or build upon this work, you may
*   distribute the resulting work only under the same or a similar license to
*   this one.
*
* + Detailed license conditions (Germany):
*   http://creativecommons.org/licenses/by-nc-sa/3.0/de/
* + Detailed license conditions (unported):
*   http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en
*
* This header must be placed in the beginning of any version of this file.
*/

package eas.users.lukas.evaluateMARB;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import org.jfree.chart.JFreeChart;

import aufnahme.fmg.edu.kit.aifb.AufnahmeTyp.Population;
import aufnahme.fmg.edu.kit.aifb.PopulationTyp.Roboter;

import com.lowagie.text.pdf.DefaultFontMapper;

import eas.miscellaneous.StaticMethods;
import eas.miscellaneous.system.FileNamePostfixFilter;
import eas.plugins.masterScheduler.AbstractDefaultMaster;
import eas.plugins.standard.eaPlugin.EAPlugin;
import eas.plugins.standard.eaPlugin.xmlRecording.XMLAufnLesen;
import eas.plugins.standard.visualization.AllroundTrajectoryPlugin;
import eas.simulation.ConstantsSimulation;
import eas.simulation.Wink;
import eas.simulation.spatial.sim2D.marbSimulation.EnvironmentEA;
import eas.simulation.spatial.sim2D.marbSimulation.RobEA;
import eas.simulation.spatial.sim2D.marbSimulation.statistik.RobSnapshot;
import eas.startSetup.ParCollection;

/**
* @author Lukas König
*/
public class TrajectoryMaster extends AbstractDefaultMaster<EnvironmentEA> {

    /**
     *
     */
    private static final long serialVersionUID = -3309106623450804773L;

    @Override
    public List<String> getRequiredPlugins() {
        LinkedList<String> list = new LinkedList<String>();
        list.add(new EAPlugin().id());
        list.add(new AllroundTrajectoryPlugin().id());
        return list;
    }
   
    @Override
    public EnvironmentEA[] generateRunnables(ParCollection params) {
        EnvironmentEA[] envs = new EnvironmentEA[1];
        envs[0] = new EnvironmentEA(new Random(params.getSeed()),0 , params, null, "TrajectoryArena");
        return envs;
    }

    private File[] storedRuns;
    private int filesFinished;

    @Override
    public void runBeforeSimulation(EnvironmentEA umg, ParCollection params) {
        super.runBeforeSimulation(umg, params);
        storedRuns = new File(params.getStdDirectory()).listFiles(new FileNamePostfixFilter("gz"));
        filesFinished = 0;
    }
   
    @Override
    public synchronized void runDuringSimulation(EnvironmentEA env, Wink simZyk, ParCollection params) {
        super.runDuringSimulation(env, simZyk, params);
        XMLAufnLesen aufn = null;

        if (simZyk.getLastTick() % Math.round(params.getParValueDouble("saveInterval")) == 0) {
            if (filesFinished < storedRuns.length) {
                env.removeAllAgents();
   
                String compressedFileName = storedRuns[filesFinished].getPath();
                String decompressedFileName = params.getStdDirectory() + File.separator + StaticMethods.datNamOhneHintErw(storedRuns[filesFinished].getPath());
               
                params.log(StaticMethods.LOG_INFO, "This is Trajectory Master at time " + simZyk + ".");
               
                StaticMethods.entpackeDatei(compressedFileName, decompressedFileName, false); // Set to true to delete compressed file.
                params.log(StaticMethods.LOG_INFO, "Decompressed '" + compressedFileName + "' to '" + decompressedFileName + "'.");
   
                aufn = new XMLAufnLesen(new File(decompressedFileName), params);
                params.log(StaticMethods.LOG_INFO, "Loaded '" + decompressedFileName + "'.");
               
                StaticMethods.deleteDAT(decompressedFileName);
                params.log(StaticMethods.LOG_INFO, "Deleted temp files.");

                int bestPopNum = findBestPopulationMovingAverage(aufn, 5, storedRuns[filesFinished].getName(), params);

                // Starte n Generationen vor der besten Population.
                bestPopNum = Math.max(0, bestPopNum - 1);
               
                for (int i = 0; i < aufn.getPop(0).getRobSchnapp().length; i++) {
                    RobSnapshot robSchnapp = aufn.getPop(bestPopNum).getRobSchnapp()[i];
                    RobEA rob = new RobEA(i, env, params, env.getRand());
                    rob.erzeugeAusSequenz(0, robSchnapp.getVStdCodes()[0], null, false);
                    env.hinzuRobotRand(rob);
                   
                    // Speichere einen beliebigen (hoffentlich representativen) Roboterautomaten.
                    if (i == 0) {
                        StaticMethods.saveAutPNG(
                                robSchnapp.getVStdCodes()[0],
                                storedRuns[filesFinished].getName() + "_simTrajTime_" + simZyk.getLastTick() + "_simOriginalTime_" + aufn.getPop(bestPopNum).getId() + ".png",
                                params);
                        rob.speichereAuts(storedRuns[filesFinished].getName() + "_simTrajTime_" + simZyk.getLastTick() + "_simOriginalTime_" + aufn.getPop(bestPopNum).getId());
                    }
                }
                       
                filesFinished++;
            } else {
                env.getSimTime().timeTerminate();
            }
        }
    }

    /**
     * @param aufn
     * @return  The best population in terms of moving average.
     */
    private int findBestPopulationMovingAverage(XMLAufnLesen aufn, int maWindow, String fileNamePrefix, ParCollection params) {
        // Finde beste Population (gleitender Durchschnitt).
        int bestPopNum; // Das ist die Populationsnummer (nicht der Simulationszyklus)!
        double bestPopFit;
        Double[] fitVerlauf = new Double[aufn.getAllPopulations().length];
        Double[] fitVerlaufMA = new Double[aufn.getAllPopulations().length];
        Double[] fitVerlaufMA2 = new Double[aufn.getAllPopulations().length];
        int i = 0;
       
        // Mit Nullen füllen.
        for (int k = 0; k < fitVerlauf.length; k++) {
            fitVerlauf[k] = 0.0;
            fitVerlaufMA[k] = 0.0;
            fitVerlaufMA2[k] = 0.0;
        }
       
        // Erzeuge Fitnesverlauf.
        for (Population pop : aufn.getAllPopulations()) {
            int fitSum = 0;
            for (Roboter rob : pop.getRoboterArray()) {
                fitSum += rob.getFit();
            }
            fitVerlauf[i] = (double) fitSum;
            i++;
        }
       
        // Moving Average Left-To-Right.
        for (int j = maWindow; j < fitVerlaufMA.length; j++) {
            int fitSum = 0;
            for (int k = j - maWindow; k <= j; k++) {
                fitSum += fitVerlauf[k];
            }
           
            fitVerlaufMA[j] = (double) fitSum / (double) (maWindow + 1);
        }

        // Moving Average Right-To-Left.
        for (int j = fitVerlaufMA2.length - 1 - maWindow; j >= 0; j--) {
            int fitSum = 0;
            for (int k = j; k <= j + maWindow; k++) {
                fitSum += fitVerlaufMA[k];
            }
           
            fitVerlaufMA2[j] = (double) fitSum / (double) (maWindow + 1);
        }
       
        // Finde beste Population.
        bestPopFit = Double.MIN_VALUE;
        bestPopNum = 0;
        for (int j = 0; j < fitVerlaufMA2.length; j++) {
            if (fitVerlaufMA2[j] > bestPopFit) {
                bestPopFit = fitVerlaufMA2[j];
                bestPopNum = j;
            }
        }

        JFreeChart chart = StaticMethods.generateLineChartFromYAxisData(
                "Course of fitness for '" + fileNamePrefix + "'",
                "",
                "",
                new String[] {"MA right-to-left", "Fitness sum"},
                new Double[][] {fitVerlaufMA2, fitVerlauf});
        try {
            StaticMethods.saveChartAsPDF(new File(params.getStdDirectory() + File.separator + fileNamePrefix + ".pdf"), chart, 600, 400, new DefaultFontMapper());
        } catch (IOException e) {
            throw new RuntimeException("PDF not generated.");
        }
       
        return bestPopNum;
    }
   
//    /**
//     * @param aufn
//     *
//     * @return  The very best population in terms of fitness sum.
//     */
//    private int findBestPopulationRegular(XMLAufnLesen aufn) {
//        // Finde beste Population (regulär).
//        int bestPopNum = 0; // Das ist die Populationsnummer (nicht der Simulationszyklus)!
//        int bestPopFit = Integer.MIN_VALUE;
//        for (Population pop : aufn.getAllPopulations()) {
//            int fitSum = 0;
//            for (Roboter rob : pop.getRoboterArray()) {
//                fitSum += rob.getFit();
//            }
//           
//            if (fitSum > bestPopFit) {
//                bestPopFit = fitSum;
//                bestPopNum = pop.getID();
//            }
//        }
//        return bestPopNum;
//    }
   
    @Override
    public String id() {
        return ConstantsSimulation.DEFAULT_MASTER_SCHEDULER_ID + "-MARB-Trajectories";
    }
}
TOP

Related Classes of eas.users.lukas.evaluateMARB.TrajectoryMaster

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.