Пример #1
0
  public void moveTowards(GridPoint pt) {
    // only move if we are not already in this grid location
    if (!pt.equals(grid.getLocation(this))) {
      NdPoint myPoint = space.getLocation(this);
      NdPoint otherPoint = new NdPoint(pt.getX(), pt.getY());
      double angle = SpatialMath.calcAngleFor2DMovement(space, myPoint, otherPoint);
      space.moveByVector(this, 1, angle, 0);
      myPoint = space.getLocation(this);
      grid.moveTo(this, (int) myPoint.getX(), (int) myPoint.getY());

      moved = true;
    }
  }
 /**
  * Returns true if a grid point of the map is free (with no car)
  *
  * @param p
  * @return
  */
 private boolean isFree(GridPoint p) {
   int count = 0;
   Iterable<TrafficElement> elements = map.getObjectsAt(p.getX(), p.getY());
   for (TrafficElement elem : elements) {
     count++;
   }
   return count == 0;
 }
  /** Executes step method for each car and adds them to their new position */
  private void moveCars() {
    this.carsToRemove.clear();
    this.positionsToCheck.clear();

    // Cars compute their new position
    for (Car car : travelingCars) car.move();

    // Move cars in the map
    for (Car car : travelingCars) {
      int x = car.getX();
      int y = car.getY();

      // Move car
      if (!this.isPositionOutOfBounds(x, y)) {
        map.moveTo(car, x, y);
        this.addPositionToCheck(car.getPosition().getGridPoint());
      }
      // Car moved out of the map. Add for removal
      else {
        this.addCarToRemove(car);
      }
    }

    // Remove cars out of bounds
    for (Car car : this.carsToRemove) {
      remove(car);
    }

    // Manage collisions
    for (String posId : this.positionsToCheck.keySet()) {
      GridPoint pos = this.positionsToCheck.get(posId);
      int x = pos.getX();
      int y = pos.getY();

      if (this.getNumElements(x, y) > 1) {
        Collision col = new Collision(x, y, map);
        Iterable<TrafficElement> elements = map.getObjectsAt(x, y);
        remove(elements);

        context.add(col);
        map.moveTo(col, x, y);

        this.collisions.add(col);
      }
    }
  }
Пример #4
0
  public float[] getLocation(Object obj) {
    GridPoint gpoint = grid.getLocation(obj);
    int[] origin = grid.getDimensions().originToIntArray(null);
    float xOffset = (float) origin[0];
    float yOffset = (float) origin[1];

    if (gpoint == null) {
      point[0] = Float.POSITIVE_INFINITY;
      point[1] = Float.POSITIVE_INFINITY;
      return point;
    }

    float x = (float) (gpoint.getX() + xOffset) * cellSize;
    float y = (float) (gpoint.getY() + yOffset) * cellSize;
    point[0] = x;
    point[1] = y;
    return point;
  }
  /**
   * @param x
   * @param y
   * @return
   */
  private int getNumElements(int x, int y) {
    Iterable<TrafficElement> elements = map.getObjectsAt(x, y);
    int elemsCount = 0;

    Iterator<TrafficElement> iterator = elements.iterator();
    while (iterator.hasNext()) {
      iterator.next();
      elemsCount++;
    }
    return elemsCount;
  }
  /**
   * Constructor
   *
   * @param context
   * @param grid
   * @param normLayer
   */
  public CarMap_Original(
      Context<TrafficElement> context,
      Grid<TrafficElement> map,
      PredicatesDomains predDomains,
      CarContextFactory carContextFactory,
      TrafficFactFactory factFactory) {

    super(map.getDimensions().getHeight(), map.getDimensions().getWidth());

    this.predDomains = predDomains;
    this.carContextFactory = carContextFactory;
    this.factFactory = factFactory;

    this.xDim = map.getDimensions().getWidth();
    this.yDim = map.getDimensions().getHeight();
    this.context = context;
    this.map = map;

    this.availableCars = new LinkedList<Car>();
    this.travelingCars = new ArrayList<Car>();
    this.allCars = new ArrayList<Car>();
    this.carsToRemove = new ArrayList<Car>();
    this.collisions = new ArrayList<Collision>();
    this.collisionsToRemove = new ArrayList<Collision>();
    this.positionsToCheck = new HashMap<String, GridPoint>();

    this.leftLane = (int) (Math.floor(0.5 * xDim)) - 1;
    this.rightLane = leftLane + 2;
    this.lowerLane = (int) (Math.floor(0.5 * yDim)) - 1;
    this.upperLane = lowerLane + 2;

    this.startRow = 0;
    this.stopRow = yDim - 1;
    this.startCol = 0;
    this.stopCol = xDim - 1;

    this.generateCars();
  }
