sim.app.antsvoronoi.AntsVoronoiWithUI.java Source code

Java tutorial

Introduction

Here is the source code for sim.app.antsvoronoi.AntsVoronoiWithUI.java

Source

/*
  Copyright 2009 by Sean Luke and George Mason University
  Licensed under the Academic Free License version 3.0
  See the file "LICENSE" for more information
 */

package sim.app.antsvoronoi;

import sim.engine.*;
import sim.display.*;
import sim.portrayal.Inspector;
import sim.portrayal.grid.*;
import sim.portrayal.network.NetworkPortrayal2D;
import sim.portrayal.network.SimpleEdgePortrayal2D;
import sim.portrayal.network.SpatialNetwork2D;
import sim.util.media.chart.ChartGenerator;
import sim.util.media.chart.BarChartGenerator;
import sim.util.media.chart.TimeSeriesChartGenerator;

import java.awt.*;
import javax.swing.*;

import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.Dataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.ui.TextAnchor;
//import org.jfree.data.general.

import java.util.EventObject;

public class AntsVoronoiWithUI extends GUIState {
    public Display2D display;
    public JFrame displayFrame;

    public BarChartGenerator barChart;
    public JFrame barChartFrame;

    public TimeSeriesChartGenerator timeSeriesChart;
    public XYSeries varianceSeries;
    public XYSeries stdDevSeries;
    public XYSeries skewnessSeries;
    public JFrame timeSeriesChartFrame;

    FastValueGridPortrayal2D homePheromonePortrayal = new FastValueGridPortrayal2D("Home Pheromone");
    FastValueGridPortrayal2D foodPheromonePortrayal = new FastValueGridPortrayal2D("Food Pheromone");
    FastValueGridPortrayal2D sitesPortrayal = new FastValueGridPortrayal2D("Site", true); // immutable
    FastValueGridPortrayal2D obstaclesPortrayal = new FastValueGridPortrayal2D("Obstacle", true); // immutable
    SparseGridPortrayal2D bugPortrayal = new SparseGridPortrayal2D();
    SparseGridPortrayal2D antHillPortrayal = new SparseGridPortrayal2D();
    FastObjectGridPortrayal2D voronoiGridPortrayal = new FastObjectGridPortrayal2D();
    NetworkPortrayal2D voronoiPortrayal = new NetworkPortrayal2D();

    public static void main(String[] args) {
        new AntsVoronoiWithUI().createController();
    }

    public AntsVoronoiWithUI() {
        super(new AntsForageVoronoi(System.currentTimeMillis()));
    }

    public AntsVoronoiWithUI(SimState state) {
        super(state);
    }

    // allow the user to inspect the model
    public Object getSimulationInspectedObject() {
        return state;
    } // non-volatile

    public Inspector getInstpector() {
        Inspector i = super.getInspector();
        i.setVolatile(true);
        return i;
    }

    public static String getName() {
        return "Ant Voronoi";
    }

