swarm-support
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Entry level Java


From: Tim Howe
Subject: Re: Entry level Java
Date: Wed, 17 Oct 2001 13:35:45 -0700

Greetings,

I have been working on making jheatbugs more understandable by amplifying
the comments and by tightening up the code, with the goal of making it a
reasonable "first program" for learning Swarm.

I have appended a sample file below (HeatbugModelSwarm.java). Invoke
"javadoc HeatbugModelSwarm.java" and see what you get in
HeatbugModelSwarm.html. I'll provide more, as it all evolves, to anyone who
would like a copy.

My documentation does assume that the reader has a general understanding of
Java. As for Java tutorials: Why not rely on the tutorials provided by the
Java community? Try
http://java.sun.com/docs/books/tutorial/?frontpage-spotlight. Or
"Introduction to Java for C and C++ Programmers" at
http://www6.software.ibm.com/reg/java/ijcc++p-i.

- Tim

And here is HeatbugModelSwarm.java:
------------------------------------------------
// Java Heatbugs application. Copyright © 1999-2000 Swarm Development Group.
// This library is distributed without any warranty; without even the
// implied warranty of merchantability or fitness for a particular
// purpose.  See file COPYING for details and terms of copying.

// All added comments copyright 2001 Timothy Howe. All rights reserved.

import swarm.Globals;
import swarm.Selector;
import swarm.defobj.Zone;
import swarm.defobj.SymbolImpl;

import swarm.defobj.FArguments;
import swarm.defobj.FArgumentsImpl;
import swarm.defobj.FCall;
import swarm.defobj.FCallImpl;

import swarm.activity.Activity;
import swarm.activity.ActionGroup;
import swarm.activity.ActionGroupImpl;
import swarm.activity.Schedule;
import swarm.activity.ScheduleImpl;
import swarm.activity.FActionForEach;

import swarm.objectbase.Swarm;
import swarm.objectbase.SwarmImpl;
import swarm.objectbase.VarProbe;
import swarm.objectbase.MessageProbe;
import swarm.objectbase.EmptyProbeMapImpl;

import java.util.ArrayList;

import swarm.space.Grid2d;
import swarm.space.Grid2dImpl;

/**
Since this class is the core of the heatbugs simulation, we present
here an overview of the entire application.

<p>
The following diagram depicts the cardinality of the custom classes of the
heatbugs application:

<xmp>
|                     +-----------------+
|                     | StartHeatbugs   |
|                     +-----------------+
|                              | 1
|                              |
|              +---------------+-----------+
|              |                           |
|              | 1                         | 1
|   +---------------------+          +------------------------+
|   | HeatbugBatchSwarm   |  - OR -  | HeatbugObserverSwarm   |
|   | extends             |          | extends                |
|   | SwarmImpl           |          | GUISwarmImpl           |
|   +---------------------+          +------------------------+
|              | 1                         | 1
|              |                           |
|              +---------------+-----------+
|                              |
|                              | 1
|                    +---------------------+
|                    | HeatbugModelSwarm   |-----------------+
|                    | extends             |                 |
|                    | SwarmImpl           |                 |
|                    +---------------------+ 1               |
|                              | 1                           | 1
|                              |                     +---------------+
|                              |                     | HeatSpace     |
|                              |                     | extends       |
|                              |                     | Diffuse2dImpl |
|                              |                     +---------------+
|                              | 0..n                        | 1
|                      +-----------------+                   |
|                      |     Heatbug     |-------------------+
|                      +-----------------+ 0..n
</xmp>

The class HeatbugModelSwarm
represents the heatbugs model, which is the core class of the heatbugs
simulation. Four of the five other custom classes involved
in the simulation are:

 <dir>
 StartHeatbugs: the class with the main() method that kicks off the
simulation.
 Depending on command-line options,
 StartHeatbugs creates either a HeatbugBatchSwarm or a HeatbugObserverSwarm
 in which to present the view of the HeatbugModelSwarm.
 </dir>

 <dir>
 HeatbugBatchSwarm:
 the non-GUI observer: a view of the model presented through
 text output. <i>Batch</i> does not refer to a
 batch of Heatbugs, but rather to batch mode as opposed to interactive mode.
 HeatbugBatchSwarm writes to files and to standard output.
 </dir>

 <dir>
 HeatbugObserverSwarm:
 the GUI observer: a view of the model presented through
 graphs and plots.
 </dir>

 <dir>
 Heatbug: the class that defines the individual
 agents. A Heatbug has data (including its position in 2-dimensional
 space), behavior (including the ability to move in 2-dimensional space),
 and the ability to perceive quantities of heat in its immediate
neighborhod.
 </dir>

We use two 2-dimensional data structures in the model: one to record
the positions of the Heatbugs, and another, of identical size, to record the
heat that the Heatbugs produce as well as seek.
The following diagram provides a rough illustration of the two data
structures:

<xmp>
^ Position:                           Heat:
| +---+---+---+---+---+---+---+---+   +---+---+---+---+---+---+---+---+
| |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
| +---+---+---+---+---+---+---+---+   +---+---+---+---+---+---+---+---+
| |   |   |   |   |   |   |   |   |   |   | h | h | h |   |   |   |   |
| +---+---+---+---+---+---+---+---+   +---+---+---+---+---+---+---+---+
| |   |   | b |   |   |   |   |   |   |   | h | h | h |   |   |   |   |
| +---+---+---+---+---+---+---+---+   +---+---+---+---+---+---+---+---+
| |   |   | b |   |   |   |   |   |   |   | h | h | h |   |   |   |   |
| +---+---+---+---+---+---+---+---+   +---+---+---+---+---+---+---+---+
| |   |   |   |   |   |   |   |   |   |   | h | h | h | h | h | h |   |
| +---+---+---+---+---+---+---+---+   +---+---+---+---+---+---+---+---+
y |   |   |   |   |   | b |   |   |   |   |   |   |   | h | h | h |   |
| +---+---+---+---+---+---+---+---+   +---+---+---+---+---+---+---+---+
| |   |   |   |   |   |   |   |   |   |   |   |   |   | h | h | h |   |
| +---+---+---+---+---+---+---+---+   +---+---+---+---+---+---+---+---+
0 |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
| +---+---+---+---+---+---+---+---+   +---+---+---+---+---+---+---+---+
| --0-------x--------------------->   --0-------x--------------------->
</xmp>

where b represents a bug and h represents a non-zero quantity of heat.

<p>
For the positional data, we use Swarm's class Grid2d. For the heat data,
we use Swarm's Diffuse2dImpl, whose behavior includes the dissipation
and "evaporation" of heat.
Rather than use Diffuse2dImpl directly, we need to specialize it, so
we define HeatSpace, the last of the six custom classes involved in the
Heatbug simulation:

<dir>
HeatSpace: a 2-dimensional array of heat values.
We don't specify the heat units, but they might be degrees Celsius.
HeatSpace inherits dissipation and evaporation from Diffuse2dImpl, and it
also provides the ability to
report the hottest or coldest cells within a neighborhood.
</dir>

*/