Пример #7
0
  public void infect() {
    GridPoint pt = grid.getLocation(this);
    List<Object> humans = new ArrayList<Object>();
    for (Object obj : grid.getObjectsAt(pt.getX(), pt.getY())) {
      if (obj instanceof Human) {
        humans.add(obj);
      }
    }

    if (humans.size() > 0) {
      int index = RandomHelper.nextIntFromTo(0, humans.size() - 1);
      Object obj = humans.get(index);
      NdPoint spacePt = space.getLocation(obj);
      Context<Object> context = ContextUtils.getContext(obj);
      context.remove(obj);
      Zombie zombie = new Zombie(space, grid);
      context.add(zombie);
      space.moveTo(zombie, spacePt.getX(), spacePt.getY());
      grid.moveTo(zombie, pt.getX(), pt.getY());

      Network<Object> net = (Network<Object>) context.getProjection("infection network");
      net.addEdge(this, zombie);
    }
  }
Пример #8
0
  public GridPoint getQueueLocation(String name, Grid grid) {
    GridPoint queueLoc = null;
    QueueSim queueR = null;
    context = ContextUtils.getContext(this);

    for (Object o : context.getObjects(QueueSim.class)) {
      queueR = (QueueSim) o;
      if (queueR.getName() == name) {
        queueLoc = grid.getLocation(o);
        // System.out.println("**** "+ queueR.getId()+ " "
        // + queueLoc);
        break;
      }
    }
    return queueLoc;
  }
Пример #9
0
  @ScheduledMethod(start = 1, interval = 1)
  public void step() {
    // get the grid location of this Zombie
    GridPoint pt = grid.getLocation(this);

    // use the GridCellNgh class to create GridCells for
    // the surrounding neighborhood .
    GridCellNgh<Human> nghCreator = new GridCellNgh<Human>(grid, pt, Human.class, 1, 1);
    List<GridCell<Human>> gridCells = nghCreator.getNeighborhood(true);
    SimUtilities.shuffle(gridCells, RandomHelper.getUniform());

    GridPoint pointWithMostHumans = null;
    int maxCount = -1;
    for (GridCell<Human> cell : gridCells) {
      if (cell.size() > maxCount) {
        pointWithMostHumans = cell.getPoint();
        maxCount = cell.size();
      }
    }
    moveTowards(pointWithMostHumans);
    infect();
  }
  @ScheduledMethod(start = 1, interval = 1)
  public void step() {

    // create colNetwork in hosting context
    Context<Object> context = ContextUtils.getContext(this);
    Network<Object> colNet = (Network<Object>) context.getProjection("collaboration_network");
    Network<Object> userNet = (Network<Object>) context.getProjection("user_network");
    Network<Object> articleNet = (Network<Object>) context.getProjection("article_network");

    if (!isDone) {
      /*
       * Neighbourhood Connection Algorithm
       */
      // get the grid location of this User
      GridPoint pt = grid.getLocation(this);

      // use the GridCellNgh class to create GridCells for
      // the surrounding neighbourhood
      if (pt != null) { // TODO Why NULL?
        GridCellNgh<Article> nghCreator =
            new GridCellNgh<Article>(
                grid, pt, Article.class, neighbourDimensions, neighbourDimensions);
        List<GridCell<Article>> gridCells = nghCreator.getNeighborhood(false);
        SimUtilities.shuffle(gridCells, RandomHelper.getUniform());

        // if an agent exist in the surrounding environment, add an edge with it.
        for (GridCell<Article> cell : gridCells) {
          if (cell.size() > 0) {
            List<Article> cellUsers = new ArrayList<Article>((Collection<Article>) cell.items());
            articleToEdit = cellUsers.get((RandomHelper.nextIntFromTo(0, cellUsers.size() - 1)));
            if (context != null && colNet != null && cellUsers != null && articleToEdit != null) {
              if (!isActiveUser) { // Good Samaritan - one and only one connection
                if (colNet.getDegree(articleToEdit) <= 0 // if neighbour is unconnected
                    && colNet.getDegree(this) <= 0) { // if our agent is unconnected)
                  colNet.addEdge(this, articleToEdit);
                  this.isDone =
                      true; // this good samaritan is no longer counted in operating agents
                }
              } else if (!hasGeneralInterest) { // Project Leader zealot (active user),
                colNet.addEdge(this, articleToEdit); // connects neighbours in every step

                for (Object coopUser : colNet.getAdjacent(articleToEdit)) {
                  if (coopUser != null && !userNet.containsEdge(userNet.getEdge(this, coopUser))) {
                    userNet.addEdge(this, coopUser);
                  }
                }
                for (Object relatedArticle : colNet.getAdjacent(this)) {
                  if (relatedArticle != null
                      && !articleNet.containsEdge(userNet.getEdge(articleToEdit, relatedArticle))) {
                    articleNet.addEdge(articleToEdit, relatedArticle);
                  }
                }
              }

              // For active agent connection algorithm we need to update good article array if found
              if (colNet.getDegree(articleToEdit)
                      > (goodArticleMultiplier * colNet.getDegree() / colNet.size())
                  && colNet.getDegree(articleToEdit) > goodArticleConnectionCount
                  && !articleToEdit.isGood) {
                articleToEdit.isGood = true;
                goodArticles.add(articleToEdit);
              }
            }
            break;
          }
        }
      }

      /*
       * Active Agent Connection Algorithm
       */
      if (isActiveUser
          && hasGeneralInterest
          && goodArticles.size() > 0) { // if in administrator career path
        articleToEdit = goodArticles.get(RandomHelper.nextIntFromTo(0, goodArticles.size() - 1));
        colNet.addEdge(this, articleToEdit); // TODO reduce goodArticles by one?

        for (Object coopUser : colNet.getAdjacent(articleToEdit)) {
          if (coopUser != null && !userNet.containsEdge(userNet.getEdge(this, coopUser))) {
            userNet.addEdge(this, coopUser);
          }
        }
        for (Object relatedArticle : colNet.getAdjacent(this)) {
          if (relatedArticle != null
              && !articleNet.containsEdge(userNet.getEdge(articleToEdit, relatedArticle))) {
            articleNet.addEdge(articleToEdit, relatedArticle);
          }
        }
        goodArticles.remove(0);
      }

      this.endRun();
    }
  }