    public void setupPortrayals() {
        AntsForageVoronoi af = (AntsForageVoronoi) state;

        // tell the portrayals what to portray and how to portray them
        homePheromonePortrayal.setField(af.toHomeGrid);
        homePheromonePortrayal.setMap(new sim.util.gui.SimpleColorMap(0, AntsForageVoronoi.LIKELY_MAX_PHEROMONE,
                // home pheromones are beneath all, just make them opaque
                Color.white, // new Color(0,255,0,0),
                new Color(0, 255, 0, 255)) {
            public double filterLevel(double level) {
                return Math.sqrt(Math.sqrt(level));
            }
        }); // map with custom level filtering
        foodPheromonePortrayal.setField(af.toFoodGrid);
        foodPheromonePortrayal.setMap(new sim.util.gui.SimpleColorMap(0, AntsForageVoronoi.LIKELY_MAX_PHEROMONE,
                new Color(0, 0, 255, 0), new Color(0, 0, 255, 255)) {
            public double filterLevel(double level) {
                return Math.sqrt(Math.sqrt(level));
            }
        }); // map with custom level filtering
        sitesPortrayal.setField(af.sites);
        sitesPortrayal
                .setMap(new sim.util.gui.SimpleColorMap(0, 1, new Color(0, 0, 0, 0), new Color(255, 0, 0, 255)));
        obstaclesPortrayal.setField(af.obstacles);
        obstaclesPortrayal
                .setMap(new sim.util.gui.SimpleColorMap(0, 1, new Color(0, 0, 0, 0), new Color(128, 64, 64, 255)));
        bugPortrayal.setField(af.buggrid);
        antHillPortrayal.setField(af.antHillGrid);

        //voronoiGridPortrayal.setField(af.voronoiGrid);
        //Color[] colorTable = new Color[1];
        //colorTable[0]=Color.black;
        //voronoiGridPortrayal.setMap(new sim.util.gui.SimpleColorMap(colorTable));
        // reschedule the displayer

        //voronoi
        //sep.setBaseWidth(0.5);
        //voronoiPortrayal.setPortrayalForAll(sep);
        voronoiPortrayal.setField(new SpatialNetwork2D(af.voronoiPoints, af.voronoiEdges));
        SimpleEdgePortrayal2D sep = new SimpleEdgePortrayal2D();

        display.reset();

        // redraw the display
        display.repaint();
    }

    public void start() {
        super.start(); // set up everything but replacing the display
        // set up our portrayals
        setupPortrayals();
        /*
              varianceSeries = new XYSeries("Population Variance Series");
              stdDevSeries = new XYSeries("Standard Deviation Series");
              skewnessSeries = new XYSeries("Skewedness Series");
                  
              timeSeriesChart.removeAllSeries();
              timeSeriesChart.addSeries(varianceSeries, null);
              timeSeriesChart.addSeries(stdDevSeries, null);
              timeSeriesChart.addSeries(skewnessSeries, null);
                  
              scheduleRepeatingImmediatelyAfter(new Steppable() {
                 public void step(SimState state) {
        double x = state.schedule.time();
        double y1 = ((AntHillGrid) antHillPortrayal.getField()).getFoodCountsPopulationVariance();
        double y2 = ((AntHillGrid) antHillPortrayal.getField()).getFoodCountsStandardDeviation();
        double y3 = ((AntHillGrid) antHillPortrayal.getField()).getFoodCountsSkewness();
            
        if (x >= state.schedule.EPOCH && x < state.schedule.AFTER_SIMULATION) {
           varianceSeries.add(x, y1, true);
           stdDevSeries.add(x, y2, true);
           skewnessSeries.add(x, y3, true);
           timeSeriesChart.updateChartLater(state.schedule.getSteps());
            }
        }
              });
                  
              barChart.removeAllSeries();
        */
        //double[] foodCounts = ((AntHillGrid) (antHillPortrayal.getField())).getFoodCountsAsDouble();
        /*for(int i=0; i<foodCounts.length; i++) {
           System.out.print(i + ": " + foodCounts[i] + " ");
        }
        System.out.print("\n");*/
        /*
        String[] antHillStrings = new String[foodCounts.length];
        for (int i=0; i<antHillStrings.length; i++) {
           StringBuilder sb = new StringBuilder();
           sb.append("");
           sb.append(i);
           String s = sb.toString();
           antHillStrings[i]=s;
        }
            
        int totalFood = 0;
        for(int i=0;i<foodCounts.length;i++) totalFood+=foodCounts[i];
            
        barChart.addSeries(foodCounts, antHillStrings, "Ant Hills", null);   
            
        */
        /*scheduleRepeatingImmediatelyAfter(new Steppable() {
           public void step(SimState state) {   
            
        double[] foodCounts2 = ((AntHillGrid) (antHillPortrayal.getField())).getFoodCountsAsDouble();
        */
        /*for(int i=0; i<foodCounts2.length; i++) {
           System.out.print(i + ": " + foodCounts2[i] + " ");
        }
        System.out.print("\n");*/
        /*
        String[] antHillStrings2 = new String[foodCounts2.length];
        for (int i=0; i<antHillStrings2.length; i++) {
           StringBuilder sb = new StringBuilder();
           sb.append("");
           sb.append(i);
           String s = sb.toString();
           antHillStrings2[i]=s;
        }
        //barChart.updateSeries(0, foodCounts2, antHillStrings2);
        //barChart.updateChartLater(state.schedule.getSteps());
            
        }
        });*/
    }

