Exemplo n.º 1
1
  /**
   * Method to read in a vector layer
   *
   * @param layer
   * @param filename
   * @param layerDescription
   * @param attributes - optional: include only the given attributes
   */
  synchronized void readInVectorLayer(
      GeomVectorField layer, String filename, String layerDescription, Bag attributes) {
    try {
      System.out.print("Reading in " + layerDescription + "from " + filename + "...");
      File file = new File(filename);
      if (attributes == null || attributes.size() == 0) ShapeFileImporter.read(file.toURL(), layer);
      else ShapeFileImporter.read(file.toURL(), layer, attributes);
      System.out.println("done");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 2
0
  @Override
  public void receiveMessage(Message m) {
    if (m instanceof MapUpdate) {
      // int del = -1;
      for (int i = 0; i < teamPosition.size(); ++i) {
        Bag b = (Bag) teamPosition.get(i);
        if (((MapUpdate) m).sender.equals(((MapUpdate) b.get(0)).sender)) {
          // del = i;
          System.out.printf(
              "Newer map received from sender. Already collected %d positions.\n",
              ((Bag) teamPosition.get(i)).size() - 1);
          teamPosition.remove(i);
          break;
        }
      }
      // if (del != -1) {
      // }

      MapUpdate mu = (MapUpdate) m;
      // for position some more steps are needed -> wait for pings from sender while "traveling
      // around"
      Bag b = new Bag();
      b.add(mu);
      b.add(new Int2D(super.pos.x, super.pos.y));
      teamPosition.add(b);
    } else if (m instanceof Ping) {
      Ping p = (Ping) m;
      // Look for all teams that want to update the map
      for (int i = 0; i < teamPosition.size(); ++i) {
        Bag b = (Bag) teamPosition.get(i);
        if (p.sender.equals(((MapUpdate) b.get(0)).sender)) {
          boolean newPos = true;
          for (int j = 1; j < b.size(); ++j) {
            Int2D pos = (Int2D) b.get(j);
            if (pos.x == super.pos.x && pos.y == super.pos.y) {
              newPos = false;
            }
          }
          if (newPos) {
            if (b.size() < 1 + neededPositions - 1) {
              b.add(new Int2D(super.pos.x, super.pos.y));
              // System.out.printf("New position collected.\n");
            } else {
              // all needed positions collected
              MapUpdate msg = (MapUpdate) b.get(0);
              System.out.printf("Collected all needed positions!\n");
              MapUpdate answer = new MapUpdate(this, msg.sender, msg.number, null, null, true);
              sendMessage(answer);
              // System.out.printf("Sender position:
              // %d,%d.\n",msg.sender.getPos().x,msg.sender.getPos().y);
              updateBaseMap(
                  msg.map,
                  msg.agentpos,
                  posToLocalMapPos(msg.sender.getPos(), msg.sender.getLocalMapScale()));
            }
          }
        }
      }
    }
  }
Exemplo n.º 3
0
 private void chooseTarget() {
   if (target == null) {
     int num = callers.size();
     int tc = targets.size();
     int tspan = tc / num;
     target = (Int2D) targets.get(tspan * (callerNr - 1));
   } else {
     // check if target was already found
     if (baseMapGrid.get(target.x, target.y) != 0) {
       target = null;
       chooseTarget();
     }
   }
 }
Exemplo n.º 4
0
 public double[] getAgitationDistribution() {
   Bag students = buddies.getAllNodes();
   double[] distro = new double[students.numObjs];
   int len = students.size();
   for (int i = 0; i < len; i++) distro[i] = ((Student) (students.get(i))).getAgitation();
   return distro;
 }
 private void assignStudent(Student s) {
   for (int y = 0; y < dorms.size(); y++) {
     if (s.hasRoom()) {
       break;
     }
     Dorm d = (Dorm) dorms.get(y);
     if (d.isFull()) {
       continue;
     }
     if (d.isFemaleOnly() && s.getGender() == Student.Gender.MALE) {
       continue;
     }
     int i = 0;
     while (i < d.getNumRooms()) {
       if (s.hasRoom()) {
         break;
       }
       try {
         d.getRoomByIndex(i).addResident(s);
       } catch (IllegalArgumentException e) {
       }
       i++;
     }
   }
 }
Exemplo n.º 6
0
  @Override
  public void step(SimState state) {
    // System.out.println("Caller scheduled");
    updateInternalState(state);
    updatePosition();

    if (callerSteps % callers.size() == 0) {
      updateTargets(this.baseMapGrid, scale, zeroPos);
    }
    chooseTarget();
    if (target == null) {
      swarm();
    } else {
      // move to target
      boolean top = false;
      boolean left = false;
      if (target.x < pos.x) {
        left = true;
      }
      if (target.y < pos.y) {
        top = true;
      }
      // TODO
    }
    if (snr.schedule.getSteps() % 20 == 0) sendMessage(new Ping(this, (AbstractAgent) team.get(0)));
    callerSteps++;
  }
Exemplo n.º 7
0
  public void vision(SimState state, SparseGrid2D grid) {
    // System.out.println("Direction: " + direction);
    // Visual Processor

    Int2D cord = grid.getObjectLocation(this);
    assert (vP != null && cord != null);
    assert (direction != 0);
    // System.out.println(this + "was at location: " + cord);
    if (cord != null) {
      seen = vP.sight(cord.x, cord.y, state, direction);
      Bag locations = new Bag();

      // Testing Print Statements
      for (int s = 0; s < seen.size(); s++) {
        Object j = seen.get(s);
        // System.out.print(s + "saw " + seen.get(s));
        Int2D obLoc = grid.getObjectLocation(j);
        locations.add(obLoc);
        // System.out.println(" at location:" + obLoc);
        // if(j.equals(Prey.class))
        // System.out.println("****" + seen.get(s));
      } // end of for loop

      this.behaviorProb(locations, seen);

      // Move every timestep
      super.move(grid, state);
    }
  } // end of vision
Exemplo n.º 8
0
 public Caller(int teamNr, IntGrid2D baseMapGrid) {
   this.teamNr = teamNr;
   this.baseMapGrid = baseMapGrid;
   communicationRadius = 100;
   zeroPos = new Int2D(0, 0);
   callerNr = callers.size() + 1;
   callers.add(this);
 }
Exemplo n.º 9
0
 public Furniture getFurniture(int x, int y) {
   if (x < grid.getWidth() && y < grid.getHeight()) {
     Bag b = grid.getObjectsAtLocation(x, y);
     if (b != null && b.size() > 0) {
       Cell cell = (Cell) b.get(0);
       if (cell.getValue() instanceof Furniture) {
         return (Furniture) cell.getValue();
       }
     }
   }
   return null;
 }
Exemplo n.º 10
0
 private void updateBaseMap(SparseGrid2D localMap, Int2D localPos, Int2D actualPos) {
   int diffx = 0; // actualPos.x - localPos.x;
   int diffy = 0; // actualPos.y - localPos.y;
   // System.out.printf("BaseGridSize: %d,%d.\n",baseMapGrid.getWidth(),baseMapGrid.getHeight());
   // System.out.printf("Actual: %d,%d, Local: %d,%d; Diff:
   // %d,%d\n",actualPos.x,actualPos.y,localPos.x,localPos.y,diffx,diffy);
   Bag all = localMap.getAllObjects();
   for (int i = 0; i < all.size(); ++i) {
     Int2D localLoc = localMap.getObjectLocation(all.get(i));
     Int2D actualLoc = new Int2D(localLoc.x + diffx, localLoc.y + diffy);
     // System.out.printf("Bag: local: %d,%d and actual %d,%d.\n",localLoc.x,localLoc.y,
     // actualLoc.x,actualLoc.y);
     baseMapGrid.set(actualLoc.x, actualLoc.y, (Integer) ((Value) all.get(i)).get());
   }
 }
Exemplo n.º 11
0
  public void start() {
    super.start();

    // clear the yard
    yard.clear();

    // clear the buddies
    buddies.clear();

    // add some students to the yard
    for (int i = 0; i < numStudents; i++) {
      Student student = new Student();
      yard.setObjectLocation(
          student,
          new Double2D(
              yard.getWidth() * 0.5 + random.nextDouble() - 0.5,
              yard.getHeight() * 0.5 + random.nextDouble() - 0.5));

      buddies.addNode(student);
      schedule.scheduleRepeating(student);
    }

    // define like/dislike relationships
    Bag students = buddies.getAllNodes();
    for (int i = 0; i < students.size(); i++) {
      Object student = students.get(i);

      // who does he like?
      Object studentB = null;
      do {
        studentB = students.get(random.nextInt(students.numObjs));
      } while (student == studentB);
      double buddiness = random.nextDouble();
      buddies.addEdge(student, studentB, new Double(buddiness));

      // who does he dislike?
      do {
        studentB = students.get(random.nextInt(students.numObjs));
      } while (student == studentB);
      buddiness = random.nextDouble();
      buddies.addEdge(student, studentB, new Double(-buddiness));
    }
  }
Exemplo n.º 12
0
  private void setActive(EpsteinGrid epState) {
    boolean alreadyActive = false;

    if (this.active) alreadyActive = true;

    int activeV = 0;
    int copsV = 0;

    // Loop through all the agents within vision and count the number of active civilians and cops
    for (int i = 0; i < neighborsX.size(); i++) {
      int x = neighborsX.get(i);
      int y = neighborsY.get(i);
      Bag agents = epState.grid.getObjectsAtLocation(x, y);

      if (agents != null) {
        Agent agent;
        for (int j = 0; j < agents.size(); j++) {
          agent = (Agent) agents.get(j);

          if (agent instanceof Civilian && agent.active) {
            activeV++;
          } else if (agent instanceof Cop) {
            copsV++;
          }
        }
      }
    }

    /*Calculations for going active*/
    arrestProbability = 1 - Math.exp(-2.3 * ((copsV / (activeV + 1))));
    grievance = perceivedHardship * (1 - govtLegitimacy);
    this.active = (grievance - (riskAversion * arrestProbability)) > epState.threshold;

    if (!alreadyActive && this.active) {
      epState.activeCount++;
      epState.quietCount--;
    } else if (alreadyActive && !this.active) {
      epState.activeCount--;
      epState.quietCount++;
    }
  }
Exemplo n.º 13
0
  public void setupAgents(GeomVectorField populationLayer) {
    Bag nodeBag = majorRoadNodesLayer.getGeometries();

    int numNodes = nodeBag.size();
    for (Object o : populationLayer.getGeometries()) {
      MasonGeometry g = (MasonGeometry) o;
      Coordinate c = g.geometry.getCoordinate();
      for (int i = 0; i < 50; i++) {
        //				GeoNode gn = (GeoNode) nodeBag.get(random.nextInt(numNodes));
        //				Coordinate myHome = (Coordinate) gn.geometry.getCoordinate().clone();
        //				double distance = Math.abs(random.nextGaussian()) * 1500;
        //				double degrees = random.nextDouble() * 2 * Math.PI;
        //				double xOffset = distance * Math.cos(degrees) + c.x;
        double xOffset = random.nextGaussian() * 100 + c.x;
        //				double yOffset = distance * Math.sin(degrees) + c.y;
        double yOffset = random.nextGaussian() * 100 + c.y;
        Coordinate myHome = new Coordinate(xOffset, yOffset);
        Geometry point = fa.createPoint(myHome);
        if (!landArea.contains(point)) continue;
        HumanTeleporter hum = new HumanTeleporter("id_" + random.nextLong(), myHome, myHome, this);
        humans.add(hum);
      }
    }
  }
  /**
   * Assign the set of students (presumably non-incoming-freshmen, but this is not checked) passed
   * to their dorm rooms, in a way that does not take race into account. (compare {@link
   * #assignByRace}.) As a precursor (side effect) to this, any students already existing in
   * upperclass dorms will be removed.
   */
  public void assign(Bag students) {

    emptyDorms();

    // Purge all freshmen. (We're not assigning those.)
    Bag upperclassmen = null;
    try {
      upperclassmen = (Bag) students.clone();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
    for (int x = upperclassmen.size() - 1; x >= 0; x--) {
      Student s = (Student) upperclassmen.get(x);
      if (s.getGrade() < 2) {
        upperclassmen.remove(s);
      }
    }

    for (int x = 0; x < upperclassmen.size(); x++) {
      Student s = (Student) upperclassmen.get(x);
      if (s.getGrade() < 2) {
        // We're only assigning upperclassmen here.
        continue;
      }
      s.leaveRoom();
      for (int y = 0; y < dorms.size(); y++) {
        if (s.hasRoom()) {
          break;
        }
        Dorm d = (Dorm) dorms.get(y);
        if (d.isFull()) {
          continue;
        }
        if (d.isFemaleOnly() && s.getGender() == Student.Gender.MALE) {
          continue;
        }
        int i = 0;
        while (i < d.getNumRooms()) {
          if (s.hasRoom()) {
            break;
          }
          try {
            d.getRoomByIndex(i).addResident(s);
          } catch (IllegalArgumentException e) { // System.out.println(e);
          }
          i++;
        }
      }
    }

    // Error testing to see if there are upperclassmen who don't have a
    //  room/dorms that aren't full
    // int q=0;
    for (int x = 0; x < upperclassmen.size(); x++) {
      Student s = (Student) upperclassmen.get(x);
      if (!s.hasRoom()) {
        System.out.println(s + " has no upperclass dorm room!");
      }
    }
  }
 private void emptyDorms() {
   for (int y = 0; y < dorms.size(); y++) {
     Dorm d = (Dorm) dorms.get(y);
     d.emptyAllRooms();
   }
 }
  /**
   * Assign the set of students (presumably non-incoming-freshmen, but this is not checked) students
   * passed to their dorm rooms, in a way that <i>does</i> take race into account. (compare {@link
   * #assign}.) Minorities will have a higher probability of rooming with other minorities than they
   * would otherwise have had. As a precursor (side effect) to this, any students already existing
   * in upperclass dorms will be removed.
   */
  public void assignByRace(Bag upperclassmen) {
    emptyDorms();
    boolean foundRoomie;
    for (int x = 0; x < upperclassmen.size(); x++) {
      foundRoomie = false;
      Student s = (Student) upperclassmen.get(x);
      // need to leave current room so that they can get a new room
      s.leaveRoom();
      if (s.getRace() == Student.Race.MINORITY) {
        double rollDice = Sim.instance().random.nextDouble();
        if (rollDice < Sim.PROB_DUAL_MINORITY) {
          for (int m = 0; m < upperclassmen.size(); m++) {
            Student r = (Student) upperclassmen.get(m);
            // if the potential roommate is the same gender, is a
            //  minority, and has no room
            if (r.getId() == s.getId()) {
              continue;
            }
            if (r.getRace() == Student.Race.MINORITY
                && r.getGender() == s.getGender()
                && !(r.hasRoom())
                && !(s.hasRoom())) {
              // find a room that is completely empty
              foundRoomie = true;
              for (int y = 0; y < dorms.size(); y++) {
                Dorm d = (Dorm) dorms.get(y);
                if (d.isFull()) {
                  continue;
                }
                if (d.isFemaleOnly() && s.getGender() == Student.Gender.MALE) {
                  continue;
                }
                int i = 0;
                while (i < d.getNumRooms()) {
                  if (s.hasRoom() && r.hasRoom()) {
                    break;
                  }
                  try {
                    if (d.getRoomByIndex(i).isEmpty()) {
                      try {
                        d.getRoomByIndex(i).addResidents(s, r);
                      } catch (IllegalArgumentException e) {
                        System.out.println(e);
                      }
                    }
                  } catch (IllegalArgumentException e) {
                  }
                  i++;
                }
              }
              if (!s.hasRoom()) {
                // no empty room has been found to put these
                // students in; just assign them normally
                assignStudent(s);
              }
              if (!r.hasRoom()) {
                assignStudent(r);
              }
            }
          }
          if (foundRoomie == false) {
            // no same-minority, same-sex, roomless roommate found
            assignStudent(s);
          }
        } else {
          // dice roll not under PROB_DUAL_MINORITY
          assignStudent(s);
        }

      } else {
        // not a minority, assign normally
        assignStudent(s);
      }
    }
  }