⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 modelswarm.java

📁 本源码应用于Java的JDK1.4.2版本+Swarm2.2 程序在Cygwin终端运行
💻 JAVA
字号:
import swarm.Globals;
import swarm.Selector;
import swarm.defobj.Zone;
import swarm.defobj.SymbolImpl;

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

import swarm.activity.Activity;
import swarm.activity.ScheduleActivity;
import swarm.activity.ActionGroup;
import swarm.activity.ActionGroupImpl;
import swarm.activity.Schedule;
import swarm.activity.ScheduleImpl;
import swarm.activity.ActionForEach;

import swarm.objectbase.Swarm;
import swarm.objectbase.SwarmImpl;
import swarm.objectbase.SwarmObjectImpl;

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

import java.util.ArrayList;
import  swarm.collections.List;
import  swarm.collections.ListImpl;
import  swarm.collections.Index;
import  swarm.collections.ListShufflerImpl;
import swarm.SwarmEnvironmentImpl;
import swarm.random.UniformIntegerDistImpl;

import swarm.space.Grid2d;
import swarm.space.Grid2dImpl;
import swarm.space.Discrete2dImpl;
import swarm.space.Discrete2d;

public class ModelSwarm extends SwarmImpl
{
// The model swarm encapsulates all the objects that go into the Sugarscape
// model. In the simplest case, this is basically a list of agents, a
// sugarspace world, and various parameters.
//parameter and method for the model
  public int numAgents;

  public int alpha;//growth rate for sugar
  public int replacement;//use replacement rule?
  public int maxVision , maxMetabolism;
  public int minInitialSugar,maxInitialSugar;
  public int deathAgeMin,deathAgeMax;
  public int worldXSize,worldYSize;
  final String datafile="env100.pgm";//const char
  //Objects in the list
  protected  List  agentList;
  //protected Shuffle  _shuffler;
  protected SugarSpace _sugarspace;
  ListImpl reaperQueue;
  public boolean randomizeUpdateOrder;
  public  Grid2dImpl world;
  //schedule stuff.
  protected Schedule    _modelSchedule;
  protected ActionGroup _modelActions;
  ActionForEach  actionForEach;
 //methods to handle the agents in the world.
 public ModelSwarm(Zone aZone)
 {
    super(aZone);
    worldXSize = 100;
    worldYSize = 100;
    numAgents = 100;
    alpha = 1;
    replacement = 0;
    maxMetabolism=4;
    maxVision = 6;
    minInitialSugar = 5;
    maxInitialSugar =25;
    deathAgeMin = 99998;
    deathAgeMax = 100000;

  // final String dataPath =arg.getAppDataPath();//const char*
   //  datafile = "env.pgm";//const char*

     EmptyProbeMapImpl  _probeMap = new EmptyProbeMapImpl(aZone,getClass());
    _probeMap.addProbe(probeVariable("numAgents"));
    _probeMap.addProbe(probeVariable("worldXSize"));
    _probeMap.addProbe(probeVariable("worldYSize"));
    _probeMap.addProbe(probeVariable("alpha"));
    _probeMap.addProbe(probeVariable("replacement"));
    _probeMap.addProbe(probeVariable("maxMetabolism"));
    _probeMap.addProbe(probeVariable("maxVision"));
    _probeMap.addProbe(probeVariable("minInitialSugar"));
    _probeMap.addProbe(probeVariable("maxInitialSugar"));
    _probeMap.addProbe(probeVariable("deathAgeMin"));
    _probeMap.addProbe(probeVariable("deathAgeMax"));
  //  _probeMap.addProbe(probeVariable("datafile"));

     Globals.env.probeLibrary.setProbeMap$For
                                 (_probeMap, getClass ());
}
// Create a new agent at random and put it in the world.


public  Object  buildObjects()
{
       super.buildObjects();
       world=new Grid2dImpl (getZone (), worldXSize, worldYSize);
          //first,set up the object that is the sugarscape-environment.
          _sugarspace = new  SugarSpace(getZone(),
                                       worldXSize,worldYSize);
         _sugarspace.setAgentGrid(world);
         _sugarspace.setMaxSugar(_sugarspace);
        // _sugarspace.setSugarGrowRate(alpha);
        // _sugarspace.agentGrid = new Grid2dImpl(getZone(), worldXSize, worldYSize);
         //_sugarspace.setDiscrete2d$fromFile(world,datafile);
        // _sugarspace.copyDiscrete2d$toDicrete2d(_sugarspace.sugar,
          //                                      _sugarspace.maxSugar);

          //create a List to store all the  agents
           agentList = new ListImpl(getZone());

           world.setOverwriteWarnings(false);
          for (int i = 0; i < numAgents; i++)
            this.addNewRandomAgent();
          world.setOverwriteWarnings(true);
          // Create a "reaper queue" to manage agent deaths
          reaperQueue = new ListImpl(Globals.env.globalZone);
          // And create a shuffler object to randomize agent order

            return this;
 }
 public   Object addNewRandomAgent()
 {
   int x,y;
   SugarAgent agent;
   //Create the agent object
    agent = new SugarAgent(world, _sugarspace);
    agent.setModelSwarm(this);
   // Give the agent a random initial position and parameters.
    x = Globals.env.uniformIntRand.getIntegerWithMin$withMax(0,worldXSize);
    y = Globals.env.uniformIntRand.getIntegerWithMin$withMax(0,worldYSize);
    _sugarspace.addAgent$atX$Y(agent,x,y);
    agent.setcurrentsugar(Globals.env.uniformIntRand.getIntegerWithMin$withMax(minInitialSugar,maxInitialSugar));
    agent.setMetabolism(Globals.env.uniformIntRand.getIntegerWithMin$withMax(1,maxMetabolism));
    agent.setVision(Globals.env.uniformIntRand.getIntegerWithMin$withMax(1,maxVision));
    agent.setDeathAge(Globals.env.uniformIntRand.getIntegerWithMin$withMax(deathAgeMin,deathAgeMax));
    this.agentBirth(agent);
     return this;
}
public boolean toggleRandomizedOrder () {
       randomizeUpdateOrder =
         ((randomizeUpdateOrder == false) ? true : false);
       return (randomizeUpdateOrder);
 }


public Object   buildActions()
{
     super.buildActions();
    //   One time tick, a set of several actions:
    //   randomize the order of agent updates (to be fair)
    //   update all the agents
    //   kill off the agents who just died
    //   update the sugar on the world
     ActionGroupImpl modelActions = new ActionGroupImpl(getZone());
    try
       {
          modelActions.createActionTo$message
          (_sugarspace,new Selector (_sugarspace.getClass(),"updateSugar",false));
      }catch(Exception e){}

  try{
      Selector sel= new Selector(Class.forName ("SugarAgent"), "step", false);
      actionForEach =
        modelActions.createActionForEach$message(this.agentList, sel);
      if (randomizeUpdateOrder == true)
        actionForEach.setDefaultOrder (Globals.env.Randomized);
    }  catch (Exception e) {
      System.err.println("Exception agent step : " + e.getMessage ());
    }

   try{
          modelActions.createActionTo$message
          (this,new Selector(this.getClass(),"reapAgents",false));

       }catch(Exception e)
        {  System.err.println("Exception"+"returns"+e.getMessage()); }


       // The schedule is just running our actions over and over again
        _modelSchedule = new ScheduleImpl(getZone(),1);
        _modelSchedule.at$createAction(0,  modelActions);
        // ... The Schedule will execute ActionGroup modelActions at time
      // value 0 relative to the beginning of the Schedule.
       return this;
}
public Activity activateIn(Swarm swarmContext)
{
    super.activateIn(swarmContext);
    // Then activate the schedule in ourselves.
     _modelSchedule.activateIn(this);
     return getActivity();
}
 //methods to handle the birth and death of agents
 public Object	agentBirth(SugarAgent agent)
 {
      agentList.addLast(agent);
     return this;
 }
 public Object agentDeath(SugarAgent agent)
 {
     reaperQueue.addLast(agent);
    if(replacement==0)//replacement rule R
    this.addNewRandomAgent();
    return this;
 }
 // remove all the agents on the reaperQueue from the agentList
// This allows us to defer the death of an agent until it's safe to
// remove it from the list.