    public void load(SimState state) {
        super.load(state);
        // we now have new grids. Set up the portrayals to reflect that
        setupPortrayals();
    }

    public void init(Controller c) {
        super.init(c);

        // Make the Display2D. We'll have it display stuff later.
        display = new Display2D(400, 400, this); // at 400x400, we've got 4x4
        // per array position
        displayFrame = display.createFrame();
        c.registerFrame(displayFrame); // register the frame so it appears in
        // the "Display" list
        displayFrame.setVisible(true);

        // attach the portrayals from bottom to top
        display.attach(homePheromonePortrayal, "Pheromones To Home");
        display.attach(foodPheromonePortrayal, "Pheromones To Food");
        display.attach(sitesPortrayal, "Site Locations");
        display.attach(obstaclesPortrayal, "Obstacles");
        display.attach(bugPortrayal, "Agents");
        display.attach(antHillPortrayal, "Ant Hills");
        display.attach(voronoiPortrayal, "Voronoi");
        // specify the backdrop color -- what gets painted behind the displays
        display.setBackdrop(Color.white);

        /*
        barChartFrame = createBarChartFrame();
        c.registerFrame(barChartFrame);
            
        timeSeriesChartFrame = createTimeSeriesChartFrame();
        c.registerFrame(timeSeriesChartFrame);   
        */
    }

    public JFrame createTimeSeriesChartFrame() {
        timeSeriesChart = new TimeSeriesChartGenerator();
        timeSeriesChart.setTitle("Standard Deviation of Food for Ant Hills");
        timeSeriesChart.setXAxisLabel("Value");
        timeSeriesChart.setYAxisLabel("Time");
        timeSeriesChartFrame = timeSeriesChart.createFrame();
        timeSeriesChartFrame.setVisible(true);
        timeSeriesChartFrame.pack();
        return timeSeriesChartFrame;
    }

    public JFrame createBarChartFrame() {
        barChart = new BarChartGenerator();
        barChart.setTitle("Number of Food Closest to Each Ant Hill");
        barChart.setYAxisLabel("Food Counts");
        barChart.setXAxisLabel("Ant Hill");

        CategoryPlot plot = barChart.getChart().getCategoryPlot();
        ValueAxis axis = plot.getRangeAxis();
        axis.setLowerBound(0);
        AntsForageVoronoi af = (AntsForageVoronoi) state;
        axis.setUpperBound(af.numFood * .75);

        BarRenderer renderer = new BarRenderer();
        renderer = (BarRenderer) plot.getRenderer();
        ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.INSIDE6, TextAnchor.BOTTOM_CENTER);//, TextAnchor.BOTTOM_CENTER, 0.0);
        renderer.setPositiveItemLabelPosition(position);
        renderer.setNegativeItemLabelPosition(position);
        plot.setRenderer(renderer);

        barChartFrame = barChart.createFrame();
        barChartFrame.setVisible(true);
        barChartFrame.setTitle("Bar Chart");
        return barChartFrame;
    }

    public void quit() {
        super.quit();

        // disposing the displayFrame automatically calls quit() on the display,
        // so we don't need to do so ourselves here.
        if (displayFrame != null)
            displayFrame.dispose();
        displayFrame = null; // let gc
        display = null; // let gc
    }

}