Package eas.startSetup.marbBuilder.traceBetrachter

Source Code of eas.startSetup.marbBuilder.traceBetrachter.TraceBetrachter

/*
* Datei:          TraceBetrachter.java
* Autor(en):      Lukas König
* Java-Version:   6.0
* Erstellt (vor): 01.04.2008
*
* (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.startSetup.marbBuilder.traceBetrachter;

import java.awt.Button;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;

import eas.math.geometry.Vector2D;
import eas.miscellaneous.StaticMethods;
import eas.miscellaneous.system.windowFrames.GeneralDialog;
import eas.miscellaneous.system.windowFrames.WindClosAdapStat;
import eas.plugins.Plugin;
import eas.plugins.PluginFactory;
import eas.plugins.standard.eaPlugin.xmlRecording.XMLAufnLesen;
import eas.plugins.standard.progressEstimation.AllroundTimeEstimatorPlugin;
import eas.simulation.SimulationStarter;
import eas.simulation.spatial.sim2D.marbSimulation.endlAutomat.conditions.Condition;
import eas.simulation.spatial.sim2D.marbSimulation.statistik.PopSnapshot;
import eas.simulation.spatial.sim2D.marbSimulation.statistik.RobSnapshot;
import eas.simulation.spatial.sim2D.marbSimulation.translator.Translator;
import eas.simulation.spatial.sim2D.marbSimulation.translator.script.ScriptInterpreter;
import eas.startSetup.GlobalVariables;
import eas.startSetup.ParCollection;
import eas.startSetup.marbBuilder.MultiLineLabel;
import eas.startSetup.marbBuilder.Vis;
import eas.statistics.StatisticMethods;
import eas.statistics.logging.AbstractMsg;

/**
* Klasse zur Repräsentation eines Steuerfensters.
*
* @author Lukas König
*/
public final class TraceBetrachter extends Frame
                                   implements ActionListener,
                                              ItemListener {

    /**
     * Die Versions-ID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * Info-Label.
     */
    private MultiLineLabel infos;
   
    /**
     * Liste der Snapshots.
     */
    private List traceListe;
   
    /**
     * Die XML-Aufnahme, die der TraceBetrachter darstellen soll.
     */
    private XMLAufnLesen aufnahme;
   
    /**
     * Die Graphen.
     */
    private ArrayList<Vis> graphen;
   
    /**
     * Die Parameter der Aufnahme.
     */
    private ParCollection parsAufn;
   
    /**
     * Der aktuelle Graph.
     */
    private Vis aktGraph;

    /**
     * Das Simulationsfenster.
     */
    private GuiSimulation guiSim;
   
    /**
     * Ob Vis-Fenster angezeigt werden.
     */
    private boolean visAnzeigen;
   
    /**
     * Die Nummer des selektierten Roboters.
     */
    private int selRob;
   
    /**
     * Die Nummer des aktuellen Populationssnapshots.
     */
    private long popNum;
   
    /**
     * Die Autoplay-Klasse.
     */
    private AutoPlay a;
   
    /**
     * Ein Button.
     */
    private Button b5;

    /**
     * Ein Button.
     */
    private Button b6;
   
    /**
     * Der Parametersatz von this.
     */
    private ParCollection aktParams;
   
    /**
     * Liste der Verschiebungen der Gegenst�nde von ihrem Nullpunkt.
     */
    private Vector2D[] aktVersch;
   
    /**
     * Bei der letzten Suche die beste gefundene Population.
     */
    private int lastBest;
   
    /**
     * Der Konstruktor.
     *
     * @param aufn        Die darzustellende Aufnahme.
     * @param paramsAufn  Der Parametersatz der Aufnahme.
     * @param paramsAkt   Der aktuelle Parametersatz.
     */
    private TraceBetrachter(
            final XMLAufnLesen aufn,
            final ParCollection paramsAufn,
            final ParCollection paramsAkt) {
        super("Trace-Betrachtung");
       
        this.aktParams = paramsAkt;
        this.parsAufn = paramsAufn;
        this.selRob = 0;
       
        String[] seqs = new String[
               aufn.getPop(0).getRobSchnapp()[0].getVStdCodes().length];
       
        this.aktGraph = new Vis("", seqs, null, -1,
                this.aktParams, null, null);

        this.popNum = -1;
       
        this.lastBest = 0;
       
        this.graphen = new ArrayList<Vis>();
        this.addWindowListener(new WindClosAdapStat(true));
        Button b1, b2, b3, b4, b7, b8, b9, b10, b11, b12, b13;
       
        Panel buttonPanel = new Panel();
        Panel buttonPanel2 = new Panel();
        Panel labelPanel = new Panel();
       
        this.setLayout(new GridLayout(4, 1));
        buttonPanel.setLayout(new GridLayout(3, 2));
        buttonPanel2.setLayout(new GridLayout(4, 2));
        labelPanel.setLayout(new GridLayout(2, 1));
        labelPanel.setBackground(new Color(255, 255, 200));
       
        this.traceListe = new List();
        this.add(this.traceListe);
       
        b1 = new Button("<");
        b2 = new Button(">");
        b3 = new Button("<<");
        b4 = new Button(">>");
        this.b5 = new Button("--");
        this.b6 = new Button("++");
        b7 = new Button("Extrahiere Fitness...");
        b8 = new Button("Ersetze Pop!");
        b9 = new Button("Simulation...");
        b10 = new Button("Trajektorien...");
        b11 = new Button("Finde beste");
        b12 = new Button("Extr. Zusatz...");
        b13 = new Button("Extr. LOG...");
       
        b1.setFont(new Font("", 0, 40));
        b2.setFont(new Font("", 0, 40));
        b3.setFont(new Font("", 0, 40));
        b4.setFont(new Font("", 0, 40));
        this.b5.setFont(new Font("", 0, 40));
        this.b6.setFont(new Font("", 0, 40));
        b7.setFont(new Font("", 1, 16));
        b8.setFont(new Font("", 1, 12));
        b9.setFont(new Font("", 1, 12));
        b10.setFont(new Font("", 1, 12));
        b11.setFont(new Font("", 1, 12));
        b12.setFont(new Font("", 1, 12));
        b13.setFont(new Font("", 1, 12));
       
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        b4.addActionListener(this);
        this.b5.addActionListener(this);
        this.b6.addActionListener(this);
        b7.addActionListener(this);
        b8.addActionListener(this);
        b9.addActionListener(this);
        b10.addActionListener(this);
        b11.addActionListener(this);
        b12.addActionListener(this);
        b13.addActionListener(this);
       
        buttonPanel.add(b1);
        buttonPanel.add(b2);
        buttonPanel.add(b3);
        buttonPanel.add(b4);
        buttonPanel.add(this.b5);
        buttonPanel.add(this.b6);
       
        MultiLineLabel m3;
        m3 = new MultiLineLabel();
        buttonPanel2.add(b10);
        buttonPanel2.add(b11);
        buttonPanel2.add(b8);
        buttonPanel2.add(b9);
        buttonPanel2.add(b12);
        buttonPanel2.add(b13);
        buttonPanel2.add(m3);
//        buttonPanel2.add(m4);

        this.infos = new MultiLineLabel();
        labelPanel.add(b7);
        labelPanel.add(this.infos);
        this.traceListe.addItemListener(this);

        this.add(buttonPanel);
        this.add(buttonPanel2);
        this.add(labelPanel);
       
        this.setSize(200, 1000);
        this.setResizable(false);
        this.setVisible(true);
       
        this.setEnabled(false);
        this.setInfos("Aufnahme wird geladen...");
        this.traceListe.setVisible(false);
       
        // Liste der Populationsschnappsch�sse auff�llen.
        this.aufnahme = aufn;
       
        for (int i = 0; i < this.aufnahme.popNum(); i++) {
            PopSnapshot aktPop = this.aufnahme.getPop(i);
            this.addListEl(""
                           + i
                           + ". Snapshot ("
                           + aktPop.getId()
                           + ") ["
                           + aktPop.getFitSum()
                           + "]");
        }
       
       
        this.traceListe.setVisible(true);
        this.setInfos("Aufnahme geladen.");       
        this.setEnabled(true);
        StaticMethods.log(2, "Aufnahme geladen.", paramsAkt);
        this.waehleEintragPlus();
    }

    /**
     * Die actionPerformed Methode.
     *
     * @param event  Das Event.
     */
    @Override
    public void actionPerformed(final ActionEvent event) {
        Object obj = event.getSource();
        String cmd = event.getActionCommand();

        this.setCursor(new Cursor(Cursor.WAIT_CURSOR));

        if (obj instanceof Button) {
            if (cmd.equals(">")) {
                this.waehleEintragPlus();
            } else if (cmd.equals("<")) {
                this.waehleEintragMinus();
            } else if (cmd.equals("<<")) {
                this.traceListe.select(0);
                this.itemStateChanged(null);
            } else if (cmd.equals(">>")) {
                this.traceListe.select(this.traceListe.getItemCount() - 1);
                this.itemStateChanged(null);
            } else if (cmd.equals("--")) {
                this.b5.setLabel("S");
                this.b6.setLabel("S");
                this.a = new AutoPlay(this, false);
                this.a.starte();
            } else if (cmd.equals("++")) {
                this.b5.setLabel("S");
                this.b6.setLabel("S");
                this.a = new AutoPlay(this, true);
                this.a.starte();
            } else if (cmd.equals("S")) {
                this.b5.setLabel("--");
                this.b6.setLabel("++");
                if (a != null) {
                    this.a.stoppe();
                }
            } else if (cmd.equals("Extrahiere Fitness...")) {
                this.extrahiereFit();
            } else if (cmd.equals("Ersetze Pop!")) {
                StaticMethods.deleteALL(eas.startSetup.marbBuilder.ConstantsGraphVis.TEMP_ENDUNG,
                        this.aktParams);
                StaticMethods.deleteALL(eas.startSetup.marbBuilder.ConstantsGraphVis.BED_ENDUNG,
                        this.aktParams);
                StaticMethods.deleteALL(eas.startSetup.marbBuilder.ConstantsGraphVis.KOORD_ENDUNG,
                        this.aktParams);
                StaticMethods.deleteALL(eas.startSetup.marbBuilder.ConstantsGraphVis.GRAPH_ENDUNG,
                        this.aktParams);
                StaticMethods.deleteALL(eas.startSetup.marbBuilder.ConstantsGraphVis.PNG_ENDUNG,
                        this.aktParams);
                StaticMethods.deleteALL(eas.startSetup.marbBuilder.ConstantsGraphVis.TRANS_ENDUNG,
                        this.aktParams);
                this.speicherePop();
            } else if (cmd.equals("Speichere Alle")) {
                // Button nicht mehr vorhanden.
                this.speichereAlle();
            } else if (cmd.equals("Simulation...")) {
                this.aktGraph.setVisible(false);
                this.setVisible(false);
                this.guiSim.setVisible(false);
//                this.aktGraph.setExtendedState(JFrame.ICONIFIED);
//                this.setExtendedState(JFrame.ICONIFIED);
//                this.guiSim.setExtendedState(JFrame.ICONIFIED);
                SimulationStarter.main(parsAufn.getAllParsArrayView());
            } else if (cmd.equals("Trajektorien...")) {
                ArrayList<String> arr = new ArrayList<String>();
                Iterator<Vis> it = this.graphen.iterator();
                while (it.hasNext()) {
                    Vis v = it.next();
                    arr.add(v.toString());
                }
               
                GeneralDialog dia = new GeneralDialog(
                          this,
                          "Draw trajectories",
                          "select robot(s) for drawing trajectories "
                              + "and last snapshot to be considered.",
                          arr,
                          "Zeichne mit Fitness",
                          "Zeichne",
                          true,
                          this.aufnahme.popNum() - 1);
                dia.setPosition(new Vector2D(400, 200));
                dia.setSize(new Vector2D(850, 250));
               
                dia.setVisible(true);
                if (dia.getResult().equals("Zeichne")
                        || dia.getResult().equals("Zeichne mit Fitness")) {
                    String[] gewGraphen = dia.getListe().getSelectedItems();
                    int[] grIndizes = new int[gewGraphen.length];
                    String name;
                   
                    for (int i = 0; i < gewGraphen.length; i++) {
                        grIndizes[i] = -1;
                       
                        for (int j = 0; j < this.graphen.size(); j++) {
                            name = this.graphen.get(j).getGraphName();
                            if (name.equals(gewGraphen[i])) {
                                grIndizes[i] = j;
                            }
                        }
                    }
                   
                    this.zeichneTraj(grIndizes,
                                     this.traceListe.getSelectedIndex(),
                                     Integer.parseInt(dia.getZusatzText()),
                                     dia.getResult().equals(
                                             "Zeichne mit Fitness"));
                }
            } else if (cmd.equals("Finde beste")) {
                long max = Integer.MIN_VALUE;
                PopSnapshot p;
                int i = (this.lastBest + 1)
                        % this.aufnahme.popNum();
                int last = this.lastBest;
                int anfang = this.lastBest;
               
                while (i != anfang) {
                    p = this.aufnahme.getPop(i);
                   
                    if (p.getFitSum() > max) {
                        max = p.getFitSum();
                        last = i;
                    }
                   
                    i = (i + 1) % this.aufnahme.popNum();
                }
               
                p = this.aufnahme.getPop(anfang);
                if (p.getFitSum() > max) {
                    max = p.getFitSum();
                    last = anfang;
                }
               
                this.traceListe.select(last);
                this.itemStateChanged(null);
                this.lastBest = last;
            } else if (cmd.equals("Extr. Zusatz...")) {
                this.zeigeZusatz();
            } else if (cmd.equals("Extr. LOG...")) {
                this.zeigeLOG();
            }
        }

       this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
   
    /**
     * Zeichnet die Trajektorien für die Roboter mit den ahgegebenen Indizes
     * in das Feld.
     *
     * @param grIndizes  Die Indizes der Roboter, deren Trajektorien
     *                   gezeichnet werden sollen.
     * @param startSnap  Der Snapshot, bei dem die Trajektorien beginnen
     *                   sollen.
     * @param endSnap    Der Snapshot, bei dem die Trajektorien enden
     *                   sollen.
     * @param fitness    Ob die Fitness senkrecht zur Blickrichtung aufgetragen
     *                   werden soll.
     */
    private void zeichneTraj(final int[] grIndizes,
                             final int startSnap,
                             final int endSnap,
                             final boolean fitness) {
        this.guiSim.loescheFeld();
        long lang = 20;
        Vector2D norm;
        RobSnapshot rob;
        int anfang = startSnap;
        int ende = endSnap;
        PopSnapshot pop;
        Vector2D[] letzte = new Vector2D[grIndizes.length];
        byte farbe;
       
        for (int i = anfang; i <= ende; i++) {
            pop = this.aufnahme.getPop(i);
            for (int j = 0; j < grIndizes.length; j++) {
                rob = pop.getRobSchnapp()[grIndizes[j]];
               
                farbe
                    = eas.simulation.ConstantsSimulation.FARBEN_BENUTZER[
                      grIndizes[j]
                      % eas.simulation.ConstantsSimulation.FARBEN_BENUTZER.length];
               
                if (letzte[j] != null) {
                    this.guiSim.getUmgeb().setzeLinie(
                                              (int) letzte[j].x,
                                              (int) letzte[j].y,
                                              (int) rob.getPosition().x,
                                              (int) rob.getPosition().y,
                                              farbe,
                                              true,
                                              false,
                                              false,
                                              false);

                    norm = new Vector2D(letzte[j].x, letzte[j].y);
                    norm.sub(new Vector2D(
                            rob.getPosition().x,
                            rob.getPosition().y));
                    norm.ortho();
                    norm.norm();
                   
                    lang = rob.getFitSum();
                   
                    if (lang <= 0) {
                        lang = 5;
                        farbe = eas.simulation.ConstantsSimulation.FARBE_SEL;
                    } else {
                        lang += 5;
                    }
                   
                    if (!fitness) {
                        lang = 0;
                    }
                   
                    this.guiSim.getUmgeb().setzeLinie(
                            (int) rob.getPosition().x - norm.x * lang / 2,
                            (int) rob.getPosition().y - norm.y * lang / 2,
                            (int) rob.getPosition().x + norm.x * lang / 2,
                            (int) rob.getPosition().y + norm.y * lang / 2,
                            farbe,
                            true,
                            false,
                            false,
                            false);

                } else {
                    // Setze Kreuz + ersten Punkt.
                    int x1 = (int) rob.getPosition().x - 10;
                    int y1 = (int) rob.getPosition().y - 10;
                    int x2 = (int) rob.getPosition().x + 10;
                    int y2 = (int) rob.getPosition().y + 10;
                    this.guiSim.getUmgeb().setzeLinie(
                            x1, y1, x2, y2, farbe,
                            true, false, false, false);
                    this.guiSim.getUmgeb().setzeLinie(
                            x2, y1, x1, y2, farbe,
                            true, false, false, false);
                    this.guiSim.getUmgeb().setzeLinie(
                            x1 + 1, y1, x2 + 1, y2, farbe,
                            true, false, false, false);
                    this.guiSim.getUmgeb().setzeLinie(
                            x2 + 1, y1, x1 + 1, y2, farbe,
                            true, false, false, false);
                    this.guiSim.getUmgeb().setzeLinie(
                            x1 - 1, y1, x2 - 1, y2, farbe,
                            true, false, false, false);
                    this.guiSim.getUmgeb().setzeLinie(
                            x2 - 1, y1, x1 - 1, y2, farbe,
                            true, false, false, false);
                }

                letzte[j] = rob.getPosition();
            }
        }
       
        this.guiSim.getUmgeb().beendeZeichenSession();
    }
   
    /**
     * Extrahiert die Fitnesswerte der aktuellen Roboter.
     */
    private void extrahiereFit() {
        GeneralDialog dia;
        ArrayList<String> buttons = new ArrayList<String>();
        String sGes;

        sGes = StatisticMethods.extrahiereFit(this.aufnahme);
       
        buttons.add(new String("Ok"));
        dia = new GeneralDialog(this,
                                    "",
                                    "Extrahierte Fitnesswerte",
                                    buttons,
                                    sGes,
                                    10,
                                    100,
                                    false);
        dia.setVisible(true);
    }

    /**
     * Zeigt die Zusatzwerte der aktuellen Aufnahme in einem Fenster an.
     */
    private void zeigeZusatz() {
        GeneralDialog dia;
        ArrayList<String> buttons = new ArrayList<String>();

        buttons.add(new String("Ok"));
        dia = new GeneralDialog(this,
                                    "",
                                    "Extrahierte Zusatzinfos",
                                    buttons,
                                    StaticMethods.extrZusatz(this.aufnahme),
                                    10,
                                    100,
                                    false);
        dia.setVisible(true);
    }

    /**
     * Zeigt die LOGs der aktuellen Aufnahme in einem Fenster an.
     */
    private void zeigeLOG() {
        GeneralDialog dia;
        ArrayList<String> buttons = new ArrayList<String>();

        String ausgaben = "";
        LinkedList<AbstractMsg> nachrichten
            = this.parsAufn.getMsgs(
                    null,
                    Long.MIN_VALUE,
                    Long.MAX_VALUE);
       
        for (AbstractMsg m : nachrichten) {
            Date zwisch = new Date(m.getDatum());
           
            ausgaben += m.getType()
                + " ("
                + zwisch.toString() 
                + "): "
                + m.getMessage()
                + "\n";
        }
       
        buttons.add(new String("Ok"));
        dia = new GeneralDialog(this,
                                    "",
                                    "LOG-Ausgaben (Zeitpunkt des Speicherns "
                                        + "der Parameter beachten!)",
                                    buttons,
                                    ausgaben,
                                    10,
                                    100,
                                    false);
        dia.setVisible(true);
    }

    /**
     * wählt den nächsten Eintrag in der Trace-Liste und aktualisiert die
     * Darstellung.
     */
    public void waehleEintragPlus() {
        if (this.traceListe.getSelectedIndex()
                == this.traceListe.getItemCount() - 1) {
                this.traceListe.select(0);
            } else {
                this.traceListe.select(
                        this.traceListe.getSelectedIndex() + 1);
            }
        this.itemStateChanged(null);
       
        if (this.traceListe.getSelectedIndex()
                == this.traceListe.getItemCount() - 1) {
            if (this.a != null) {
                this.a.stoppe();
                this.b5.setLabel("--");
                this.b6.setLabel("++");
            }
        }
    }

    /**
     * wählt den nächsten Eintrag in der Trace-Liste und aktualisiert die
     * Darstellung.
     */
    public void waehleEintragMinus() {
        if (this.traceListe.getSelectedIndex() == 0) {
            this.traceListe.select(this.traceListe.getItemCount() - 1);
        } else {
            this.traceListe.select(this.traceListe.getSelectedIndex()
                                   - 1);
        }
        this.itemStateChanged(null);
       
        if (this.traceListe.getSelectedIndex()
                == 0) {
            if (this.a != null) {
                this.a.stoppe();
                this.b5.setLabel("--");
                this.b6.setLabel("++");
            }
        }
    }

    /**
     * Die item-State-Changed-Methode.
     *
     * @param e  Das Event.
     */
    @Override
    public void itemStateChanged(final ItemEvent e) {
        this.ladeSnap(this.traceListe.getSelectedIndex());
       
        this.aktGraph.dispose();
        if (this.visAnzeigen
                && this.graphen.size() > 0) {
            this.aktGraph = this.graphen.get(this.selRob);
            this.aktGraph.setVisible(true);
        }
    }
   
    /**
     * lädt einen einzelnen Snapshot in die Graphenliste.
     *
     * @param nummer  Die Nummer des zu ladenden Snapshots.
     */
    private void ladeSnap(final int nummer) {
        PopSnapshot pop
            = this.aufnahme.getPop(nummer);
        RobSnapshot[] robs = pop.getRobSchnapp();
        Vis neuVis;
        Translator[] trans = new Translator[robs[0].getTStdCodes().length];
       
        this.popNum = pop.getId();
        this.graphen.clear();
       
        for (int i = 0; i < robs.length; i++) {
            for (int j = 0; j < trans.length; j++) {
                trans[j] = new Translator(
                        robs[i].getTStdCodes()[j],
                        new ScriptInterpreter(
                                this.aktParams,
                                StaticMethods.MODUS_TRANSLATOR),
                        this.aktParams);
            }
           
            neuVis = new Vis(
                    this.nameRob(pop, robs[i]),
                    robs[i].getVStdCodes(),
                    robs[i].getConds(),
                    robs[i].getId(),
                    this.aktParams,
                    trans,
                    null);
            this.graphen.add(neuVis);
           
            int zustand = robs[i].getZustand();
            if (zustand < 0) {
                // Markiere Startzustand, falls zustand = -1.
                if (neuVis.getRob().vAuts()[0].holeStartzustand() != null) {
                    zustand = neuVis.getRob().vAuts()[0]
                                     .holeStartzustand().holeName();
                }
            }
            neuVis.selKnoten(
                  neuVis.getRob().vAuts()[0].holeKnoten(zustand),
                  0);

            neuVis.setBounds(this.getWidth(),
                             0,
                             800,
                             700);
        }
       
    /*
     * Erzeugt eine Simulationsumgebung, in der die Aufnahme angezeigt wird:
     */
        SimulationsZeit simZ;
        int size = robs.length;
       
        String[][] vAutStd  = new String[size][];
        String[][] tAutStd  = new String[size][];
        String[][] vAut  = new String[size][];
        String[][] tAut  = new String[size][];
        int[] identitaeten  = new int[size];
        Vector2D[] positionen = new Vector2D[size];
        double[] winkel     = new double[size];
        Vector2D[] versch;
        Vector2D[] neuVersch;
        int[][] fitness = new int[size][];
        Condition[][] conds = new Condition[size][];
       
        Vis[] visGr = new Vis[this.graphen.size()];
       
        int i = 0;
        Iterator<Vis> it = this.graphen.iterator();
        while (it.hasNext()) {
            visGr[i] = it.next();
           
            for (int j = 0; j < robs.length; j++) {
                if (visGr[i].getRob().id() == robs[j].getId()) {
                    vAutStd[i] = robs[j].getVStdCodes();
                    vAut[i] = robs[j].getVCodes();
                    tAutStd[i] = robs[j].getTStdCodes();
                    tAut[i] = robs[j].getTCodes();
                    fitness[i] = robs[j].getFitness();
                    identitaeten[i] = robs[j].getId();
                    positionen[i] = robs[j].getPosition();
                    winkel[i] = robs[j].getWinkel();
                    conds[i] = new Condition[robs[j].getConds().length];
                    for (int k = 0; k < robs[j].getConds().length; k++) {
                        conds[i][k] = robs[j].getConds()[k];
                    }
                    break;
                }
            }
            i++;
        }
           
        // Erzeugt eine neue Simulation, falls noch keine erzeugt wurde.
        if (this.guiSim == null) {
            Plugin<?>[] plugins = new Plugin[this.aktParams.getPlugins().size()];
           
            for (int z = 0; z < this.aktParams.getPlugins().size(); z++) {
                try {
                    plugins[z] = PluginFactory.getKonstPlug(
                            this.aktParams.getPlugins().get(z).id(),
                            this.aktParams);
                } catch (Exception e) {
                    plugins[z] = PluginFactory.getKonstPlug(new AllroundTimeEstimatorPlugin().id(), this.aktParams);
                }
            }

            this.guiSim = new GuiSimulation(
                    "Snapshot"
                    + " ["
                    + this.graphen.size()
                    + " robots]",
                    null,
                    this,
                    this.parsAufn,
                    this.aufnahme);
   
            simZ = new SimulationsZeit(
                    this.parsAufn,
                    this.guiSim,
                    visGr,
                    vAutStd,
                    conds,
                    identitaeten,
                    this.aufnahme);
           
            this.guiSim.setVisible(true);
            this.guiSim.registriereTakt(simZ);
        }

        // Dynamische Wände zeichnen.
        this.guiSim.getUmgeb().leereFeld();
        for (int j = 0; j < pop.getTatdynDrehMittPkt().length; j++) {
            if (pop.getTatdynDrehMittPkt()[j] != null) {
                this.guiSim.getUmgeb().setDynDrehMittPkt(j,
                        pop.getTatdynDrehMittPkt()[j]);
                this.guiSim.getUmgeb().dreheWand(j,
                        pop.getTatdynDrehWinkel()[j] * 180 / Math.PI);
                this.guiSim.getUmgeb().verschWand(j, pop.getTatdynVersch()[j]);
                this.guiSim.getUmgeb().verzerrWand(j,
                        pop.getTatdynSkalFaktor()[j].x,
                        pop.getTatdynSkalFaktor()[j].y);
            }
        }
        this.guiSim.getUmgeb().alleFelderNeu();
       
        // Gegenst�nde setzen.
        versch = pop.getVerschiebungen();
        if (versch != null) {
            if (this.aktVersch == null) {
                this.aktVersch = new Vector2D[versch.length];
                for (int k = 0; k < this.aktVersch.length; k++) {
                    this.aktVersch[k] = new Vector2D(0, 0);
                }
            }
           
            neuVersch = new Vector2D[versch.length];
            for (int k = 0; k < neuVersch.length; k++) {
                neuVersch[k] = new Vector2D(versch[k].x - this.aktVersch[k].x,
                                          versch[k].y - this.aktVersch[k].y);
               
                if (!this.guiSim.getUmgeb().verschGgstWennMoegl(neuVersch[k].x,
                                                                neuVersch[k].y,
                                                                k)) {
                    StaticMethods.log(StaticMethods.LOG_WARNING,
                                  "Gegenstand " + k + " nicht verschoben.",
                                  this.aktParams);
                }
            }
           
            this.aktVersch = versch;
        }
       
        // Roboter setzen.
        for (int j = 0; j < visGr.length; j++) {
            this.guiSim.getUmgeb().setEigRobUnbed(
                    visGr[j].getRob().id(),
                    vAutStd[j],
                    vAut[j],
                    tAutStd[j],
                    tAut[j],
                    positionen[j],
                    winkel[j],
                    fitness[j],
                    conds[j]);
        }

        this.guiSim.getUmgeb().beendeZeichenSession();
    }
   
    /**
     * Generiert einen Dateinamen für einen Roboter.
     *
     * @param pop  Der Popsnapshot.
     * @param rob  Der Robotersnapshot
     *
     * @return  Der generierte Name des Roboters.
     */
    private String nameRob(final PopSnapshot pop,
                           final RobSnapshot rob) {
        String s = "";
       
        s = s
            + this.parsAufn.getTimestamp().toString().replace(' ',
                                                            '_').replace(':',
                                                                         '-')
            + "__pop"
            + this.normiereZahl(pop.getId(), 6)
            + "__rob"
            + this.normiereZahl(rob.getId(), 3)
            + "_["
            + this.normiereZahl(rob.getFitSum(), 4)
            + "]";
               
        return s;
    }
   
    /**
     * Gibt die Zahl als String zurück, wobei die Anzahl an Stellen genau
     * die vorgegebene ist. Das wird durch Auff�llen von vorne mit Nullen
     * erreicht. Zu Große Zahlen werden unverändert zurückgegeben
     *
     * @param zahl     Die zu normierende Zahl.
     * @param stellen  Die Anzahl an Stellen.
     *
     * @return  Die normierte Zahl.
     */
    private String normiereZahl(final long zahl,
                                final int stellen) {
        String s = "";
        String zahlS = "" + zahl;
       
        for (int i = 0; i < stellen - zahlS.length(); i++) {
            s = s + "0";
        }
       
        s = s + zahlS;
       
        return s;
    }
   
    /**
     * Speichert alle Populationen.
     */
    private void speichereAlle() {
        int i = 0;
       
        while (i < this.traceListe.getItemCount()) {
            this.traceListe.select(i);
            this.itemStateChanged(null);
            this.speicherePop();
            i++;
        }
    }
   
    /**
     * Speichert die aktuelle Population im Standardverzeichnis.
     */
    private void speicherePop() {
        Vis aktVis;
        Iterator<Vis> it = this.graphen.iterator();
       
        while (it.hasNext()) {
            aktVis = it.next();
            aktVis.speichereGraph(
                    eas.startSetup.marbBuilder.Messages.getString("Vis.All"));
        }
       
        StaticMethods.log(StaticMethods.LOG_INFO,
                      "Population gespeichert ("
                         + this.popNum
                         + ").",
                      this.aktParams);    }
   
    /**
     * @param info The Text to set.
     */
    private void setInfos(final String info) {
        this.infos.setText(info);
    }
   
    /**
     * fügt ein Listenelement ein.
     *
     * @param s  Das einzufügende Element.
     */
    private void addListEl(final String s) {
        this.traceListe.add(s);
    }
   
    /**
     * Stellt ein, dass keine Vis-Fenster angezeigt werden.
     */
    public void deselektiereAlle() {
        this.aktGraph.dispose();
        this.visAnzeigen = false;
    }

    /**
     * Selektiert den angegebenen Roboter.
     *
     * @param rob  Der zu selektierende Roboter.
     */
    public void selGraph(final Vis rob) {
        int i = 0;
       
        Iterator<Vis> it = this.graphen.iterator();
        while (it.hasNext()) {
            if (rob == it.next()) {
                this.selRob = i;
                break;
            }
            i++;
        }
       
        this.visAnzeigen = true;
        this.aktGraph.dispose();
        this.aktGraph = rob;
        rob.setVisible(true);
    }
   
    /**
     * Selektiert das zum angegebenen Roboter gehörende Graphfenster
     * (macht es sichtbar, etc).
     *
     * @param rob  Der zu selektierende Roboter.
     */
    public void selGraph(final Roboter rob) {
        int i = 0;
        Vis aktVis;
       
        while (i < this.graphen.size()) {
            aktVis = this.graphen.get(i);
            if (aktVis.getRob().id() == rob.getId()) {
                aktVis.erzeugeTransAusStdSeqs(rob.getTransStdCodes());
                this.selGraph(aktVis);
            }
            i++;
        }
    }
   
    /**
     * Die Startmethode startet Werkzeuge zum auswerten von Statistiken.
     *
     * @param args  Die Parameter.<BR>
     *              <BR>
     *              Option 1: Der erste muss die Aufnahme-Datei bezeichen.
     *              Danach können mit einem Dummy-Parameter Abstand (!) die
     *              übrigen festgesetzt werden. Es werden jedoch die meisten
     *              Parameter aus der Aufnahme-Datei benutzt.<BR>
     *              Wenn der zweite Parameter "nurLetzter" ist, wird das
     *              Programm nach der automatischen Speicherung der letzten
     *              Population wieder beendet.<BR>
     *              <BR>
     *              Option 2: Wenn der zweite Parameter "alleFitnesswerte"
     *              ist, wird der erste als Verzeichnis interpretiert und von
     *              allen Statistiken in diesem Verzeichnis die Fitness
     *              extrahiert.
     */
    public static void main(final String[] args) {
        ParCollection paramsAkt = GlobalVariables.getPrematureParameters();
        paramsAkt.overwriteParameterList(args);
        XMLAufnLesen aufn = null;
       
        // Extrahiere alle Fitnesswerte.
        if (args.length > 1
            && args[1].toLowerCase().equals("allefitnesswerte")) {
            StaticMethods.log(StaticMethods.LOG_INFO,
                          "Extrahiere alle Fitnesswerte in " + args[0] + ".",
                          paramsAkt);
            StatisticMethods.extrahiereAlleFit(args[0], paramsAkt);
            StaticMethods.log(StaticMethods.LOG_INFO,
                          "Fitnesswerte extrahiert.",
                          paramsAkt);
            return;
        }

        // Normaler Programmstart.
        StaticMethods.log(StaticMethods.LOG_INFO,
                      "Aufnahme wird geladen (" + args[0] + ")...",
                      paramsAkt);
        try {
            if (StaticMethods.datEndung(args[0]).equals("gz")) {
                StaticMethods.entpackeDatei(args[0], StaticMethods
                        .datNamOhneHintErw(args[0]), false);
                aufn = new XMLAufnLesen(new File(StaticMethods
                        .datNamOhneHintErw(args[0])), paramsAkt);
            } else {
                aufn = new XMLAufnLesen(new File(args[0]), paramsAkt);
            }

            StaticMethods.log(StaticMethods.LOG_INFO, "Aufn.-Parameter: \n"
                    + aufn.getParams(), paramsAkt);
            aufn.getParams().complete();
        } catch (final Exception e) {
            StaticMethods.log(
                    StaticMethods.LOG_ERROR,
                    "Aufnahme konnte nicht geladen werden (Ursache:\n"
                        + e
                        + "\n)",
                    paramsAkt);
            e.printStackTrace();
        }
       
        TraceBetrachter steuer = new TraceBetrachter(
                aufn,
                aufn.getParams(),
                paramsAkt);
       
        // Speichere letzte Population.
        if (args.length > 1
            && args[1].toLowerCase().equals("nurletzter")) {
            steuer.traceListe.select(steuer.traceListe.getItemCount() - 1);
            steuer.itemStateChanged(null);
            steuer.speicherePop();
            StaticMethods.log(2, "Programmende.", paramsAkt);
            return;
        }
    }
}
TOP

Related Classes of eas.startSetup.marbBuilder.traceBetrachter.TraceBetrachter

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.