public class HeatbugModelSwarm extends SwarmImpl
{

public int numBugs = 100;

public double evaporationRate = 0.99; // 0 = maximum, 1 = minimum retention
public double diffuseConstant = 1.0; // 0 = minimum, 1 = maximum diffusion
// "newHeat = evapRate * (self + diffuseConstant*(nbdavg - self)) where
nbdavg
// is the weighted average of the 8 neighbours" -- but what does "weighted"
// mean?
public int worldXSize = 80;
public int worldYSize = 80;
public int minIdealTemp = 17000;
public int maxIdealTemp = 31000;
public int minOutputHeat = 3000;
public int maxOutputHeat = 10000;
public boolean randomizeHeatbugUpdateOrder = false;
public double randomMoveProbability = -99.99;

public ActionGroup modelActions;
public Schedule modelSchedule;

public ArrayList heatbugList;

public Grid2d world;
public HeatSpace heatSpace;

private boolean _immobile = false;
// ... We can set _immobile = true to see what happens when Heatbugs never
move.
 public boolean getImmobile () { return _immobile; }
 public void setImmobile (boolean immobile) { _immobile = immobile; }

public HeatbugModelSwarm (Zone aZone)
{
    super (aZone);

    // Build a customized probe map using a "local" subclass (a
    // special kind of Java "inner class") of the EmptyProbeMapImpl
    // class. Without a probe map, the default is to show all
    // variables and messages. Here we choose to customize the
    // appearance of the probe, to display a nicer interface.

    class HeatbugModelProbeMap extends EmptyProbeMapImpl
    {
        private VarProbe probeVariable (String name)
        {
            return
             Globals.env.probeLibrary.getProbeForVariable$inClass
             (name, HeatbugModelSwarm.this.getClass ());
        }
        private MessageProbe probeMessage (String name)
        {
            return
             Globals.env.probeLibrary.getProbeForMessage$inClass
             (name, HeatbugModelSwarm.this.getClass ());
        }
        private void addVar (String name)
        { addProbe (probeVariable (name)); }
        private void addMessage (String name)
        { addProbe (probeMessage (name)); }
        public HeatbugModelProbeMap (Zone _aZone, Class aClass)
        {
            super (_aZone, aClass);
            addVar ("numBugs");
            addVar ("diffuseConstant");
            addVar ("worldXSize");
            addVar ("worldYSize");
            addVar ("minIdealTemp");
            addVar ("maxIdealTemp");
            addVar ("minOutputHeat");
            addVar ("maxOutputHeat");
            addVar ("evaporationRate");
            addVar ("randomMoveProbability");
            addMessage ("toggleRandomizedOrder");
            addMessage ("addHeatbug:");
        }
    } /// class HeatbugModelProbeMap

    // Now, install our custom probeMap class directly into the
    // probeLibrary
    Globals.env.probeLibrary.setProbeMap$For
     (new HeatbugModelProbeMap (aZone, getClass ()), getClass ());
} /// constructor

FActionForEach actionForEach;

// The remaining methods provide access to the objects inside the
// ModelSwarm. These objects are the ones visible to other
// classes via message call. In theory we could just let other
// objects use Probes to read our state, but message access is
// frequently more convenient.

public ArrayList getHeatbugList ()
{
    return heatbugList;
}

public Grid2d getWorld ()
{
    return world;
}

public HeatSpace getHeatSpace ()
{
    return heatSpace;
}

public boolean toggleRandomizedOrder ()
{
    randomizeHeatbugUpdateOrder = !randomizeHeatbugUpdateOrder;
    syncUpdateOrder ();
    return randomizeHeatbugUpdateOrder;
}

public void syncUpdateOrder ()
{
    if (actionForEach != null)
        actionForEach.setDefaultOrder
         (randomizeHeatbugUpdateOrder
          ? Globals.env.Randomized
          : Globals.env.Sequential
         );
}

/**
If Heatbugs gave birth or immigrated, you could use this method to introduce
them into the model.
*/
public Object addHeatbug (Heatbug bug)
{
    heatbugList.add (bug);
    return this;
}

public Object buildObjects ()
{
    // Ask our parent class to build anything it needs to:
    super.buildObjects();

    // Create a HeatSpace, which is a 2-dimensional array of heat values:
    heatSpace = new HeatSpace
     (getZone (), worldXSize, worldYSize, diffuseConstant, evaporationRate);

    // Create a grid to represent Heatbug positions:
    world = new Grid2dImpl (getZone (), worldXSize, worldYSize);

    // Create a list to keep track of the Heatbugs:
    heatbugList = new ArrayList ();

 // We will let two or more Heatbugs occupy the same cell:
    world.setOverwriteWarnings (false);

    // Now a loop to create a bunch of heatbugs.

    for (int i = 0; i < numBugs; i++)
    {
        Heatbug hbug;
        int idealTemp, outputHeat;

        // Choose a random ideal temperature, output heat
        // from the specified range (model parameters).
        idealTemp =
         Globals.env.uniformIntRand.getIntegerWithMin$withMax
          (minIdealTemp, maxIdealTemp);
        outputHeat =
         Globals.env.uniformIntRand.getIntegerWithMin$withMax
          (minOutputHeat, maxOutputHeat);

        // Create the heatbug, with a standard Java constructor
        hbug = new Heatbug (world, heatSpace, this);

        // Add the bug to the end of the list.
        heatbugList.add (hbug);

        // Now initialize the rest of the heatbug's state.

        hbug.setIdealTemperature (idealTemp);
        hbug.setOutputHeat (outputHeat);
        hbug.setRandomMoveProbability (randomMoveProbability);
        // System.out.println ("I set randomMoveProbability to " +
randomMoveProbability);
        if (randomMoveProbability == -99.99)
        {
            System.out.println ("Because randomMoveProbability is still " +
randomMoveProbability + ", we know that Observer did not read the SCM
properly.");
            randomMoveProbability = 0.5;
            System.out.println ("So I have set randomMoveProbability
arbitrarily to " + randomMoveProbability + ".");
        }

        // Initialize the location of the Heatbug. Collisions are OK:
        hbug.setX$Y
         (Globals.env.uniformIntRand.getIntegerWithMin$withMax
           (0, (worldXSize-1)),
          Globals.env.uniformIntRand.getIntegerWithMin$withMax
           (0, (worldYSize-1))
         );
        // Use this instead, if you want to see what happens when they all
        // start in one cell: hbug.setX$Y (worldXSize/2, worldYSize/5);
    } /// for each Heatbug

    return this;
} /// buildObjects()

public Object buildActions ()
{
    super.buildActions();

    // Create the list of simulation actions. We put these in
    // an action group, because we want these actions to be
    // executed in a specific order, but these steps should
    // take no (simulated) time. The M(foo) means "The message
    // called <foo>". You can send a message To a particular
    // object, or ForEach object in a collection.

    // Note we update the heatspace in two phases: first run
    // diffusion, then run "updateWorld" to actually enact the
    // changes the heatbugs have made. The ordering here is
    // significant!

    // Note also, that with the additional
    // "randomizeHeatbugUpdateOrder" boolean we can
    // randomize the order in which the bugs actually run
    // their step rule.  This has the effect of removing any
    // systematic bias in the iteration throught the heatbug
    // list from timestep to timestep

    // By default, all "createActionForEach" modelActions have
    // a default order of Sequential, which means that the
    // order of iteration through heatbugList will be
    // identical (assuming the list order is not changed
    // by some other process).

    modelActions = new ActionGroupImpl (getZone ());

    try
    {
    modelActions.createActionTo$message
     (heatSpace, new Selector (heatSpace.getClass (), "stepRule", false));
  // "stepRule" is the name of Diffuse2d's sole behavioral method. In other
  // words, it's the only thing that a Diffuse2d knows how to do at any
  // step of the simulation. In particular, it applies diffusion and
  // evaporation.
    } catch (Exception e)
    { System.err.println ("Exception stepRule: " + e.getMessage ()); }

    try
    {
    Heatbug proto = (Heatbug) heatbugList.get (0);
    Selector sel = new Selector
     (proto.getClass (), "heatbugStep", false);
    actionForEach = modelActions.createFActionForEachHomogeneous$call
     (heatbugList,
      new FCallImpl (this, proto, sel, new FArgumentsImpl (this, sel, true))
     );
    } catch (Exception e)
    { e.printStackTrace (System.err); }

    syncUpdateOrder ();

    try
    {
    modelActions.createActionTo$message
     (heatSpace, new Selector (heatSpace.getClass (), "updateLattice",
false));
    } catch (Exception e)
    { System.err.println ("Exception updateLattice: " + e.getMessage ()); }

    /*
    This simulation contains only one Schedule, and the Schedule contains
only
    one ActionGroup, and the ActionGroup contains two Actions.
    */
    modelSchedule = new ScheduleImpl
     (getZone (),
      1
      // ... The repeat interval is 1, so the schedule will
      // execute every step of the simulation.
     );
    modelSchedule.at$createAction
     (0,
      // ... Execute action group at time 0 relative to the beginning of the
      // schedule.
      modelActions
     );

    return this;
} /// buildActions()

/**
This method activates the schedules so they're ready to run.

@param swarmContext (in)
    the larger context within which this model is activated; a model swarm
    usually runs in the context of an observer swarm or a super-model swarm
*/
public Activity activateIn (Swarm swarmContext)
{
    super.activateIn (swarmContext);
    // Add our own schedule to the base class's schedule:
    modelSchedule.activateIn (this);
    // Return the schedule that we inherit from the base class:
    return getActivity ();
} /// activateIn()

} /// class HeatbugModelSwarm
------------------------------------------------


----- Original Message -----
From: "Methot, Chris" <address@hidden>
To: <address@hidden>
Sent: Wednesday, October 17, 2001 10:59 AM
Subject: Entry level Java


> I am working an issue that can only be solved by simulations.  We can't
> really build and test it and if we could there is little likelihood it
> would be stable enough to be repeatable at this point.  As a novice I
> hit on Swarm and decided to use Java because of its insistence on
> correct programming technique (garbage collection and logic checking).
> I am just completing my first Java course (I can flash and scroll text
> with the best of them).
>
> Now I am looking for Java samples along the lines of Hello_world and
> simpleCBug.  Jheatbugs and Jmousetrap are a little too ambitious for me.
> I tried "porting" simpleCBug but got hung up on minimum restrictions for
> Java Swarm like main().  I tried the SDG csss tutorial sample but the
> tar file has no Make file, many unneeded Java files and I am not able to
> get it to compile.
>
> I found that in January of 2000 you felt that Java was not a good
> candidate for novice programmers (me).  Despite that, your slides from
> SDG csss indicate that it seems superior for that purpose.  I believe
> you felt that there would be a time when that would change.  I checked
> the mail archives to see if this had changed.
>
> 2 Questions:
> Has there been any additional simple self-teaching progressive Java
> examples added since January of 2000?
>
> Would it be possible (with some guidance) to port Hello_world or
> simpleCBug (ultimately ending up with the examples I need) or perhaps
> they are designed to teach Objective C++ Swarm and have lots of
> extraneous stuff not needed in Java Swarm?
>
> Thanks!
>
> Chris Methot
>
>
>                   ==================================
>    Swarm-Support is for discussion of the technical details of the day
>    to day usage of Swarm.  For list administration needs (esp.
>    [un]subscribing), please send a message to <address@hidden>
>    with "help" in the body of the message.
>
>

                  ==================================
   Swarm-Support is for discussion of the technical details of the day
   to day usage of Swarm.  For list administration needs (esp.
   [un]subscribing), please send a message to <address@hidden>
   with "help" in the body of the message.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]