Пример #11
0
  /**
   * Rain clouds appear with a certain chance, influenced by the weather For every rain cloud in the
   * grid the velocity of every rain object is updated Rain clouds are removed if they have passed a
   * certain time
   */
  @ScheduledMethod(start = 1, interval = 1, priority = 0)
  public void rain() {
    // Let new raingroups appear with a certain chance
    double chance = SimulationParameters.rainProb;
    // The probability of rain appearing decreases if there is already rain in the grid
    if (noRainGroups == 1) chance = (chance / (noRainGroups)) * 0.5;
    if (noRainGroups == 2) chance = (chance / (noRainGroups)) * 0.1;
    if (noRainGroups > 2) chance = (chance / (noRainGroups)) * 0.01;
    double f = urng.nextDouble();
    if (f < chance) {
      // Let rain appear
      int x = rand.nextInt((SimulationParameters.gridSize - 0) + 1);
      int y = rand.nextInt((SimulationParameters.gridSize - 0) + 1);
      int[] newLoc = {x, y};
      // Let new raingroup appear in random location
      RainGroup rg = new RainGroup(ContextUtils.getContext(this), grid, newLoc);
      noRainGroups++;
      rainGroups.add(rg);
    }

    ArrayList<RainGroup> toRemove = new ArrayList<RainGroup>();
    for (RainGroup rg : rainGroups) {
      // Get velocity vector of the rain
      float x = Wind.getWindVelocity().x;
      float y = Wind.getWindVelocity().y;
      Vector2 velRain = new Vector2(x, y);
      velRain.setLength(
          Wind.getWindVelocity().len() * 0.9f); // Rain speed is a bit lower than that of the wind

      List<Rain> toRemove1 = new ArrayList<Rain>();
      // Let rain be carried by the wind
      if (urng.nextDouble() < velRain.len()) {
        for (Rain rain : rg.getRainObjects()) {
          Directions dir = Directions.fromVectorToDir(velRain);
          GridPoint pt = grid.getLocation(rain);
          int cX = pt.getX() + dir.xDiff;
          int cY = pt.getY() + dir.yDiff;

          // If new rain-location is out of borders, delete this rain object
          // In this way the cloud "travels" out of the grid
          if (cX < 0
              || cX >= SimulationParameters.gridSize
              || cY < 0
              || cY >= SimulationParameters.gridSize) {
            toRemove1.add(rain);
          } else grid.moveTo(rain, cX, cY);
        }
      }

      for (Rain r : toRemove1) {
        rg.removeRain(r);
        TreeBuilder.performance.decreaseRainCount();
      }
    }

    // Remove the raingroups from our list which were removed from the context
    for (RainGroup rg : toRemove) {
      rainGroups.remove(rg);
      noRainGroups--;
    }
  }
Пример #12
0
 public GridPoint getLoc() {
   loc = grid.getLocation(this);
   return loc;
 }
 /**
  * Adds a car to the simulation
  *
  * @param car
  */
 private void add(Car car) {
   travelingCars.add(car);
   context.add(car);
   map.moveTo(car, car.getX(), car.getY());
 }