  public  Object shuffleList()
{
  int j,k;
  Object temp;
  j=agentList.getCount();
  while(j>1){
    k=Globals.env.uniformIntRand.getIntegerWithMin$withMax(0,j-1);//return an integer
    j--;
    temp =agentList.atOffset(k);
    agentList.atOffset$put(k,agentList.atOffset(j));
    agentList.atOffset$put(j,temp);
  }
  return  this;
}




public Object reapAgents()
{
        SugarAgent agents;

        while (reaperQueue.getCount() != 0)
            {
            agents = (SugarAgent)reaperQueue.removeFirst();
            agentList.remove(agents);
            agents.drop();
          /*  System.out.println("agents " + agents.ID +
                               " has died of hunger.");*/
            numAgents -= 1;
            }
        // Check the number of remaining bugs and quit the simulation
        // if there are none left, by terminating the ModelSwarm
        // activity.
        if (agentList.getCount() == 0)
            getActivity().terminate();
            return this;
}

/*public Object reapAgents()
{
   Index agent;//ListIndex include begin
   Index index;//ListImpl include next/drop
   index = reaperQueue.begin(getZone());//new ListImpl(getZone());
   while((agent=(Index) index.next())!=null)
   {
          agentList.remove(agent);
          agent.drop();
    }
    reaperQueue.removeAll();//members not exist,but resource hold
    return this;
}*/

//Accessor functions
protected SugarSpace getSugarSpace()
{
  return _sugarspace;
}
protected Object getAgentList()
{
   return  agentList;
}

protected MessageProbe probeMessage (String name)
 {
    return Globals.env.probeLibrary.getProbeForMessage$inClass
     (name, ModelSwarm.this.getClass ());
 }

protected VarProbe probeVariable (String name)
 {
    return Globals.env.probeLibrary.getProbeForVariable$inClass
     (name, ModelSwarm.this.getClass ());
 }
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -